Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
- **Registry: dataset mart-only**: i compose senza `clean:` non restano più fuori dal catalogo con i mart orfani. `build_clean_catalog` emette una entry dataset con metadati e `mart_refs`, senza `columns`/`location`; `registry.schema.json` rende i due campi opzionali. Così ACB/MCP vedono il dataset (`find`/`explore`) e risolvono i suoi mart (`gcs_query`).
- **`toolkit run preflight --sql-check`**: preflight con validazione SQL in due stadi. `sql_syntax` è un parse-only (`json_serialize_sql`) di clean e mart SQL, bloccante e deterministico: non richiede RAW, schema o support materializzato (i placeholder `{...}` sono neutralizzati e i riferimenti `{support.NOME}` confrontati con i support dichiarati; i commenti fuori dai letterali sono esclusi). `sql_validation` è il binding reale contro lo schema del preview, advisory e disponibile solo per le fonti CSV che espongono colonne. Il report espone anche `col_types` per fonte. Misurato sul workspace: 634/636 config passano il syntax check con 0 falsi positivi (i 2 fail sono config davvero invalidi), 1 file `PIVOT` saltato.
- **`toolkit run --dry-run` documentato** in `docs/advanced-workflows.md`: validazione del binding senza eseguire i layer, limiti dell'euristica senza schema, nota sul run record `DRY_RUN` scritto in `data/_runs`.
- **`mart_name`** (#425): pipeline mode, CLI (`toolkit inspect config --mart-name`) e MCP (`toolkit_query`) selezionano la tabella mart per nome invece che per indice. `mart_index` resta per backward compat ma e' deprecato; un nome non dichiarato fallisce con l'elenco delle tabelle disponibili.
- **Registry: codelists dai support id** (#471): `build_codelists` deriva i nomi dalle entry `support:` con `type: codelist` e `id` (fonte canonica SDMX), con fallback ai `codelists/*.csv` per i repo legacy.

### Changed

Expand All @@ -28,6 +30,7 @@
- **Warning su `all_varchar` + `columns` insieme**: DuckDB usa solo `columns` (i tipi dichiarati) e ignora `all_varchar`. Il toolkit ora avvisa invece di lasciare l'opzione senza effetto.
- **Layering ripristinato** (PR #504): rimosse 6 inversioni di dipendenza `core → clean/domain/scout/scaffold`. `sql_validation` spostato in `domain/`, orchestration support in `domain/support.py`, `ProbePool` in `scout/pool.py`, scaffold clean.sql spostato da `raw/run.py` a `cmd_run` (comportamento invariato). Contratto condiviso `dataset_yml_slug`/`iter_workspace_dataset_ymls` in `registry/layout.py`.
- **Catalogo unico tipi fonte** (PR #505): nuovo `toolkit/core/source_types.py` come single source of truth per registry plugin, dispatch fetch e contratto AI (`contracts._SOURCE_TYPES` generato). Eliminato `_fetch_fallback` (tipo sconosciuto → `ValueError` esplicito). Tipo `script` documentato nel contratto con nota di sicurezza.
- **Run MART** (#426): i parquet non piu' dichiarati in `dataset.yml` vengono rimossi dal run (per-anno e multi-year), cosi' una tabella rinominata non lascia il vecchio file a inquinare il layer tool.

### Fixed

Expand Down
68 changes: 68 additions & 0 deletions tests/test_mart_multi_year.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,74 @@ def test_mart_multi_year_on_project_example(project_example: Path) -> None:
assert any(t.get("years") == [2022, 2023] for t in tables), "years missing from metadata"


def _add_multi_year_table(project_example: Path) -> None:
"""Aggiunge a project_example la tabella multi-year ``clean_union``."""
sql_dir = project_example / "sql" / "multi_year"
sql_dir.mkdir(parents=True, exist_ok=True)
(sql_dir / "clean_union.sql").write_text(
"\n".join(
[
"select",
" count(*) as rows_total,",
" count(distinct anno) as anni_distinti",
"from clean_input",
]
),
encoding="utf-8",
)
config_path = project_example / "dataset.yml"
config_data = yaml.safe_load(config_path.read_text(encoding="utf-8"))
config_data["dataset"]["years"] = [2022, 2023]
config_data.setdefault("mart", {}).setdefault("tables", []).append(
{
"name": "clean_union",
"sql": "sql/multi_year/clean_union.sql",
"years": [2022, 2023],
}
)
config_path.write_text(
yaml.dump(config_data, default_flow_style=False, allow_unicode=True, sort_keys=False),
encoding="utf-8",
)


def test_mart_multi_year_cleanup_rimuove_stale(project_example: Path) -> None:
"""#426: la pulizia copre anche la dir multi-year (dataset-level)."""
_add_multi_year_table(project_example)
config_path = project_example / "dataset.yml"
run_cmd(step="all", config=str(config_path))

mart_dir = project_example / "_smoke_out" / "data" / "mart" / "project_example"
stale = mart_dir / "mart_vecchia.parquet"
stale.write_bytes(b"stale")

run_cmd(step="mart", config=str(config_path))

assert not stale.exists(), "il parquet non dichiarato va rimosso anche a livello dataset"
assert (mart_dir / "clean_union.parquet").exists()
assert (mart_dir / "2022" / "rd_by_regione.parquet").exists()


def test_clean_preview_mart_name_multi_year(project_example: Path) -> None:
"""#425: ``mart_name`` seleziona anche una tabella multi-year."""
from toolkit.domain.layer import clean_preview

_add_multi_year_table(project_example)
config_path = project_example / "dataset.yml"
run_cmd(step="all", config=str(config_path))

result = clean_preview(
str(config_path), layer="mart", mart_name="clean_union", year=2022, limit=5
)
assert result["mart_name"] == "clean_union"
assert result["columns"]

with pytest.raises(ValueError, match="non dichiarata"):
clean_preview(
str(config_path), layer="mart", mart_name="mart_inesistente", year=2022, limit=5
)


def test_mart_only_multi_year(project_example: Path) -> None:
"""Solo tabelle multi-year: il run per-anno non deve fallire (issue #445).

Expand Down
25 changes: 25 additions & 0 deletions tests/test_mcp_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -752,3 +752,28 @@ def test_dataset_status_shape(tmp_path, monkeypatch):
for section in ("paths_info", "summary", "readiness", "run_stats", "info"):
assert section in result
assert result["info"]["dataset"] == dataset


def test_clean_preview_mart_name(
mcp_project_example: tuple[Path, str, int],
) -> None:
"""Issue #425: selezione della tabella mart per nome, non per indice."""
from toolkit.mcp.errors import ToolkitClientError
from toolkit.mcp.schema_ops import clean_preview

config_path, dataset, year = mcp_project_example
root = Path(config_path).parent / "_smoke_out"
mart_dir = root / "data" / "mart" / dataset / str(year)
mart_dir.mkdir(parents=True, exist_ok=True)
_make_parquet(mart_dir / "rd_by_regione.parquet")
_make_parquet(mart_dir / "rd_by_provincia.parquet")

result = clean_preview(
str(config_path), layer="mart", mart_name="rd_by_provincia", year=year, limit=5
)
assert result["mart_name"] == "rd_by_provincia"

with pytest.raises(ToolkitClientError, match="non dichiarata"):
clean_preview(
str(config_path), layer="mart", mart_name="mart_inesistente", year=year, limit=5
)
45 changes: 45 additions & 0 deletions tests/test_pipeline_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,3 +342,48 @@ def test_run_mart_supports_support_placeholder(tmp_path: Path) -> None:
f"SELECT marker FROM read_parquet('{mart_output.as_posix()}')"
).fetchone() == ("ok",)
assert result["output_rows"] == 1


def test_run_mart_rimuove_output_non_dichiarati(project_example: Path, monkeypatch) -> None:
"""Issue #426: il run mart elimina i parquet non piu' dichiarati."""
_simplify_sql_project(project_example)
config_path = project_example / "dataset.yml"

monkeypatch.chdir(project_example)
cfg = load_config(config_path)
year = cfg.years[0]
logger = NoopLogger()

run_raw(
cfg.dataset,
year,
cfg.root,
cfg.raw,
logger,
base_dir=cfg.base_dir,
output_cfg=cfg.output,
clean_cfg=cfg.clean,
)
run_profile_fn(cfg, [year], logger)
run_clean(
cfg.dataset, year, cfg.root, cfg.clean, logger, base_dir=cfg.base_dir, output_cfg=cfg.output
)

mart_dir = Path(cfg.root) / "data" / "mart" / cfg.dataset / str(year)
mart_dir.mkdir(parents=True, exist_ok=True)
stale = mart_dir / "mart_vecchia.parquet"
stale.write_bytes(b"stale")

run_mart(
cfg.dataset,
year,
cfg.root,
cfg.mart,
logger,
base_dir=cfg.base_dir,
clean_cfg=cfg.clean,
output_cfg=cfg.output,
)

assert not stale.exists(), "il parquet non dichiarato deve essere rimosso"
assert (mart_dir / "rd_by_regione.parquet").exists()
84 changes: 84 additions & 0 deletions tests/test_registry_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -590,6 +590,90 @@ def test_registry_builder_imports() -> None:
# ---------------------------------------------------------------------------


@pytest.mark.contract
def test_codelists_from_support_ids(tmp_path: Path) -> None:
"""codelists derivate dai support id (SDMX), con fallback ai CSV repo."""
from toolkit.registry.builders import build_codelists

ds_dir = tmp_path / "datasets" / "demo"
ds_dir.mkdir(parents=True)
(ds_dir / "dataset.yml").write_text(
"""
root: "../../out"
schema_version: 1
dataset:
name: demo_sdmx
years: [2024]
support:
- name: freq
type: codelist
provider: sdmx
agency: ESTAT
id: FREQ
- name: unit
type: codelist
provider: sdmx
agency: ESTAT
id: unit
- name: comuni
type: dataset
config: "../support_datasets/comuni/dataset.yml"
years: [2024]
""",
encoding="utf-8",
)
cl_dir = tmp_path / "codelists"
cl_dir.mkdir()
(cl_dir / "geo.csv").write_text("code,label_en\nIT,Lombardia\n", encoding="utf-8")

layout = RepoLayout(
repo_root=tmp_path,
dataset_dirs=("datasets",),
source_repo="dataciviclab/demo",
)
payload, errors = build_codelists(layout)
assert errors == {"derive": [], "validation": []}, f"errori inattesi: {errors}"
assert payload["codelists"] == ["freq", "geo", "unit"]


@pytest.mark.contract
def test_support_without_type_is_not_a_codelist(tmp_path: Path) -> None:
"""Un support senza `type` vale "dataset": il suo `id` non è una codelist.

In ``core/config.py`` il tipo mancante diventa ``"dataset"``. Se il
support porta anche un ``id`` (campo che il modello non vieta), non deve
finire nella sezione codelists.
"""
from toolkit.registry.builders import build_codelists

ds_dir = tmp_path / "datasets" / "demo"
ds_dir.mkdir(parents=True)
(ds_dir / "dataset.yml").write_text(
"""
root: "../../out"
schema_version: 1
dataset:
name: demo_senza_type
years: [2024]
support:
- name: comuni
config: "../support_datasets/comuni/dataset.yml"
years: [2024]
id: NON_E_UNA_CODELIST
""",
encoding="utf-8",
)

layout = RepoLayout(
repo_root=tmp_path,
dataset_dirs=("datasets",),
source_repo="dataciviclab/demo",
)
payload, errors = build_codelists(layout)
assert errors == {"derive": [], "validation": []}, f"errori inattesi: {errors}"
assert payload["codelists"] == []


@pytest.mark.contract
def test_codelists_contract(tmp_path: Path) -> None:
"""codelists espone i NOMI dei codelist del repo (contract)."""
Expand Down
6 changes: 5 additions & 1 deletion toolkit/cli/inspect/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,10 @@ def inspect_config(
year: int = typer.Option(0, "--year", "-y", help="Anno"),
sql: str | None = typer.Option(None, "--sql", help="SQL query (mode=sql)"),
limit: int = typer.Option(20, "--limit", help="Max righe (mode=preview/sql)"),
mart_index: int = typer.Option(0, "--mart-index", help="Indice tabella mart"),
mart_index: int = typer.Option(0, "--mart-index", help="Indice tabella mart (deprecato)"),
mart_name: str | None = typer.Option(
None, "--mart-name", help="Nome tabella mart (es. mart_comuni)"
),
diff: bool = typer.Option(False, "--diff", help="Schema-diff RAW tra anni"),
json_output: bool = typer.Option(False, "--json", help="Output JSON"),
):
Expand All @@ -67,6 +70,7 @@ def inspect_config(
sql=sql,
limit=limit,
mart_index=mart_index,
mart_name=mart_name,
diff=diff,
json_output=json_output,
)
Expand Down
6 changes: 5 additions & 1 deletion toolkit/cli/inspect/config_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,10 @@ def config(
year: int = typer.Option(0, "--year", "-y", help="Anno (default: ultimo configurato)"),
sql: str | None = typer.Option(None, "--sql", help="SQL query (solo mode=sql)"),
limit: int = typer.Option(20, "--limit", help="Max righe (solo mode=preview/sql)"),
mart_index: int = typer.Option(0, "--mart-index", help="Indice tabella mart (default 0)"),
mart_index: int = typer.Option(0, "--mart-index", help="Indice tabella mart (deprecato)"),
mart_name: str | None = typer.Option(
None, "--mart-name", help="Nome tabella mart (es. mart_comuni)"
),
diff: bool = typer.Option(False, "--diff", help="Schema-diff RAW tra anni"),
json_output: bool = typer.Option(False, "--json", help="Output JSON"),
) -> None:
Expand Down Expand Up @@ -122,6 +125,7 @@ def config(
limit=limit,
sql=sql,
mart_index=mart_index,
mart_name=mart_name,
)
except (ValueError, FileNotFoundError) as exc:
if json_output:
Expand Down
Loading