diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 3e0fbe8..e52b5e3 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "data-toolkit", - "version": "0.8.9", + "version": "0.8.10", "description": "Extract, tidy, reconcile, analyse, visualise and convert messy data into clean, validated, audit-ready tables and insight briefs \u2014 computed by a deterministic engine that runs on your machine, with no third-party services. From Phronesis Applied.", "author": { "name": "Phronesis Applied", diff --git a/CHANGELOG.md b/CHANGELOG.md index 68647a1..123479b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,39 @@ # Changelog +## 0.8.10 — 2026-10-12 + +- **`data-convert` refuses to write over source drift.** `convert_file` previously blocked only + on contract errors; a mapped source column that was missing or renamed (a sense-check + `error`) still produced output with that column blank. Any sense-check `error` now blocks the + write too: `report["blocked"] = True`, `report["written"] = []`, and a new + `report["blocked_by"]` lists `"contract"` and/or `"sense_check"`. The report is still + produced; `render_report` states the blocking reason(s); the CLI exits 1 when blocked. +- **Date-keyed FX never invents a rate.** With a pinned `fx.rates` table, a row dated before + every pinned rate, or with a blank/unparseable date, was silently converted at the earliest + (or latest) rate. Such cells are now left **blank** and flagged `fx_rate_unresolved` + (severity `warning`, with row and field) in the report's `issues`. Rate selection parses + dates (ISO, DD MMM YYYY, dd/mm/yyyy, Excel serial — via the shared `dataclean.parse_date`) + instead of comparing strings. A single pinned `fx.rate` still applies to every row; a + `fx_convert` with no pinned rate still raises. New helpers `_to_date` and `_fx_resolve`; + `_field` / `apply_map` gain optional `flags=` / `issues=` (defaults unchanged). +- **Stale-FX sense-check parses dates.** The check was a raw string compare and gave the wrong + answer for DD MMM YYYY dates (e.g. `"30 Jun 2026" < "2026-07-01"` is false). Both sides are + now parsed; a `rates` table is judged by its latest `as_of`; an unparseable date raises a new + `fx_date_unparsed` warning instead of passing silently. `--as-of` help clarified. +- **`ingest.read_large_rows(path, sheet=None, cache_dir=None)`** — additive drop-in for + `read_any` on big files: returns `(rows, note)` in the same list-of-rows shape (header first, + missing cells as `""`). `.xlsx`/`.xlsm` go through `read_large` (Parquet cache / streaming); + any other type falls back to `read_any`, so it never raises just because the file is not + Excel. `read_large` itself stays Excel-only. +- Docs: `data-convert` SKILL.md / `conversion-spec.md` (default `flag`, stale rule, + `--as-of` / `run_dates_after` on the call lines, blocking, unresolved FX); + `data-analyse` / `data-tidy` SKILL.md and `large-file-patterns.md` (which reader: + `read_large_rows` vs `read_large`). +- Tests: 4 new engine tests (suite 116 → 120) + extended `convert.py --self-test`. + +All changes are backward-compatible at the API level; the behavioural changes are the +blocked write on sense-check errors (exit 1) and blank-plus-flag for unresolvable FX rows. + ## 0.8.9 — 2026-10-06 - **Done-when gates added to `data-reconcile`, `data-convert` and `data-visualise`.** A diff --git a/scripts/ingest.py b/scripts/ingest.py index 810f06e..4a72e65 100644 --- a/scripts/ingest.py +++ b/scripts/ingest.py @@ -2,12 +2,13 @@ text, so the diversity of inputs lives here and the cleanup pipeline (dataclean.py) stays one shared path. Used by `data-tidy` (clean tabular data) and `data-extract` (get data out of documents). Lives at the toolkit-root `scripts/`; skills import it by adding -`../../scripts` to sys.path (run from the skill directory). +`[skill]/../../scripts` (absolute) to sys.path, so commands can run from the work folder. - from ingest import read_any, read_large, read_paste, read_text, list_sheets, list_pdf_tables, ocr_available + from ingest import read_any, read_large, read_large_rows, read_paste, read_text, list_sheets, list_pdf_tables, ocr_available rows, note = read_any("export.xlsx") # or .csv/.tsv, a .pdf, a .docx, a .msg, a .pptx rows, note = read_any("book.xlsx", sheet="Q2") # pick a tab in a multi-sheet workbook df, note = read_large("ledger.xlsx") # 10k+ rows: strategy gate + Parquet cache/stream + rows, note = read_large_rows("ledger.xlsx") # same, but rows shaped like read_any (any ext) sheets = list_sheets("book.xlsx") # discover tabs (name/size/hidden/empty) rows, note = read_paste(pasted_text) # markdown / tab / csv-ish pasted table text, note = read_text("form.pdf") # document -> plain text (OCR fallback) @@ -206,6 +207,38 @@ def read_large(path: str, sheet=None, cache_dir=None): return df, note +def read_large_rows(path: str, sheet=None, cache_dir=None): + """Drop-in for ``read_any`` on big files → ``(rows, note)`` in the SAME shape as + ``read_any`` (list of row lists, header row first), so the rest of the workflow + (``dataclean.detect_header`` / ``profile_table`` / ``analyse``) is unchanged. + + ``.xlsx``/``.xlsm`` go through ``read_large`` (Parquet cache / streaming when pandas+pyarrow + are installed); a DataFrame result is converted as ``[list(df.columns)] + df.values.tolist()`` + with missing cells (None/NaN/NaT) as ``""``. Any other type (``.csv``, ``.pdf`` …) is read + with ``read_any`` — it never raises just because the file is not Excel.""" + ext = Path(path).suffix.lower() + if ext not in (".xlsx", ".xlsm"): + rows, note = read_any(path, sheet=sheet) + return rows, note + " (read_large_rows: non-Excel source read directly)" + frame, note = read_large(path, sheet=sheet, cache_dir=cache_dir) + if isinstance(frame, list): # fallback path already returns rows + return frame, note + + def _cell(v): + if v is None: + return "" + try: + if v != v: # NaN / NaT + return "" + except (TypeError, ValueError): # pandas.NA refuses bool() + return "" if repr(v) == "" else v + return v + + rows = [[str(c) for c in frame.columns]] + rows += [[_cell(v) for v in rec] for rec in frame.astype(object).values.tolist()] + return rows, note + + def read_csv(path: str): with open(path, "r", encoding="utf-8-sig", errors="replace", newline="") as f: sample = f.read(4096) diff --git a/skills/data-analyse/SKILL.md b/skills/data-analyse/SKILL.md index 2fd45df..fede671 100644 --- a/skills/data-analyse/SKILL.md +++ b/skills/data-analyse/SKILL.md @@ -55,10 +55,14 @@ header_rows, note = ingest.read_any(path) # xlsx/csv/pdf/docx/msg; read_past Multi-tab workbooks: `read_any` raises `SheetSelectionRequired` if several tabs hold data — list the sheets and ask, don't guess. -For files with 10k+ rows, use `ingest.read_large` instead of `read_any` to avoid OOM. See -`references/large-file-patterns.md` for vectorised operation guidance. - -**Done when:** you have `(header_rows, note)` from `read_any` (or `read_large` for 10k+ rows). If `SheetSelectionRequired` was raised, the user has chosen a sheet. `note` has been read for source-quality flags. +For files with 10k+ rows, use `ingest.read_large_rows(path)` instead of `read_any` — a drop-in +that returns the same `(header_rows, note)` shape (Parquet cache / streaming for `.xlsx`; any +other type falls back to `read_any`). `ingest.read_large` is the DataFrame variant and is +**`.xlsx`/`.xlsm` only** (raises on `.csv`); convert its result with +`header, rows = list(df.columns), df.values.tolist()`. See `references/large-file-patterns.md` +for vectorised operation guidance. + +**Done when:** you have `(header_rows, note)` from `read_any` (or `read_large_rows` for 10k+ rows). If `SheetSelectionRequired` was raised, the user has chosen a sheet. `note` has been read for source-quality flags. ### 2 — Profile & quality gate `dataclean.profile_table(header, rows)` / `score_quality(...)` — column types, missing %, diff --git a/skills/data-analyse/references/large-file-patterns.md b/skills/data-analyse/references/large-file-patterns.md index 013292f..950a031 100644 --- a/skills/data-analyse/references/large-file-patterns.md +++ b/skills/data-analyse/references/large-file-patterns.md @@ -1,6 +1,6 @@ # Large-file patterns — vectorised operations cheat sheet -Use with `ingest.read_large` when a source has **10k+ rows**. Prefer vectorised pandas / +Use with `ingest.read_large_rows` / `ingest.read_large` when a source has **10k+ rows**. Prefer vectorised pandas / NumPy ops over Python row loops — a 200k-row ledger that finishes in seconds with the left-hand forms can take minutes (or OOM) with the right-hand forms. @@ -12,15 +12,23 @@ left-hand forms can take minutes (or OOM) with the right-hand forms. | `np.where(df['a'] > 0, 'Y', 'N')` | `df['a'].map(lambda ...)` | `np.where` / boolean assignment beats per-cell Python callables | | `df.groupby('a').agg({'b': 'sum'})` | `df.groupby('a').apply(custom_func)` | Named aggregations use the fast path; `apply` falls back to Python | -## Scope: `read_large` is Excel-only — CSV goes through `read_any` +## Which reader? `read_large_rows` (drop-in) vs `read_large` (DataFrame) -`ingest.read_large` (the Parquet cache / stream path above) supports **`.xlsx` / `.xlsm` only**. -A large **CSV** is read by `ingest.read_any`, whose single-pass `csv.reader` returns list-of-rows -— fast (a 250k-row CSV ingests in well under a second) and the shape the analyse engine expects. +- **`ingest.read_large_rows(path, sheet=None)` → `(rows, note)`** — the drop-in for `read_any`: + the same list-of-rows shape (header row first), so `dataclean` / `analyse` run unchanged. Excel + goes through the Parquet cache / stream path below; any other type (`.csv`, `.pdf` …) is read + with `read_any`, so it never raises just because the file isn't Excel. +- **`ingest.read_large(path, sheet=None)` → `(DataFrame, note)`** — **`.xlsx` / `.xlsm` only** + (raises `ValueError` on `.csv` and other extensions). Use it when you want pandas for the + vectorised ops above. Without pandas/pyarrow it falls back to `(rows, note)` from `read_xlsx`. + To hand a DataFrame back to the row-based engines: + `header, rows = list(df.columns), df.values.tolist()`. + +A large **CSV** is read by `ingest.read_any` (or `read_large_rows`), whose single-pass +`csv.reader` returns list-of-rows — fast (a 250k-row CSV ingests in well under a second). Ingestion is not the bottleneck at this scale; there is no chunked/pyarrow CSV path today, so a genuinely memory-bound CSV (millions of rows) should be pre-split or loaded via your own -`pandas.read_csv(chunksize=…)` outside the toolkit. Don't assume `read_large` will take a CSV — -it raises `ValueError` on non-Excel extensions. +`pandas.read_csv(chunksize=…)` outside the toolkit. ## Strategy reminder (`scripts/streaming.py`) @@ -35,5 +43,5 @@ low-cardinality object columns) — typically **50–80%** memory reduction. ## Optional deps -`pyarrow` + `pandas` are optional. Without them `ingest.read_large` falls back to a -direct openpyxl read and warns that large files may OOM. See `README.md#mode--environment-compatibility`. +`pyarrow` + `pandas` are optional. Without them `ingest.read_large` / `read_large_rows` fall back to a +direct openpyxl read and warn that large files may OOM. See `README.md#mode--environment-compatibility`. diff --git a/skills/data-convert/SKILL.md b/skills/data-convert/SKILL.md index eae3a46..2d53d14 100644 --- a/skills/data-convert/SKILL.md +++ b/skills/data-convert/SKILL.md @@ -23,7 +23,7 @@ clean result. > **Two jobs, often combined:** > 1. **Contract mapping** — map a source onto *another system's* import contract (columns, order, > types, required fields). Unmapped sources are reported; required-but-missing rows follow -> `rules.on_missing_required` (`flag` / `exclude` / `error`) — never invent values. +> `rules.on_missing_required` (`flag` / `exclude` / `error`; default `flag`) — never invent values. > 2. **Structural reshape** — `unpivot` (wide→long), `pivot` (long→wide), `flatten`/`nest` > (JSON↔table), `split` (one file→many by a key), `union` (many→one with column alignment). @@ -51,23 +51,33 @@ or the field list), and the user has confirmed the proposed mapping before any f `convert_[name].md` in the working folder). If one does, **do not blind-run it**: 1. Load it (`load_spec`) and read its **Mapping** + **Expected source**. 2. **Sense-check today's source against it** (`sense_check(spec, header, rows)` / - `convert.py --card card.md --check-only`). + `convert.py --card card.md --check-only`), passing the run's as-of date — + `sense_check(spec, header, rows, run_dates_after="30 Jun 2026")` / `--as-of "30 Jun 2026"` + (ISO or DD MMM YYYY; the date the conversion must be current for, e.g. the period end). 3. **Flag any discrepancy to the user** — a mapped column missing/renamed, a new column, a required field now empty, or a **stale pinned rate** — and let them decide: proceed / adjust / - regenerate. Never apply over drift silently. + regenerate. Never apply over drift silently. **Stale rule:** a pinned rate is "old" when its + `as_of` (for a `rates` table, the latest `as_of`) is earlier than the run's as-of date; both + dates are parsed, never compared as text. ### 3. Apply (deterministic) ```python spec = load_spec("convert_gl_to_journal.md") # or a dict you just built + confirmed -report = convert_file(spec, "gl_export.xlsx", "journal_import.csv") +report = convert_file(spec, "gl_export.xlsx", "journal_import.csv", + run_dates_after="30 Jun 2026") # the run's as-of date (stale-FX check) print(render_report(report, name=spec["name"])) ``` Or one-shot from the CLI: -`python scripts/convert.py gl_export.xlsx --card convert_gl_to_journal.md -o journal_import.csv` +`python scripts/convert.py gl_export.xlsx --card convert_gl_to_journal.md -o journal_import.csv --as-of "30 Jun 2026"` The engine reads the source (any format via the shared `ingest`), runs any reshape ops, maps to the target contract, and writes the target format (`csv` / `json` / `xlsx`). It reports rows in/out, the **sense-check**, unmapped source columns and required-but-missing target fields. +**Nothing is written** (`report["blocked"]`, CLI exit code 1) when the sense-check or the contract +has an `error` — e.g. a mapped source column that is missing or renamed, which would otherwise be +written blank; the report still lists why. With a date-keyed `fx.rates` table, a row dated +before every pinned rate (or with a blank/unparseable date) is left **blank and flagged** +(`fx_rate_unresolved`), never converted at a guessed rate. **Done when:** `report["sense_check"]` is clean (or every discrepancy has been flagged to the user and resolved), the target file is written, and the report's unmapped-column / @@ -97,7 +107,8 @@ on that. When a conversion needs a live value (e.g. a USD→GBP rate): decides** whether to apply it (confirm-first); - the value is **pinned into the card** (`fx: {pair, rate, as_of, source}`) and applied by the engine as a **recorded constant**, so a re-run is deterministic and auditable; -- refreshing is a deliberate act — the sense-check flags a pinned rate that's old for the run. +- refreshing is a deliberate act — the sense-check flags a pinned rate that's old for the run + (its `as_of` is earlier than the run's `--as-of` date). Fetching a public rate is a public lookup, not egress of the user's data — the dataset never leaves. Never send the actual rows to an external service to "convert" them. @@ -121,7 +132,8 @@ Ready-made example contracts: `references/contracts/journal-import.md`, ## Safety - **Deterministic & human-in-the-loop** — the engine applies a confirmed spec; it never invents a value. Output is a **draft for review**, not a posting or an upload — a person submits it. -- **Never blind-applies** — a drifted source is flagged, not force-converted. +- **Never blind-applies** — a drifted source is flagged, not force-converted: a missing or + renamed mapped column blocks the write. ## Files diff --git a/skills/data-convert/references/conversion-spec.md b/skills/data-convert/references/conversion-spec.md index d7b867e..9ba5192 100644 --- a/skills/data-convert/references/conversion-spec.md +++ b/skills/data-convert/references/conversion-spec.md @@ -77,9 +77,13 @@ user's intent, confirm it, then `convert_file(spec, in, out)`. "as_of": "2026-07-15", "source": "" }`, or a **date-keyed table** for per-row conversion by transaction date: `{ "pair": "USD/GBP", "rates": [ {"as_of":"2026-01-01","rate":"0.80"}, {"as_of":"2026-06-01","rate":"0.75"} ] }` — with `compute:"fx_convert"` setting `on_date` to - the row's date column (the latest rate whose `as_of` ≤ the row date is used). The engine - **never fetches** — the agent fetches on the user's instruction, the user approves, and it's - recorded here. + the row's date column (the latest rate whose `as_of` ≤ the row date is used; dates are parsed + — ISO, DD MMM YYYY, dd/mm/yyyy — never compared as text). A row dated **before every pinned + rate**, or with a blank/unparseable date, is left **blank and flagged** (`fx_rate_unresolved`) + — never converted at the nearest rate. The engine **never fetches** — the agent fetches on the + user's instruction, the user approves, and it's recorded here. **Stale rule:** pass the run's + as-of date (`run_dates_after=` / CLI `--as-of`); a pinned `as_of` (for a table, the latest one) + earlier than that date is flagged `stale_fx`. - **standing_rules** — a string list of user confirm-first rules to preserve across sessions. `render_card` always emits them as a **Standing rules** section so later agents do not have to rediscover policy from chat history. @@ -163,9 +167,10 @@ Beyond `required`, a target column can carry validators; violations surface in t ## How it's reported -- **Sense-check** (run against the card before applying): a mapped source column missing/renamed, - a new column, an expected column gone, or a **stale pinned rate** → surfaced to the user; the - engine does **not** auto-apply over drift. +- **Sense-check** (run against the card before applying): a mapped source column missing/renamed + (`error`), a new column, an expected column gone, or a **stale pinned rate** (`warn`) → + surfaced to the user; the engine does **not** auto-apply over drift — any sense-check `error` + **blocks the write** (`report["blocked"]`, CLI exit 1) and the report says why. - **Contract issues**: a required target field unmapped → `error`; a required field blank on a row → handled by `on_missing_required` (`flag` / `exclude` / `error`); a validator violation (`allowed`/`pattern`/`max_len`/`check`) → `error`; a source column the diff --git a/skills/data-convert/scripts/convert.py b/skills/data-convert/scripts/convert.py index 8c2a134..dc9d714 100644 --- a/skills/data-convert/scripts/convert.py +++ b/skills/data-convert/scripts/convert.py @@ -262,29 +262,69 @@ def load_lookups(mapping, base_dir=None): return out -def _fx_rate(fx, row, spec): - """The rate to apply: a single pinned `fx.rate`, or the row-date-effective rate from a pinned - `fx.rates` table (latest as_of <= the row's `on_date`). The engine never fetches.""" - if not fx: +def _to_date(v): + """Parse a date (ISO, DD MMM YYYY, dd/mm/yyyy, Excel serial, ...) -> date | None. Uses the + shared dataclean parser (dayfirst) when present, else ISO only. Never compares raw strings.""" + import datetime as _dt + if isinstance(v, _dt.datetime): + return v.date() + if isinstance(v, _dt.date): + return v + if _s(v) == "": return None + dc, _ = _load_engine() + if dc is not None: + d, _note = dc.parse_date(v, dayfirst=True) + return d + try: + return _dt.date.fromisoformat(_s(v)[:10]) + except ValueError: + return None + + +def _fx_resolve(fx, row, spec): + """(rate | None, problem | None). A single pinned `fx.rate` always applies. From a pinned + `fx.rates` table the row-date-effective rate is used (latest as_of <= the row's `on_date`, + dates parsed, not string-compared). Never invents: a row date that is blank/unparseable, or + that predates every pinned rate, resolves to (None, reason) — the caller leaves the cell + blank and flags it. With a table but no `on_date`, the latest pinned rate applies.""" + if not fx: + return None, None if fx.get("rate") not in (None, ""): - return Decimal(str(fx["rate"])) + return Decimal(str(fx["rate"])), None rates = fx.get("rates") - if rates: - on = spec.get("on_date") - d = _fmt_date(row.get(on), {"format": "%Y-%m-%d"}) if on else None - eligible = [r for r in rates if (not d or _s(r.get("as_of")) <= d)] - chosen = (max(eligible, key=lambda r: _s(r.get("as_of")), default=None) - or min(rates, key=lambda r: _s(r.get("as_of")), default=None)) - return Decimal(str(chosen["rate"])) if chosen else None - return None + if not rates: + return None, None + dated = [(_to_date(r.get("as_of")), r) for r in rates] + dated = [(d, r) for d, r in dated if d is not None] + if not dated: + return None, "no pinned fx.rates entry has a parseable as_of date" + on = spec.get("on_date") + if not on: + return Decimal(str(max(dated, key=lambda t: t[0])[1]["rate"])), None + raw = row.get(on) + d = _to_date(raw) + if d is None: + return None, f"row date {_s(raw)!r} in '{on}' is blank or unparseable — no rate applied" + eligible = [(rd, r) for rd, r in dated if rd <= d] + if not eligible: + first = min(rd for rd, _ in dated) + return None, (f"row date {d:%d %b %Y} predates the earliest pinned rate " + f"({first:%d %b %Y}) — no rate applied") + return Decimal(str(max(eligible, key=lambda t: t[0])[1]["rate"])), None + + +def _fx_rate(fx, row, spec): + """The rate to apply, or None when it can't be resolved (see `_fx_resolve`). The engine + never fetches.""" + return _fx_resolve(fx, row, spec)[0] # --------------------------------------------------------------------------- # # Stage 2 — map onto the target contract. # mapping: {target_col: {from, compute?, type?, format?, dp?, const?, sep?, ...}} # --------------------------------------------------------------------------- # -def _field(row, spec, fx=None, lookup=None): +def _field(row, spec, fx=None, lookup=None, flags=None): comp = spec.get("compute", "as_is") frm = spec.get("from") if "const" in spec: @@ -297,9 +337,13 @@ def _field(row, spec, fx=None, lookup=None): elif comp == "concat": return spec.get("sep", " ").join(_s(row.get(x)) for x in frm) elif comp == "fx_convert": - rate = _fx_rate(fx, row, spec) - if rate is None: + rate, problem = _fx_resolve(fx, row, spec) + if rate is None and problem is None: raise ValueError("compute 'fx_convert' needs a pinned fx.rate (or fx.rates + on_date)") + if rate is None: # never invent: blank + flagged + if flags is not None: + flags.append(problem) + return "" n = _num(row.get(frm)) return _fmt_number((n * rate) if n is not None else None, spec) elif comp == "lookup": @@ -321,11 +365,24 @@ def _field(row, spec, fx=None, lookup=None): return _s(raw) -def apply_map(header, rows, mapping, fx=None, lookups=None): - """Produce (target_header, target_rows) by applying `mapping` to each source row.""" +def apply_map(header, rows, mapping, fx=None, lookups=None, issues=None): + """Produce (target_header, target_rows) by applying `mapping` to each source row. Pass a list + as `issues` to receive per-cell flags (e.g. an FX rate that could not be resolved for a row's + date — that cell is left blank, never filled with a guessed rate).""" lookups = lookups or {} tcols = list(mapping.keys()) - out = [{tc: _field(r, sp, fx, lookups.get(tc)) for tc, sp in mapping.items()} for r in rows] + out = [] + for idx, r in enumerate(rows): + rec = {} + for tc, sp in mapping.items(): + flags = [] + rec[tc] = _field(r, sp, fx, lookups.get(tc), flags) + if issues is not None: + for f in flags: + issues.append({"kind": "fx_rate_unresolved", "severity": "warning", + "row": idx + 1, "fields": [tc], + "detail": f"row {idx + 1}, '{tc}' left blank: {f}"}) + out.append(rec) return tcols, out @@ -581,11 +638,29 @@ def sense_check(spec, header, rows, run_dates_after=None): if col not in header: issues.append({"kind": "expected_column_gone", "severity": "warn", "detail": f"card expects '{col}', absent from this source"}) + # Stale-rate rule: a pinned rate is "old" when its as_of date is strictly EARLIER than the + # run's as-of date (`run_dates_after` — the date the conversion should be current for, e.g. + # the period end or latest transaction date). Both sides are parsed as dates (ISO, + # DD MMM YYYY, dd/mm/yyyy ...), never string-compared. A `rates` table is judged by its + # latest as_of. An unparseable date is flagged rather than silently passed. fx = spec.get("fx") - if fx and fx.get("as_of") and run_dates_after and fx["as_of"] < run_dates_after: - issues.append({"kind": "stale_fx", "severity": "warn", - "detail": f"pinned {fx.get('pair','rate')} is as of {fx['as_of']} — " - f"older than this run; refresh if the rate should be current"}) + if fx and run_dates_after: + pinned = fx.get("as_of") + if not pinned and fx.get("rates"): + ds = [_to_date(r.get("as_of")) for r in fx["rates"]] + ds = [d for d in ds if d is not None] + pinned = max(ds) if ds else None + if pinned: + p_d, run_d = _to_date(pinned), _to_date(run_dates_after) + if p_d is None or run_d is None: + issues.append({"kind": "fx_date_unparsed", "severity": "warn", + "detail": f"could not compare the pinned rate date ({pinned}) with " + f"the run date ({run_dates_after}) — check both dates"}) + elif p_d < run_d: + issues.append({"kind": "stale_fx", "severity": "warn", + "detail": f"pinned {fx.get('pair','rate')} is as of " + f"{p_d:%d %b %Y} — older than this run " + f"({run_d:%d %b %Y}); refresh if the rate should be current"}) return issues @@ -679,13 +754,15 @@ def convert_rows(spec, header, rows, lookups=None): rules = spec.get("rules") or {} if lookups is None: lookups = load_lookups(mapping) # inline map_values (file tables need a base_dir) + map_issues = [] if mapping: - t_header, t_rows = apply_map(header, rows, mapping, fx=spec.get("fx"), lookups=lookups) + t_header, t_rows = apply_map(header, rows, mapping, fx=spec.get("fx"), lookups=lookups, + issues=map_issues) else: t_header, t_rows = header, rows t_rows, required_issues, n_excluded = apply_required_policy( t_header, t_rows, tgt.get("columns"), rules) - issues = list(required_issues) + issues = map_issues + list(required_issues) issues.extend(check_contract(t_header, t_rows, tgt.get("columns"), header, mapping, rules)) report = {"rows_in": n_in, "rows_filtered": n_filtered, "rows_excluded_required": n_excluded, "rows_out": len(t_rows), @@ -727,10 +804,15 @@ def convert_file(spec, in_path, out_path, run_dates_after=None, base_dir=None): lookups = load_lookups(spec.get("map", {}), base_dir=base_dir) # resolve file tables here t_header, t_rows, report = convert_rows(spec, header, rows, lookups=lookups) report["sense_check"] = drift + # Never blind-apply: an error in the contract issues OR in the source sense-check (e.g. a + # mapped source column missing/renamed — it would be written blank) blocks the write. The + # report is still produced so the drift can be shown and the card adjusted/regenerated. blocking = [i for i in (report.get("issues") or []) if i.get("severity") == "error"] - if blocking: + drift_errors = [i for i in drift if i.get("severity") == "error"] + if blocking or drift_errors: report["written"] = [] report["blocked"] = True + report["blocked_by"] = (["contract"] if blocking else []) + (["sense_check"] if drift_errors else []) return report split_op = next((o for o in spec.get("reshape", []) if o["op"] == "split"), None) @@ -765,7 +847,14 @@ def render_report(report, *, name="Conversion"): + (f" · excluded (required missing): {excl}" if excl else "") + f" · rows out: {report['rows_out']}") if report.get("blocked"): - L.append("- Written: (blocked — contract errors; fix required fields or policy)") + why = report.get("blocked_by") or ["contract"] + reasons = [] + if "sense_check" in why: + reasons.append("the source has drifted from the card (see sense-check errors) — " + "adjust or regenerate the card, then re-run") + if "contract" in why: + reasons.append("contract errors — fix required fields or policy") + L.append("- Written: nothing (blocked — " + "; ".join(reasons) + ")") else: L.append(f"- Written: {', '.join(report.get('written', [])) or '(not written)'}") drift = report.get("sense_check") or [] @@ -938,6 +1027,19 @@ def _self_test(): [{"USD": "100", "Date": "15/03/2026"}, # -> 0.80 {"USD": "100", "Date": "20/06/2026"}]) # -> 0.75 assert fxr[0]["GBP"] == "80.00" and fxr[1]["GBP"] == "75.00", fxr + # never invent: a row predating every rate, or an unparseable date, is blank + flagged + _, fxr2, fxrep2 = convert_rows(fxspec, ["USD", "Date"], + [{"USD": "100", "Date": "15 Dec 2025"}, + {"USD": "100", "Date": "not a date"}, + {"USD": "100", "Date": "15 Jul 2026"}]) + assert fxr2[0]["GBP"] == "" and fxr2[1]["GBP"] == "" and fxr2[2]["GBP"] == "75.00", fxr2 + assert sum(1 for i in fxrep2["issues"] if i["kind"] == "fx_rate_unresolved") == 2, fxrep2 + # stale-rate check parses dates (DD MMM YYYY vs ISO), never string-compares + st = sense_check({"fx": {"pair": "USD/GBP", "rate": "0.8", "as_of": "30 Jun 2026"}}, [], [], + run_dates_after="2026-07-01") + assert [i["kind"] for i in st] == ["stale_fx"], st + assert not sense_check({"fx": {"rate": "0.8", "as_of": "01 Jul 2026"}}, [], [], + run_dates_after="2026-07-01") print("v2 date-keyed FX: PASS") # v2 (5) fixed-width output @@ -971,7 +1073,8 @@ def main(argv=None): ap.add_argument("-o", "--out", help="output path (a split writes _)") ap.add_argument("--check-only", action="store_true", help="sense-check the source against the card and report; write nothing") - ap.add_argument("--as-of", help="this run's date, to flag a stale pinned rate") + ap.add_argument("--as-of", help="this run's as-of date (ISO or DD MMM YYYY); a pinned rate " + "dated earlier is flagged stale") ap.add_argument("--self-test", action="store_true") a = ap.parse_args(argv) if a.self_test: @@ -991,7 +1094,7 @@ def main(argv=None): base_dir = str(Path(a.card).resolve().parent) # resolve relative lookup tables / templates report = convert_file(spec, a.source, out, run_dates_after=a.as_of, base_dir=base_dir) print(render_report(report, name=spec.get("name", "Conversion"))) - return 0 + return 1 if report.get("blocked") else 0 if __name__ == "__main__": diff --git a/skills/data-tidy/SKILL.md b/skills/data-tidy/SKILL.md index f1f8785..2d62bd2 100644 --- a/skills/data-tidy/SKILL.md +++ b/skills/data-tidy/SKILL.md @@ -50,10 +50,14 @@ For a **multi-tab workbook** it won't guess: `read_any` auto-selects the single but if several tabs hold data it raises `SheetSelectionRequired` — call `ingest.list_sheets(path)`, show the tabs, then `read_any(path, sheet="")`. -For files with 10k+ rows, use `ingest.read_large` instead of `read_any` to avoid OOM. See -`references/large-file-patterns.md` for vectorised operation guidance. - -**Done when:** you have `(header, rows, note)` from `read_any` (or `read_large` for 10k+ rows), and `note` has been read for any source-quality flags. If `SheetSelectionRequired` was raised, the user has chosen a sheet. +For files with 10k+ rows, use `ingest.read_large_rows(path)` instead of `read_any` — a drop-in +that returns the same `(rows, note)` shape (Parquet cache / streaming for `.xlsx`; any +other type falls back to `read_any`). `ingest.read_large` is the DataFrame variant and is +**`.xlsx`/`.xlsm` only** (raises on `.csv`); convert its result with +`header, rows = list(df.columns), df.values.tolist()`. See `references/large-file-patterns.md` +for vectorised operation guidance. + +**Done when:** you have `(header, rows, note)` from `read_any` (or `read_large_rows` for 10k+ rows), and `note` has been read for any source-quality flags. If `SheetSelectionRequired` was raised, the user has chosen a sheet. ### 2 — Profile (against the target) `dataclean.profile_table(header, rows)` / `dataclean.render_profile(...)` — shows columns, diff --git a/skills/data-tidy/references/large-file-patterns.md b/skills/data-tidy/references/large-file-patterns.md index e3b5f60..950a031 100644 --- a/skills/data-tidy/references/large-file-patterns.md +++ b/skills/data-tidy/references/large-file-patterns.md @@ -1,6 +1,6 @@ # Large-file patterns — vectorised operations cheat sheet -Use with `ingest.read_large` when a source has **10k+ rows**. Prefer vectorised pandas / +Use with `ingest.read_large_rows` / `ingest.read_large` when a source has **10k+ rows**. Prefer vectorised pandas / NumPy ops over Python row loops — a 200k-row ledger that finishes in seconds with the left-hand forms can take minutes (or OOM) with the right-hand forms. @@ -12,6 +12,24 @@ left-hand forms can take minutes (or OOM) with the right-hand forms. | `np.where(df['a'] > 0, 'Y', 'N')` | `df['a'].map(lambda ...)` | `np.where` / boolean assignment beats per-cell Python callables | | `df.groupby('a').agg({'b': 'sum'})` | `df.groupby('a').apply(custom_func)` | Named aggregations use the fast path; `apply` falls back to Python | +## Which reader? `read_large_rows` (drop-in) vs `read_large` (DataFrame) + +- **`ingest.read_large_rows(path, sheet=None)` → `(rows, note)`** — the drop-in for `read_any`: + the same list-of-rows shape (header row first), so `dataclean` / `analyse` run unchanged. Excel + goes through the Parquet cache / stream path below; any other type (`.csv`, `.pdf` …) is read + with `read_any`, so it never raises just because the file isn't Excel. +- **`ingest.read_large(path, sheet=None)` → `(DataFrame, note)`** — **`.xlsx` / `.xlsm` only** + (raises `ValueError` on `.csv` and other extensions). Use it when you want pandas for the + vectorised ops above. Without pandas/pyarrow it falls back to `(rows, note)` from `read_xlsx`. + To hand a DataFrame back to the row-based engines: + `header, rows = list(df.columns), df.values.tolist()`. + +A large **CSV** is read by `ingest.read_any` (or `read_large_rows`), whose single-pass +`csv.reader` returns list-of-rows — fast (a 250k-row CSV ingests in well under a second). +Ingestion is not the bottleneck at this scale; there is no chunked/pyarrow CSV path today, so a +genuinely memory-bound CSV (millions of rows) should be pre-split or loaded via your own +`pandas.read_csv(chunksize=…)` outside the toolkit. + ## Strategy reminder (`scripts/streaming.py`) | Rows (data) | Strategy | Behaviour | @@ -25,5 +43,5 @@ low-cardinality object columns) — typically **50–80%** memory reduction. ## Optional deps -`pyarrow` + `pandas` are optional. Without them `ingest.read_large` falls back to a -direct openpyxl read and warns that large files may OOM. See `README.md#mode--environment-compatibility`. +`pyarrow` + `pandas` are optional. Without them `ingest.read_large` / `read_large_rows` fall back to a +direct openpyxl read and warn that large files may OOM. See `README.md#mode--environment-compatibility`. diff --git a/tests/test_engine.py b/tests/test_engine.py index 14d963c..1f9b6a8 100644 --- a/tests/test_engine.py +++ b/tests/test_engine.py @@ -33,7 +33,8 @@ for _p in (_ROOT / "scripts", _ROOT / "skills" / "data-reconcile" / "scripts", _ROOT / "skills" / "data-visualise" / "scripts", - _ROOT / "skills" / "data-analyse" / "scripts"): + _ROOT / "skills" / "data-analyse" / "scripts", + _ROOT / "skills" / "data-convert" / "scripts"): if str(_p) not in sys.path: sys.path.insert(0, str(_p)) @@ -43,6 +44,7 @@ import reconcile # noqa: E402 import viz # noqa: E402 import workbook # noqa: E402 +import convert # noqa: E402 (interoperability engine — data-convert) # --------------------------------------------------------------------------- # @@ -2052,6 +2054,99 @@ def fake_post(url, headers=None, json=None, timeout=None): assert str(r3["validation"]).startswith("flagged"), r3["validation"] +# --------------------------------------------------------------------------- # +# Skill-quality audit fixes (Oct 2026): read_large_rows, convert drift block + FX dates +# --------------------------------------------------------------------------- # +def test_read_large_rows_matches_read_any_shape(): + """read_large_rows is a drop-in for read_any: (rows, note), header row first, blanks as "".""" + d = tempfile.mkdtemp() + xp = Path(d) / "big.xlsx" + rows = [["txn_id", "amount", "region"], ["T1", 10, "APAC"], ["T2", None, "EMEA"]] + _write_xlsx(xp, [("Data", rows)]) + got, note = ingest.read_large_rows(str(xp), sheet="Data", cache_dir=d) + assert isinstance(got, list) and isinstance(note, str) + assert [str(c) for c in got[0]] == ["txn_id", "amount", "region"], got + assert len(got) == 3 and got[2][1] in ("", None) and got[2][2] == "EMEA", got + assert all(not (isinstance(v, float) and v != v) for r in got for v in r), "no NaN leaks" + # a CSV never raises (read_large itself is Excel-only) + cp = Path(d) / "big.csv" + cp.write_text("a,b\n1,2\n", encoding="utf-8") + crow, cnote = ingest.read_large_rows(str(cp)) + assert crow == [["a", "b"], ["1", "2"]] and "non-Excel" in cnote + try: + ingest.read_large(str(cp)) + raise AssertionError("read_large should stay Excel-only") + except ValueError: + pass + + +def test_convert_blocks_write_on_sense_check_error(): + """A renamed/missing mapped source column must not be force-converted (written blank).""" + d = Path(tempfile.mkdtemp()) + src = d / "src.csv" + src.write_text("Date,Acct,Amount\n01/03/2026,4000,10\n", encoding="utf-8") # 'Account' renamed + spec = {"name": "t", "source": {"expected_columns": ["Date", "Account", "Amount"]}, + "target": {"format": "csv"}, + "map": {"D": {"from": "Date", "type": "date"}, "A": {"from": "Account"}, + "V": {"from": "Amount", "type": "number"}}} + out = d / "out.csv" + rep = convert.convert_file(spec, str(src), str(out)) + assert rep["blocked"] and rep["written"] == [] and not out.exists(), rep + assert "sense_check" in rep["blocked_by"] + assert any(i["kind"] == "mapped_column_missing" for i in rep["sense_check"]) + assert "drifted" in convert.render_report(rep) + # CLI: non-zero exit and nothing written + card = d / "card.json" + card.write_text(json.dumps(spec), encoding="utf-8") + assert convert.main([str(src), "--card", str(card), "-o", str(out)]) == 1 and not out.exists() + # the matching source still converts + src.write_text("Date,Account,Amount\n01/03/2026,4000,10\n", encoding="utf-8") + rep2 = convert.convert_file(spec, str(src), str(out)) + assert not rep2.get("blocked") and out.exists(), rep2 + + +def test_convert_stale_fx_parses_both_date_formats(): + def kinds(as_of, run): + return [i["kind"] for i in convert.sense_check( + {"fx": {"pair": "USD/GBP", "rate": "0.8", "as_of": as_of}}, [], [], run_dates_after=run)] + assert kinds("30 Jun 2026", "2026-07-01") == ["stale_fx"] # string compare said "not stale" + assert kinds("2026-06-30", "01 Jul 2026") == ["stale_fx"] + assert kinds("01 Jul 2026", "2026-07-01") == [] # same day — current + assert kinds("2026-07-02", "01 Jul 2026") == [] + assert kinds("someday", "01 Jul 2026") == ["fx_date_unparsed"] + # a rates table is judged by its latest as_of + st = convert.sense_check({"fx": {"rates": [{"as_of": "01 Jan 2026", "rate": "0.8"}, + {"as_of": "2026-06-01", "rate": "0.75"}]}}, + [], [], run_dates_after="15 Jul 2026") + assert [i["kind"] for i in st] == ["stale_fx"], st + + +def test_convert_fx_rate_never_invented(): + spec = {"map": {"GBP": {"from": "USD", "compute": "fx_convert", "on_date": "Date", "dp": 2}}, + "fx": {"pair": "USD/GBP", "rates": [{"as_of": "01 Jan 2026", "rate": "0.80"}, + {"as_of": "2026-06-01", "rate": "0.75"}]}, + "target": {}} + _, rows, rep = convert.convert_rows(spec, ["USD", "Date"], [ + {"USD": "100", "Date": "31 Dec 2025"}, # predates every rate -> blank + flag + {"USD": "100", "Date": "garbage"}, # unparseable -> blank + flag + {"USD": "100", "Date": ""}, # blank -> blank + flag + {"USD": "100", "Date": "15/03/2026"}, # -> 0.80 + {"USD": "100", "Date": "2026-06-01"}]) # boundary -> 0.75 + assert [r["GBP"] for r in rows] == ["", "", "", "80.00", "75.00"], rows + flagged = [i for i in rep["issues"] if i["kind"] == "fx_rate_unresolved"] + assert [i["row"] for i in flagged] == [1, 2, 3] and all(i["severity"] == "warning" for i in flagged) + # a single pinned rate still applies to every row; no rate at all still raises + _, r1, _ = convert.convert_rows({"map": spec["map"], "fx": {"rate": "0.5"}, "target": {}}, + ["USD", "Date"], [{"USD": "10", "Date": "garbage"}]) + assert r1[0]["GBP"] == "5.00" + try: + convert.convert_rows({"map": spec["map"], "fx": {}, "target": {}}, ["USD", "Date"], + [{"USD": "10", "Date": "01/01/2026"}]) + raise AssertionError("missing fx should raise") + except ValueError: + pass + + # --------------------------------------------------------------------------- # # Standalone runner (no pytest needed) # --------------------------------------------------------------------------- #