From a05cc51916d38b2933df3d85f5502d3b82437323 Mon Sep 17 00:00:00 2001 From: kert Date: Sun, 25 Oct 2026 16:04:16 -0400 Subject: [PATCH] =?UTF-8?q?feat(bcda):=20incremental=20=5Fsince=20pulls=20?= =?UTF-8?q?=E2=80=94=20watermarks,=20temporality=20checks,=20reconciliatio?= =?UTF-8?q?n=20with=20tiebreakers,=20ledger=20and=20invariants?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Design: docs/superpowers/specs/2026-10-25-bcda-since-reconciliation-design.md. Until now a _since export was loaded like a full one: the loader took the newest export directory per type, so a delta silently replaced the baseline it was meant to extend. bcda.sync makes incremental pulls safe end to end. First order — which row is current. A baseline (no _since) is the authoritative snapshot for its types; deltas of the same population at or after its cut-off extend it. Keys: Patient BENE_SK, Coverage id, EOB claim control number (each claim *version* has a new FHIR id — migration guide). Winner per key: newest meta.lastUpdated, then NCH/DDPS over SharedSystem (the connector's rule), then later transactionTime, later applied sequence, larger id. NotFinalAction winners stay as tombstones; only a baseline retires rows (the API cannot express deletion). eob_item follows its header. Second order — what a job did, per table, in the ledger: new / replaced / unchanged / stale_ignored, backfill (lastUpdated < _since for an enrollee we did not have — the API's promise for newly attributed enrollees on Group/all) vs late (same shape for one we had — should not happen), tombstoned, adjusted (clm_orig_cntl_num → bcda.eob_supersession), retired, orphans (claims/coverage without a current Patient), scope drift. Third order — invariants on every apply before anything is published: unique keys, count conservation (|cur'| = |cur| + new − retired), watermark monotone, every item has a header; replay determinism and idempotency are tested (apply in either order → byte-identical tables; re-apply → no-op). Current tables are re-derived from the applied partitions each time, so the state is a function of the set of applied jobs, not their arrival order. Temporality checks before a _since export starts (block/warn/ok): format, future (server 400s), floor (no v3 lastUpdated before 2026-03-26), no_baseline, gap (since > watermark: a window nobody would ever fetch), overlap (free), endpoint_mix (runout vs current population), backfill_scope (/Patient delta over a Group/all baseline), scope_filter (_typeFilter drift), inflight, unapplied, attribution_newer, stale_baseline. next_since() is the previous job's transactionTime, as BCDA recommends; a combined job takes the earliest watermark of its types. Store: job rows carry transaction_time and request, exports// manifest.json keeps the completed-job body, resume() fills both in for jobs completed before this; adopted jobs read _since from their request line; a delta with nothing to deliver (200, empty output) still counts and advances the watermark. flatten_export(out_dir=) writes per-job partitions under flat/history//; current tables keep _job_key/_transaction_time/ _since/_kind/_applied_seq and the connector's _ensure() drops them before the stage contracts. load_bcda(reconcile=True) applies pending jobs and also loads bcda.sync_ledger, bcda.sync_watermark, bcda.eob_supersession; an explicit ndjson_dir or a store without job rows keeps the legacy path. Surfaces: `stack bcda sync status|check|apply|pull`, `stack bcda export --since auto [--force]`, `stack bcda resume`; the manager's Exports page gets a _since mode (off / watermark / date) with the checks shown and blocks respected, and a Sync page (watermarks, pending, reconcile, ledger); notebook section 8. Verified on the real Large-entity store: applying the three baselines over the legacy flat/ tables reported every row unchanged (0 new, 0 retired) and loaded counts identical to the full load (221,021 medical lines, 11,968 pharmacy, 9,582 eligibility); a real /Patient-endpoint EOB delta with a _typeFilter reconciled as 248 unchanged with the drift on record; the sandbox's transactionTime is midnight UTC of the run day, so a same-day zero-row delta is correctly ignored as predating its baseline. refs #1139 --- docs/docs/cli/api-serve.md | 2 +- docs/docs/cli/api.md | 2 +- docs/docs/cli/bcda-cancel.md | 2 +- docs/docs/cli/bcda-export.md | 8 +- docs/docs/cli/bcda-load.md | 6 +- docs/docs/cli/bcda-resume.md | 21 + docs/docs/cli/bcda-store.md | 2 +- docs/docs/cli/bcda-sync.md | 25 + docs/docs/cli/bcda-ui.md | 2 +- docs/docs/cli/bcda-vendor.md | 2 +- docs/docs/cli/bcda.md | 10 +- docs/docs/cli/bib-attach-iom.md | 2 +- docs/docs/cli/bib-attach-oig.md | 2 +- docs/docs/cli/bib-backfill-comments.md | 2 +- docs/docs/cli/bib-cfr-jump.md | 2 +- docs/docs/cli/bib-code-tags.md | 2 +- docs/docs/cli/bib-discover-pfs-rules.md | 2 +- docs/docs/cli/bib-fetch-docket-comments.md | 2 +- docs/docs/cli/bib-fetch-pfs-comments.md | 2 +- docs/docs/cli/bib-fr-grab.md | 2 +- docs/docs/cli/bib-fr-jump.md | 2 +- docs/docs/cli/bib-import-zotero.md | 2 +- docs/docs/cli/bib-ingest-iom.md | 2 +- docs/docs/cli/bib-ingest-mail.md | 2 +- docs/docs/cli/bib-ingest-oig.md | 2 +- docs/docs/cli/bib-query.md | 2 +- docs/docs/cli/bib-refresh-iom.md | 2 +- docs/docs/cli/bib-refresh-oig.md | 2 +- docs/docs/cli/bib-sync-zotero.md | 2 +- docs/docs/cli/bib-sync.md | 2 +- docs/docs/cli/bib-tag.md | 2 +- docs/docs/cli/bib-watch-iom.md | 2 +- docs/docs/cli/bib.md | 2 +- docs/docs/cli/bls-ces.md | 2 +- docs/docs/cli/bls-oews.md | 2 +- docs/docs/cli/bls.md | 2 +- docs/docs/cli/comments-dockets.md | 2 +- docs/docs/cli/comments-extract-ocr.md | 2 +- docs/docs/cli/comments-extract.md | 2 +- docs/docs/cli/comments-seal.md | 2 +- docs/docs/cli/comments-stats.md | 2 +- docs/docs/cli/comments-unseal.md | 2 +- docs/docs/cli/comments.md | 2 +- docs/docs/cli/db-comment.md | 2 +- docs/docs/cli/db-inspect.md | 2 +- docs/docs/cli/db.md | 2 +- docs/docs/cli/docs-build.md | 2 +- docs/docs/cli/docs-generate.md | 2 +- docs/docs/cli/docs-serve.md | 2 +- docs/docs/cli/docs.md | 2 +- docs/docs/cli/generate-models.md | 2 +- docs/docs/cli/generate.md | 2 +- docs/docs/cli/lake-deploy.md | 2 +- docs/docs/cli/lake-load.md | 2 +- docs/docs/cli/lake-parity.md | 2 +- docs/docs/cli/lake-validate.md | 2 +- docs/docs/cli/lake.md | 2 +- docs/docs/cli/llm-eval-tags.md | 2 +- docs/docs/cli/llm-hosts.md | 2 +- docs/docs/cli/llm-index.md | 2 +- docs/docs/cli/llm-prune-rules.md | 2 +- docs/docs/cli/llm-restamp.md | 2 +- docs/docs/cli/llm-serve.md | 2 +- docs/docs/cli/llm-stamp-themes.md | 2 +- docs/docs/cli/llm-tag.md | 2 +- docs/docs/cli/llm-vocab.md | 2 +- docs/docs/cli/llm.md | 2 +- docs/docs/cli/mail-attach-smarthost.md | 2 +- docs/docs/cli/mail-dkim-export.md | 2 +- docs/docs/cli/mail-dns.md | 2 +- docs/docs/cli/mail-down.md | 2 +- docs/docs/cli/mail-provision.md | 2 +- docs/docs/cli/mail-rotate-creds.md | 2 +- docs/docs/cli/mail-seed-mailboxes.md | 2 +- docs/docs/cli/mail-status.md | 2 +- docs/docs/cli/mail-up.md | 2 +- docs/docs/cli/mail-wire-git.md | 2 +- docs/docs/cli/mail.md | 2 +- docs/docs/cli/perf-show.md | 2 +- docs/docs/cli/perf.md | 2 +- docs/docs/cli/pfs-cpt-ingest.md | 2 +- docs/docs/cli/pfs-elements.md | 2 +- docs/docs/cli/pfs-exposure.md | 2 +- docs/docs/cli/pfs-families.md | 2 +- docs/docs/cli/pfs-guidance.md | 2 +- docs/docs/cli/pfs-lineage.md | 2 +- docs/docs/cli/pfs-reaction.md | 2 +- docs/docs/cli/pfs-review.md | 2 +- docs/docs/cli/pfs-utilization.md | 2 +- docs/docs/cli/pfs.md | 2 +- docs/docs/cli/prisma-eligible.md | 2 +- docs/docs/cli/prisma-export.md | 2 +- docs/docs/cli/prisma-extract.md | 2 +- docs/docs/cli/prisma-fetch.md | 2 +- docs/docs/cli/prisma-flow.md | 2 +- docs/docs/cli/prisma-init.md | 2 +- docs/docs/cli/prisma-ping-llm.md | 2 +- docs/docs/cli/prisma-run.md | 2 +- docs/docs/cli/prisma-screen.md | 2 +- docs/docs/cli/prisma-vpn.md | 2 +- docs/docs/cli/prisma.md | 2 +- docs/docs/cli/rec-list.md | 2 +- docs/docs/cli/rec-opps.md | 2 +- docs/docs/cli/rec-pfs.md | 2 +- docs/docs/cli/rec.md | 2 +- docs/docs/cli/zot-dump-schema.md | 2 +- docs/docs/cli/zot-fix-dates.md | 2 +- docs/docs/cli/zot-fix-fields.md | 2 +- docs/docs/cli/zot-fix-keys.md | 2 +- docs/docs/cli/zot-verify-parity.md | 2 +- docs/docs/cli/zot.md | 2 +- ...-10-25-bcda-since-reconciliation-design.md | 240 ++++ .../specs/2026-10-25-bcda-v3-design.md | 4 + notebooks/bcda_v3_sandbox.py | 80 ++ src/aco/load/bcda.py | 40 +- src/bcda/express/cclf.py | 14 +- src/bcda/express/flatten.py | 18 +- src/bcda/store.py | 76 ++ src/bcda/sync.py | 1094 +++++++++++++++++ src/bcda/ui/app.py | 1 + src/bcda/ui/service.py | 144 ++- src/bcda/ui/views.py | 185 ++- src/cli/bcda.py | 284 ++++- tests/aco/test_load_bcda.py | 84 ++ tests/bcda/test_store.py | 56 + tests/bcda/test_sync.py | 750 +++++++++++ tests/bcda/test_ui_service.py | 129 +- tests/bcda/test_ui_views.py | 84 +- tests/cli/test_cli_bcda.py | 204 +++ 129 files changed, 3615 insertions(+), 154 deletions(-) create mode 100644 docs/docs/cli/bcda-resume.md create mode 100644 docs/docs/cli/bcda-sync.md create mode 100644 docs/superpowers/specs/2026-10-25-bcda-since-reconciliation-design.md create mode 100644 src/bcda/sync.py create mode 100644 tests/bcda/test_sync.py diff --git a/docs/docs/cli/api-serve.md b/docs/docs/cli/api-serve.md index a677d0c..9981b5f 100644 --- a/docs/docs/cli/api-serve.md +++ b/docs/docs/cli/api-serve.md @@ -1,6 +1,6 @@ --- title: stack api serve -sidebar_position: 77 +sidebar_position: 79 --- # `stack api serve` diff --git a/docs/docs/cli/api.md b/docs/docs/cli/api.md index 8def8b9..a86800d 100644 --- a/docs/docs/cli/api.md +++ b/docs/docs/cli/api.md @@ -1,6 +1,6 @@ --- title: stack api -sidebar_position: 76 +sidebar_position: 78 --- # `stack api` diff --git a/docs/docs/cli/bcda-cancel.md b/docs/docs/cli/bcda-cancel.md index e4c35be..8d92a82 100644 --- a/docs/docs/cli/bcda-cancel.md +++ b/docs/docs/cli/bcda-cancel.md @@ -1,6 +1,6 @@ --- title: stack bcda cancel -sidebar_position: 16 +sidebar_position: 17 --- # `stack bcda cancel` diff --git a/docs/docs/cli/bcda-export.md b/docs/docs/cli/bcda-export.md index 6a894f8..5b2bd87 100644 --- a/docs/docs/cli/bcda-export.md +++ b/docs/docs/cli/bcda-export.md @@ -19,8 +19,12 @@ Usage: stack bcda export [OPTIONS] │ --endpoint TEXT Group/all, Group/runout or │ │ Patient. │ │ [default: Group/all] │ -│ --since TEXT FHIR instant, e.g. │ -│ 2026-01-01T00:00:00+00:00 │ +│ --since TEXT FHIR instant │ +│ (2026-10-01T00:00:00+00:00) │ +│ or 'auto' = the per-type │ +│ watermark. │ +│ --force Start even when the _since │ +│ checks say block. │ │ --system-type TEXT _typeFilter System-Type │ │ tag(s). │ │ --outcome TEXT _typeFilter outcome: partial │ diff --git a/docs/docs/cli/bcda-load.md b/docs/docs/cli/bcda-load.md index 951a8a0..64f0e9c 100644 --- a/docs/docs/cli/bcda-load.md +++ b/docs/docs/cli/bcda-load.md @@ -1,6 +1,6 @@ --- title: stack bcda load -sidebar_position: 18 +sidebar_position: 19 --- # `stack bcda load` @@ -8,8 +8,8 @@ sidebar_position: 18 ``` Usage: stack bcda load [OPTIONS] - Flatten + load the newest export per type, run the connector, publish the - replica. + Reconcile the store (or flatten the newest export per type), load, run the + connector, publish the replica. ╭─ Options ────────────────────────────────────────────────────────────────────╮ │ --pipeline --no-pipeline Run the connector into input_layer.* │ diff --git a/docs/docs/cli/bcda-resume.md b/docs/docs/cli/bcda-resume.md new file mode 100644 index 0000000..cf571e4 --- /dev/null +++ b/docs/docs/cli/bcda-resume.md @@ -0,0 +1,21 @@ +--- +title: stack bcda resume +sidebar_position: 16 +--- + +# `stack bcda resume` + +``` +Usage: stack bcda resume [OPTIONS] KEY + + Finish a store job: re-poll, download missing files, record the manifest. + +╭─ Arguments ──────────────────────────────────────────────────────────────────╮ +│ * key TEXT Store job key (see `stack bcda store`). [required] │ +╰──────────────────────────────────────────────────────────────────────────────╯ +╭─ Options ────────────────────────────────────────────────────────────────────╮ +│ --preset TEXT Public sandbox entity when BCDA_CLIENT_ID is unset. │ +│ [default: Large Model Entity] │ +│ --help Show this message and exit. │ +╰──────────────────────────────────────────────────────────────────────────────╯ +``` diff --git a/docs/docs/cli/bcda-store.md b/docs/docs/cli/bcda-store.md index 464f127..04ad7a2 100644 --- a/docs/docs/cli/bcda-store.md +++ b/docs/docs/cli/bcda-store.md @@ -1,6 +1,6 @@ --- title: stack bcda store -sidebar_position: 17 +sidebar_position: 18 --- # `stack bcda store` diff --git a/docs/docs/cli/bcda-sync.md b/docs/docs/cli/bcda-sync.md new file mode 100644 index 0000000..ab613df --- /dev/null +++ b/docs/docs/cli/bcda-sync.md @@ -0,0 +1,25 @@ +--- +title: stack bcda sync +sidebar_position: 21 +--- + +# `stack bcda sync` + +``` +Usage: stack bcda sync [OPTIONS] COMMAND [ARGS]... + + Incremental (_since) pulls. + +╭─ Options ────────────────────────────────────────────────────────────────────╮ +│ --help Show this message and exit. │ +╰──────────────────────────────────────────────────────────────────────────────╯ +╭─ Commands ───────────────────────────────────────────────────────────────────╮ +│ status Watermarks per (endpoint, _typeFilter, type), downloaded vs applied │ +│ jobs, ledger, current counts. │ +│ check Temporality checks for a proposed _since (exit 2 on block). │ +│ apply Reconcile downloaded jobs into the current tables (ledger kept), │ +│ then load. │ +│ pull Pull every type since its watermark (one job per type), then │ +│ reconcile and load. │ +╰──────────────────────────────────────────────────────────────────────────────╯ +``` diff --git a/docs/docs/cli/bcda-ui.md b/docs/docs/cli/bcda-ui.md index 70af438..b2fcadb 100644 --- a/docs/docs/cli/bcda-ui.md +++ b/docs/docs/cli/bcda-ui.md @@ -8,7 +8,7 @@ sidebar_position: 10 ``` Usage: stack bcda ui [OPTIONS] - Launch the BCDA manager (Streamlit). + Launch the BCDA manager (Streamlit; /metrics when STACK_TELEMETRY is on). ╭─ Options ────────────────────────────────────────────────────────────────────╮ │ --port INTEGER Port for the Streamlit server. │ diff --git a/docs/docs/cli/bcda-vendor.md b/docs/docs/cli/bcda-vendor.md index ab9f99a..a3fb754 100644 --- a/docs/docs/cli/bcda-vendor.md +++ b/docs/docs/cli/bcda-vendor.md @@ -1,6 +1,6 @@ --- title: stack bcda vendor -sidebar_position: 19 +sidebar_position: 20 --- # `stack bcda vendor` diff --git a/docs/docs/cli/bcda.md b/docs/docs/cli/bcda.md index 31a65b0..6c6178c 100644 --- a/docs/docs/cli/bcda.md +++ b/docs/docs/cli/bcda.md @@ -14,17 +14,21 @@ Usage: stack bcda [OPTIONS] COMMAND [ARGS]... │ --help Show this message and exit. │ ╰──────────────────────────────────────────────────────────────────────────────╯ ╭─ Commands ───────────────────────────────────────────────────────────────────╮ -│ ui Launch the BCDA manager (Streamlit). │ +│ ui Launch the BCDA manager (Streamlit; /metrics when STACK_TELEMETRY │ +│ is on). │ │ preflight /_version, /_health and metadata — no token needed. │ │ auth Issue a token and show attribution status. │ │ jobs Server job history for the entity (shared on the sandbox). │ │ export Run an export through the store (blocks until downloaded). │ │ adopt Download a completed job this store did not start. │ +│ resume Finish a store job: re-poll, download missing files, record the │ +│ manifest. │ │ cancel Cancel an in-progress job. │ │ store Local store: jobs, files, bytes. │ -│ load Flatten + load the newest export per type, run the connector, │ -│ publish the replica. │ +│ load Reconcile the store (or flatten the newest export per type), │ +│ load, run the connector, publish the replica. │ │ vendor Vendored upstream (CMSgov/bcda-app, bcda.cms.gov): manifest, │ │ verification, drift. │ +│ sync Incremental (_since) pulls. │ ╰──────────────────────────────────────────────────────────────────────────────╯ ``` diff --git a/docs/docs/cli/bib-attach-iom.md b/docs/docs/cli/bib-attach-iom.md index d85e063..478fbf1 100644 --- a/docs/docs/cli/bib-attach-iom.md +++ b/docs/docs/cli/bib-attach-iom.md @@ -1,6 +1,6 @@ --- title: stack bib attach-iom -sidebar_position: 32 +sidebar_position: 34 --- # `stack bib attach-iom` diff --git a/docs/docs/cli/bib-attach-oig.md b/docs/docs/cli/bib-attach-oig.md index abb17c9..1fdb4f5 100644 --- a/docs/docs/cli/bib-attach-oig.md +++ b/docs/docs/cli/bib-attach-oig.md @@ -1,6 +1,6 @@ --- title: stack bib attach-oig -sidebar_position: 37 +sidebar_position: 39 --- # `stack bib attach-oig` diff --git a/docs/docs/cli/bib-backfill-comments.md b/docs/docs/cli/bib-backfill-comments.md index b098014..4dd1f9e 100644 --- a/docs/docs/cli/bib-backfill-comments.md +++ b/docs/docs/cli/bib-backfill-comments.md @@ -1,6 +1,6 @@ --- title: stack bib backfill-comments -sidebar_position: 30 +sidebar_position: 32 --- # `stack bib backfill-comments` diff --git a/docs/docs/cli/bib-cfr-jump.md b/docs/docs/cli/bib-cfr-jump.md index 3346665..a1d239c 100644 --- a/docs/docs/cli/bib-cfr-jump.md +++ b/docs/docs/cli/bib-cfr-jump.md @@ -1,6 +1,6 @@ --- title: stack bib cfr-jump -sidebar_position: 42 +sidebar_position: 44 --- # `stack bib cfr-jump` diff --git a/docs/docs/cli/bib-code-tags.md b/docs/docs/cli/bib-code-tags.md index a576d1d..a455b95 100644 --- a/docs/docs/cli/bib-code-tags.md +++ b/docs/docs/cli/bib-code-tags.md @@ -1,6 +1,6 @@ --- title: stack bib code-tags -sidebar_position: 43 +sidebar_position: 45 --- # `stack bib code-tags` diff --git a/docs/docs/cli/bib-discover-pfs-rules.md b/docs/docs/cli/bib-discover-pfs-rules.md index c98b2d8..37b98e0 100644 --- a/docs/docs/cli/bib-discover-pfs-rules.md +++ b/docs/docs/cli/bib-discover-pfs-rules.md @@ -1,6 +1,6 @@ --- title: stack bib discover-pfs-rules -sidebar_position: 26 +sidebar_position: 28 --- # `stack bib discover-pfs-rules` diff --git a/docs/docs/cli/bib-fetch-docket-comments.md b/docs/docs/cli/bib-fetch-docket-comments.md index b2ef056..a3ef0f5 100644 --- a/docs/docs/cli/bib-fetch-docket-comments.md +++ b/docs/docs/cli/bib-fetch-docket-comments.md @@ -1,6 +1,6 @@ --- title: stack bib fetch-docket-comments -sidebar_position: 27 +sidebar_position: 29 --- # `stack bib fetch-docket-comments` diff --git a/docs/docs/cli/bib-fetch-pfs-comments.md b/docs/docs/cli/bib-fetch-pfs-comments.md index 93d989a..45cf2b8 100644 --- a/docs/docs/cli/bib-fetch-pfs-comments.md +++ b/docs/docs/cli/bib-fetch-pfs-comments.md @@ -1,6 +1,6 @@ --- title: stack bib fetch-pfs-comments -sidebar_position: 28 +sidebar_position: 30 --- # `stack bib fetch-pfs-comments` diff --git a/docs/docs/cli/bib-fr-grab.md b/docs/docs/cli/bib-fr-grab.md index cbf06df..b167aa2 100644 --- a/docs/docs/cli/bib-fr-grab.md +++ b/docs/docs/cli/bib-fr-grab.md @@ -1,6 +1,6 @@ --- title: stack bib fr-grab -sidebar_position: 40 +sidebar_position: 42 --- # `stack bib fr-grab` diff --git a/docs/docs/cli/bib-fr-jump.md b/docs/docs/cli/bib-fr-jump.md index 33aef6d..d3b13d6 100644 --- a/docs/docs/cli/bib-fr-jump.md +++ b/docs/docs/cli/bib-fr-jump.md @@ -1,6 +1,6 @@ --- title: stack bib fr-jump -sidebar_position: 41 +sidebar_position: 43 --- # `stack bib fr-jump` diff --git a/docs/docs/cli/bib-import-zotero.md b/docs/docs/cli/bib-import-zotero.md index 6fcdfdd..e86d716 100644 --- a/docs/docs/cli/bib-import-zotero.md +++ b/docs/docs/cli/bib-import-zotero.md @@ -1,6 +1,6 @@ --- title: stack bib import-zotero -sidebar_position: 34 +sidebar_position: 36 --- # `stack bib import-zotero` diff --git a/docs/docs/cli/bib-ingest-iom.md b/docs/docs/cli/bib-ingest-iom.md index 03c8e22..1c8d2c7 100644 --- a/docs/docs/cli/bib-ingest-iom.md +++ b/docs/docs/cli/bib-ingest-iom.md @@ -1,6 +1,6 @@ --- title: stack bib ingest-iom -sidebar_position: 31 +sidebar_position: 33 --- # `stack bib ingest-iom` diff --git a/docs/docs/cli/bib-ingest-mail.md b/docs/docs/cli/bib-ingest-mail.md index ab80fa9..f1ea1d4 100644 --- a/docs/docs/cli/bib-ingest-mail.md +++ b/docs/docs/cli/bib-ingest-mail.md @@ -1,6 +1,6 @@ --- title: stack bib ingest-mail -sidebar_position: 29 +sidebar_position: 31 --- # `stack bib ingest-mail` diff --git a/docs/docs/cli/bib-ingest-oig.md b/docs/docs/cli/bib-ingest-oig.md index 3c8cb2c..5b71bb1 100644 --- a/docs/docs/cli/bib-ingest-oig.md +++ b/docs/docs/cli/bib-ingest-oig.md @@ -1,6 +1,6 @@ --- title: stack bib ingest-oig -sidebar_position: 36 +sidebar_position: 38 --- # `stack bib ingest-oig` diff --git a/docs/docs/cli/bib-query.md b/docs/docs/cli/bib-query.md index 4311440..d2e8602 100644 --- a/docs/docs/cli/bib-query.md +++ b/docs/docs/cli/bib-query.md @@ -1,6 +1,6 @@ --- title: stack bib query -sidebar_position: 25 +sidebar_position: 27 --- # `stack bib query` diff --git a/docs/docs/cli/bib-refresh-iom.md b/docs/docs/cli/bib-refresh-iom.md index cc0c7be..e587e3b 100644 --- a/docs/docs/cli/bib-refresh-iom.md +++ b/docs/docs/cli/bib-refresh-iom.md @@ -1,6 +1,6 @@ --- title: stack bib refresh-iom -sidebar_position: 39 +sidebar_position: 41 --- # `stack bib refresh-iom` diff --git a/docs/docs/cli/bib-refresh-oig.md b/docs/docs/cli/bib-refresh-oig.md index 32b3cd2..4b7895b 100644 --- a/docs/docs/cli/bib-refresh-oig.md +++ b/docs/docs/cli/bib-refresh-oig.md @@ -1,6 +1,6 @@ --- title: stack bib refresh-oig -sidebar_position: 38 +sidebar_position: 40 --- # `stack bib refresh-oig` diff --git a/docs/docs/cli/bib-sync-zotero.md b/docs/docs/cli/bib-sync-zotero.md index ec7af77..57e1973 100644 --- a/docs/docs/cli/bib-sync-zotero.md +++ b/docs/docs/cli/bib-sync-zotero.md @@ -1,6 +1,6 @@ --- title: stack bib sync-zotero -sidebar_position: 35 +sidebar_position: 37 --- # `stack bib sync-zotero` diff --git a/docs/docs/cli/bib-sync.md b/docs/docs/cli/bib-sync.md index 8802c80..4c2da1c 100644 --- a/docs/docs/cli/bib-sync.md +++ b/docs/docs/cli/bib-sync.md @@ -1,6 +1,6 @@ --- title: stack bib sync -sidebar_position: 23 +sidebar_position: 25 --- # `stack bib sync` diff --git a/docs/docs/cli/bib-tag.md b/docs/docs/cli/bib-tag.md index 5fe79df..a78f14f 100644 --- a/docs/docs/cli/bib-tag.md +++ b/docs/docs/cli/bib-tag.md @@ -1,6 +1,6 @@ --- title: stack bib tag -sidebar_position: 24 +sidebar_position: 26 --- # `stack bib tag` diff --git a/docs/docs/cli/bib-watch-iom.md b/docs/docs/cli/bib-watch-iom.md index 44d1d1c..15c44ca 100644 --- a/docs/docs/cli/bib-watch-iom.md +++ b/docs/docs/cli/bib-watch-iom.md @@ -1,6 +1,6 @@ --- title: stack bib watch-iom -sidebar_position: 33 +sidebar_position: 35 --- # `stack bib watch-iom` diff --git a/docs/docs/cli/bib.md b/docs/docs/cli/bib.md index 44d9f33..f31fb9e 100644 --- a/docs/docs/cli/bib.md +++ b/docs/docs/cli/bib.md @@ -1,6 +1,6 @@ --- title: stack bib -sidebar_position: 22 +sidebar_position: 24 --- # `stack bib` diff --git a/docs/docs/cli/bls-ces.md b/docs/docs/cli/bls-ces.md index ddbe3c4..32ecae0 100644 --- a/docs/docs/cli/bls-ces.md +++ b/docs/docs/cli/bls-ces.md @@ -1,6 +1,6 @@ --- title: stack bls ces -sidebar_position: 46 +sidebar_position: 48 --- # `stack bls ces` diff --git a/docs/docs/cli/bls-oews.md b/docs/docs/cli/bls-oews.md index ec8a01a..dc2b4f6 100644 --- a/docs/docs/cli/bls-oews.md +++ b/docs/docs/cli/bls-oews.md @@ -1,6 +1,6 @@ --- title: stack bls oews -sidebar_position: 45 +sidebar_position: 47 --- # `stack bls oews` diff --git a/docs/docs/cli/bls.md b/docs/docs/cli/bls.md index 678e9f7..417e796 100644 --- a/docs/docs/cli/bls.md +++ b/docs/docs/cli/bls.md @@ -1,6 +1,6 @@ --- title: stack bls -sidebar_position: 44 +sidebar_position: 46 --- # `stack bls` diff --git a/docs/docs/cli/comments-dockets.md b/docs/docs/cli/comments-dockets.md index 20aec18..ed2f06f 100644 --- a/docs/docs/cli/comments-dockets.md +++ b/docs/docs/cli/comments-dockets.md @@ -1,6 +1,6 @@ --- title: stack comments dockets -sidebar_position: 51 +sidebar_position: 53 --- # `stack comments dockets` diff --git a/docs/docs/cli/comments-extract-ocr.md b/docs/docs/cli/comments-extract-ocr.md index 00d87e5..7958670 100644 --- a/docs/docs/cli/comments-extract-ocr.md +++ b/docs/docs/cli/comments-extract-ocr.md @@ -1,6 +1,6 @@ --- title: stack comments extract-ocr -sidebar_position: 49 +sidebar_position: 51 --- # `stack comments extract-ocr` diff --git a/docs/docs/cli/comments-extract.md b/docs/docs/cli/comments-extract.md index 4591e9e..d21f1ac 100644 --- a/docs/docs/cli/comments-extract.md +++ b/docs/docs/cli/comments-extract.md @@ -1,6 +1,6 @@ --- title: stack comments extract -sidebar_position: 48 +sidebar_position: 50 --- # `stack comments extract` diff --git a/docs/docs/cli/comments-seal.md b/docs/docs/cli/comments-seal.md index e86617b..47fad6a 100644 --- a/docs/docs/cli/comments-seal.md +++ b/docs/docs/cli/comments-seal.md @@ -1,6 +1,6 @@ --- title: stack comments seal -sidebar_position: 52 +sidebar_position: 54 --- # `stack comments seal` diff --git a/docs/docs/cli/comments-stats.md b/docs/docs/cli/comments-stats.md index 0c435a4..daf0817 100644 --- a/docs/docs/cli/comments-stats.md +++ b/docs/docs/cli/comments-stats.md @@ -1,6 +1,6 @@ --- title: stack comments stats -sidebar_position: 50 +sidebar_position: 52 --- # `stack comments stats` diff --git a/docs/docs/cli/comments-unseal.md b/docs/docs/cli/comments-unseal.md index df5d68c..a2be37e 100644 --- a/docs/docs/cli/comments-unseal.md +++ b/docs/docs/cli/comments-unseal.md @@ -1,6 +1,6 @@ --- title: stack comments unseal -sidebar_position: 53 +sidebar_position: 55 --- # `stack comments unseal` diff --git a/docs/docs/cli/comments.md b/docs/docs/cli/comments.md index 2a61708..c4b15a7 100644 --- a/docs/docs/cli/comments.md +++ b/docs/docs/cli/comments.md @@ -1,6 +1,6 @@ --- title: stack comments -sidebar_position: 47 +sidebar_position: 49 --- # `stack comments` diff --git a/docs/docs/cli/db-comment.md b/docs/docs/cli/db-comment.md index 4ea6adc..15462aa 100644 --- a/docs/docs/cli/db-comment.md +++ b/docs/docs/cli/db-comment.md @@ -1,6 +1,6 @@ --- title: stack db comment -sidebar_position: 70 +sidebar_position: 72 --- # `stack db comment` diff --git a/docs/docs/cli/db-inspect.md b/docs/docs/cli/db-inspect.md index 5d33428..0ec38b5 100644 --- a/docs/docs/cli/db-inspect.md +++ b/docs/docs/cli/db-inspect.md @@ -1,6 +1,6 @@ --- title: stack db inspect -sidebar_position: 71 +sidebar_position: 73 --- # `stack db inspect` diff --git a/docs/docs/cli/db.md b/docs/docs/cli/db.md index 6b223e5..7297962 100644 --- a/docs/docs/cli/db.md +++ b/docs/docs/cli/db.md @@ -1,6 +1,6 @@ --- title: stack db -sidebar_position: 69 +sidebar_position: 71 --- # `stack db` diff --git a/docs/docs/cli/docs-build.md b/docs/docs/cli/docs-build.md index dd909e8..7fcd660 100644 --- a/docs/docs/cli/docs-build.md +++ b/docs/docs/cli/docs-build.md @@ -1,6 +1,6 @@ --- title: stack docs build -sidebar_position: 73 +sidebar_position: 75 --- # `stack docs build` diff --git a/docs/docs/cli/docs-generate.md b/docs/docs/cli/docs-generate.md index 9cda6d0..e039afa 100644 --- a/docs/docs/cli/docs-generate.md +++ b/docs/docs/cli/docs-generate.md @@ -1,6 +1,6 @@ --- title: stack docs generate -sidebar_position: 75 +sidebar_position: 77 --- # `stack docs generate` diff --git a/docs/docs/cli/docs-serve.md b/docs/docs/cli/docs-serve.md index 19f3262..9b7530f 100644 --- a/docs/docs/cli/docs-serve.md +++ b/docs/docs/cli/docs-serve.md @@ -1,6 +1,6 @@ --- title: stack docs serve -sidebar_position: 74 +sidebar_position: 76 --- # `stack docs serve` diff --git a/docs/docs/cli/docs.md b/docs/docs/cli/docs.md index 7dccf7d..246f84e 100644 --- a/docs/docs/cli/docs.md +++ b/docs/docs/cli/docs.md @@ -1,6 +1,6 @@ --- title: stack docs -sidebar_position: 72 +sidebar_position: 74 --- # `stack docs` diff --git a/docs/docs/cli/generate-models.md b/docs/docs/cli/generate-models.md index bb68333..e603edc 100644 --- a/docs/docs/cli/generate-models.md +++ b/docs/docs/cli/generate-models.md @@ -1,6 +1,6 @@ --- title: stack generate models -sidebar_position: 21 +sidebar_position: 23 --- # `stack generate models` diff --git a/docs/docs/cli/generate.md b/docs/docs/cli/generate.md index e532df1..36be99c 100644 --- a/docs/docs/cli/generate.md +++ b/docs/docs/cli/generate.md @@ -1,6 +1,6 @@ --- title: stack generate -sidebar_position: 20 +sidebar_position: 22 --- # `stack generate` diff --git a/docs/docs/cli/lake-deploy.md b/docs/docs/cli/lake-deploy.md index 13ce235..52bdbf9 100644 --- a/docs/docs/cli/lake-deploy.md +++ b/docs/docs/cli/lake-deploy.md @@ -1,6 +1,6 @@ --- title: stack lake deploy -sidebar_position: 55 +sidebar_position: 57 --- # `stack lake deploy` diff --git a/docs/docs/cli/lake-load.md b/docs/docs/cli/lake-load.md index 1f6c998..392d76b 100644 --- a/docs/docs/cli/lake-load.md +++ b/docs/docs/cli/lake-load.md @@ -1,6 +1,6 @@ --- title: stack lake load -sidebar_position: 56 +sidebar_position: 58 --- # `stack lake load` diff --git a/docs/docs/cli/lake-parity.md b/docs/docs/cli/lake-parity.md index 74481e5..0a8b5f9 100644 --- a/docs/docs/cli/lake-parity.md +++ b/docs/docs/cli/lake-parity.md @@ -1,6 +1,6 @@ --- title: stack lake parity -sidebar_position: 58 +sidebar_position: 60 --- # `stack lake parity` diff --git a/docs/docs/cli/lake-validate.md b/docs/docs/cli/lake-validate.md index de003f3..80465cb 100644 --- a/docs/docs/cli/lake-validate.md +++ b/docs/docs/cli/lake-validate.md @@ -1,6 +1,6 @@ --- title: stack lake validate -sidebar_position: 57 +sidebar_position: 59 --- # `stack lake validate` diff --git a/docs/docs/cli/lake.md b/docs/docs/cli/lake.md index 0960e99..88e8777 100644 --- a/docs/docs/cli/lake.md +++ b/docs/docs/cli/lake.md @@ -1,6 +1,6 @@ --- title: stack lake -sidebar_position: 54 +sidebar_position: 56 --- # `stack lake` diff --git a/docs/docs/cli/llm-eval-tags.md b/docs/docs/cli/llm-eval-tags.md index 3c6b253..4241416 100644 --- a/docs/docs/cli/llm-eval-tags.md +++ b/docs/docs/cli/llm-eval-tags.md @@ -1,6 +1,6 @@ --- title: stack llm eval-tags -sidebar_position: 66 +sidebar_position: 68 --- # `stack llm eval-tags` diff --git a/docs/docs/cli/llm-hosts.md b/docs/docs/cli/llm-hosts.md index ad11335..4a348a9 100644 --- a/docs/docs/cli/llm-hosts.md +++ b/docs/docs/cli/llm-hosts.md @@ -1,6 +1,6 @@ --- title: stack llm hosts -sidebar_position: 62 +sidebar_position: 64 --- # `stack llm hosts` diff --git a/docs/docs/cli/llm-index.md b/docs/docs/cli/llm-index.md index d91c929..27bf742 100644 --- a/docs/docs/cli/llm-index.md +++ b/docs/docs/cli/llm-index.md @@ -1,6 +1,6 @@ --- title: stack llm index -sidebar_position: 60 +sidebar_position: 62 --- # `stack llm index` diff --git a/docs/docs/cli/llm-prune-rules.md b/docs/docs/cli/llm-prune-rules.md index 970e32e..c290e58 100644 --- a/docs/docs/cli/llm-prune-rules.md +++ b/docs/docs/cli/llm-prune-rules.md @@ -1,6 +1,6 @@ --- title: stack llm prune-rules -sidebar_position: 67 +sidebar_position: 69 --- # `stack llm prune-rules` diff --git a/docs/docs/cli/llm-restamp.md b/docs/docs/cli/llm-restamp.md index 31818f8..df5e320 100644 --- a/docs/docs/cli/llm-restamp.md +++ b/docs/docs/cli/llm-restamp.md @@ -1,6 +1,6 @@ --- title: stack llm restamp -sidebar_position: 61 +sidebar_position: 63 --- # `stack llm restamp` diff --git a/docs/docs/cli/llm-serve.md b/docs/docs/cli/llm-serve.md index c4a93f3..9fc321b 100644 --- a/docs/docs/cli/llm-serve.md +++ b/docs/docs/cli/llm-serve.md @@ -1,6 +1,6 @@ --- title: stack llm serve -sidebar_position: 63 +sidebar_position: 65 --- # `stack llm serve` diff --git a/docs/docs/cli/llm-stamp-themes.md b/docs/docs/cli/llm-stamp-themes.md index 5764031..bb399a8 100644 --- a/docs/docs/cli/llm-stamp-themes.md +++ b/docs/docs/cli/llm-stamp-themes.md @@ -1,6 +1,6 @@ --- title: stack llm stamp-themes -sidebar_position: 68 +sidebar_position: 70 --- # `stack llm stamp-themes` diff --git a/docs/docs/cli/llm-tag.md b/docs/docs/cli/llm-tag.md index 7361ac2..97358fa 100644 --- a/docs/docs/cli/llm-tag.md +++ b/docs/docs/cli/llm-tag.md @@ -1,6 +1,6 @@ --- title: stack llm tag -sidebar_position: 65 +sidebar_position: 67 --- # `stack llm tag` diff --git a/docs/docs/cli/llm-vocab.md b/docs/docs/cli/llm-vocab.md index 923c8e4..7caac45 100644 --- a/docs/docs/cli/llm-vocab.md +++ b/docs/docs/cli/llm-vocab.md @@ -1,6 +1,6 @@ --- title: stack llm vocab -sidebar_position: 64 +sidebar_position: 66 --- # `stack llm vocab` diff --git a/docs/docs/cli/llm.md b/docs/docs/cli/llm.md index 3a2687a..069f1d2 100644 --- a/docs/docs/cli/llm.md +++ b/docs/docs/cli/llm.md @@ -1,6 +1,6 @@ --- title: stack llm -sidebar_position: 59 +sidebar_position: 61 --- # `stack llm` diff --git a/docs/docs/cli/mail-attach-smarthost.md b/docs/docs/cli/mail-attach-smarthost.md index 81f4327..1818125 100644 --- a/docs/docs/cli/mail-attach-smarthost.md +++ b/docs/docs/cli/mail-attach-smarthost.md @@ -1,6 +1,6 @@ --- title: stack mail attach-smarthost -sidebar_position: 118 +sidebar_position: 120 --- # `stack mail attach-smarthost` diff --git a/docs/docs/cli/mail-dkim-export.md b/docs/docs/cli/mail-dkim-export.md index fb64359..43fcd94 100644 --- a/docs/docs/cli/mail-dkim-export.md +++ b/docs/docs/cli/mail-dkim-export.md @@ -1,6 +1,6 @@ --- title: stack mail dkim-export -sidebar_position: 117 +sidebar_position: 119 --- # `stack mail dkim-export` diff --git a/docs/docs/cli/mail-dns.md b/docs/docs/cli/mail-dns.md index 20985f0..a13cd3d 100644 --- a/docs/docs/cli/mail-dns.md +++ b/docs/docs/cli/mail-dns.md @@ -1,6 +1,6 @@ --- title: stack mail dns -sidebar_position: 116 +sidebar_position: 118 --- # `stack mail dns` diff --git a/docs/docs/cli/mail-down.md b/docs/docs/cli/mail-down.md index 2eb00b7..f6cf2fb 100644 --- a/docs/docs/cli/mail-down.md +++ b/docs/docs/cli/mail-down.md @@ -1,6 +1,6 @@ --- title: stack mail down -sidebar_position: 114 +sidebar_position: 116 --- # `stack mail down` diff --git a/docs/docs/cli/mail-provision.md b/docs/docs/cli/mail-provision.md index 4c7cc6d..0cc4a87 100644 --- a/docs/docs/cli/mail-provision.md +++ b/docs/docs/cli/mail-provision.md @@ -1,6 +1,6 @@ --- title: stack mail provision -sidebar_position: 112 +sidebar_position: 114 --- # `stack mail provision` diff --git a/docs/docs/cli/mail-rotate-creds.md b/docs/docs/cli/mail-rotate-creds.md index af6b9ed..86cba90 100644 --- a/docs/docs/cli/mail-rotate-creds.md +++ b/docs/docs/cli/mail-rotate-creds.md @@ -1,6 +1,6 @@ --- title: stack mail rotate-creds -sidebar_position: 119 +sidebar_position: 121 --- # `stack mail rotate-creds` diff --git a/docs/docs/cli/mail-seed-mailboxes.md b/docs/docs/cli/mail-seed-mailboxes.md index 3ac98d3..3743602 100644 --- a/docs/docs/cli/mail-seed-mailboxes.md +++ b/docs/docs/cli/mail-seed-mailboxes.md @@ -1,6 +1,6 @@ --- title: stack mail seed-mailboxes -sidebar_position: 120 +sidebar_position: 122 --- # `stack mail seed-mailboxes` diff --git a/docs/docs/cli/mail-status.md b/docs/docs/cli/mail-status.md index fc89ac4..72ae198 100644 --- a/docs/docs/cli/mail-status.md +++ b/docs/docs/cli/mail-status.md @@ -1,6 +1,6 @@ --- title: stack mail status -sidebar_position: 115 +sidebar_position: 117 --- # `stack mail status` diff --git a/docs/docs/cli/mail-up.md b/docs/docs/cli/mail-up.md index 6988c32..e155979 100644 --- a/docs/docs/cli/mail-up.md +++ b/docs/docs/cli/mail-up.md @@ -1,6 +1,6 @@ --- title: stack mail up -sidebar_position: 113 +sidebar_position: 115 --- # `stack mail up` diff --git a/docs/docs/cli/mail-wire-git.md b/docs/docs/cli/mail-wire-git.md index c68a92a..0f234a4 100644 --- a/docs/docs/cli/mail-wire-git.md +++ b/docs/docs/cli/mail-wire-git.md @@ -1,6 +1,6 @@ --- title: stack mail wire-git -sidebar_position: 121 +sidebar_position: 123 --- # `stack mail wire-git` diff --git a/docs/docs/cli/mail.md b/docs/docs/cli/mail.md index 626ddd9..ccfa985 100644 --- a/docs/docs/cli/mail.md +++ b/docs/docs/cli/mail.md @@ -1,6 +1,6 @@ --- title: stack mail -sidebar_position: 111 +sidebar_position: 113 --- # `stack mail` diff --git a/docs/docs/cli/perf-show.md b/docs/docs/cli/perf-show.md index 4d03297..04ac799 100644 --- a/docs/docs/cli/perf-show.md +++ b/docs/docs/cli/perf-show.md @@ -1,6 +1,6 @@ --- title: stack perf show -sidebar_position: 79 +sidebar_position: 81 --- # `stack perf show` diff --git a/docs/docs/cli/perf.md b/docs/docs/cli/perf.md index 5a3296e..40feb56 100644 --- a/docs/docs/cli/perf.md +++ b/docs/docs/cli/perf.md @@ -1,6 +1,6 @@ --- title: stack perf -sidebar_position: 78 +sidebar_position: 80 --- # `stack perf` diff --git a/docs/docs/cli/pfs-cpt-ingest.md b/docs/docs/cli/pfs-cpt-ingest.md index 5095ed8..f5786f5 100644 --- a/docs/docs/cli/pfs-cpt-ingest.md +++ b/docs/docs/cli/pfs-cpt-ingest.md @@ -1,6 +1,6 @@ --- title: stack pfs cpt-ingest -sidebar_position: 93 +sidebar_position: 95 --- # `stack pfs cpt-ingest` diff --git a/docs/docs/cli/pfs-elements.md b/docs/docs/cli/pfs-elements.md index d249534..d27fe84 100644 --- a/docs/docs/cli/pfs-elements.md +++ b/docs/docs/cli/pfs-elements.md @@ -1,6 +1,6 @@ --- title: stack pfs elements -sidebar_position: 85 +sidebar_position: 87 --- # `stack pfs elements` diff --git a/docs/docs/cli/pfs-exposure.md b/docs/docs/cli/pfs-exposure.md index 1f4cf05..e2121b6 100644 --- a/docs/docs/cli/pfs-exposure.md +++ b/docs/docs/cli/pfs-exposure.md @@ -1,6 +1,6 @@ --- title: stack pfs exposure -sidebar_position: 90 +sidebar_position: 92 --- # `stack pfs exposure` diff --git a/docs/docs/cli/pfs-families.md b/docs/docs/cli/pfs-families.md index 666708b..9c6b5c5 100644 --- a/docs/docs/cli/pfs-families.md +++ b/docs/docs/cli/pfs-families.md @@ -1,6 +1,6 @@ --- title: stack pfs families -sidebar_position: 87 +sidebar_position: 89 --- # `stack pfs families` diff --git a/docs/docs/cli/pfs-guidance.md b/docs/docs/cli/pfs-guidance.md index 08c4e1d..a463a90 100644 --- a/docs/docs/cli/pfs-guidance.md +++ b/docs/docs/cli/pfs-guidance.md @@ -1,6 +1,6 @@ --- title: stack pfs guidance -sidebar_position: 88 +sidebar_position: 90 --- # `stack pfs guidance` diff --git a/docs/docs/cli/pfs-lineage.md b/docs/docs/cli/pfs-lineage.md index bed5e38..54cc2f8 100644 --- a/docs/docs/cli/pfs-lineage.md +++ b/docs/docs/cli/pfs-lineage.md @@ -1,6 +1,6 @@ --- title: stack pfs lineage -sidebar_position: 86 +sidebar_position: 88 --- # `stack pfs lineage` diff --git a/docs/docs/cli/pfs-reaction.md b/docs/docs/cli/pfs-reaction.md index 7ff6842..89b5370 100644 --- a/docs/docs/cli/pfs-reaction.md +++ b/docs/docs/cli/pfs-reaction.md @@ -1,6 +1,6 @@ --- title: stack pfs reaction -sidebar_position: 89 +sidebar_position: 91 --- # `stack pfs reaction` diff --git a/docs/docs/cli/pfs-review.md b/docs/docs/cli/pfs-review.md index b088cf0..5aa3c34 100644 --- a/docs/docs/cli/pfs-review.md +++ b/docs/docs/cli/pfs-review.md @@ -1,6 +1,6 @@ --- title: stack pfs review -sidebar_position: 92 +sidebar_position: 94 --- # `stack pfs review` diff --git a/docs/docs/cli/pfs-utilization.md b/docs/docs/cli/pfs-utilization.md index 12bbb79..a80fde9 100644 --- a/docs/docs/cli/pfs-utilization.md +++ b/docs/docs/cli/pfs-utilization.md @@ -1,6 +1,6 @@ --- title: stack pfs utilization -sidebar_position: 91 +sidebar_position: 93 --- # `stack pfs utilization` diff --git a/docs/docs/cli/pfs.md b/docs/docs/cli/pfs.md index ea57562..3b06635 100644 --- a/docs/docs/cli/pfs.md +++ b/docs/docs/cli/pfs.md @@ -1,6 +1,6 @@ --- title: stack pfs -sidebar_position: 84 +sidebar_position: 86 --- # `stack pfs` diff --git a/docs/docs/cli/prisma-eligible.md b/docs/docs/cli/prisma-eligible.md index 727026e..b7dcc28 100644 --- a/docs/docs/cli/prisma-eligible.md +++ b/docs/docs/cli/prisma-eligible.md @@ -1,6 +1,6 @@ --- title: stack prisma eligible -sidebar_position: 105 +sidebar_position: 107 --- # `stack prisma eligible` diff --git a/docs/docs/cli/prisma-export.md b/docs/docs/cli/prisma-export.md index 88bb40e..ee424e7 100644 --- a/docs/docs/cli/prisma-export.md +++ b/docs/docs/cli/prisma-export.md @@ -1,6 +1,6 @@ --- title: stack prisma export -sidebar_position: 102 +sidebar_position: 104 --- # `stack prisma export` diff --git a/docs/docs/cli/prisma-extract.md b/docs/docs/cli/prisma-extract.md index 7a89a1b..9d2650e 100644 --- a/docs/docs/cli/prisma-extract.md +++ b/docs/docs/cli/prisma-extract.md @@ -1,6 +1,6 @@ --- title: stack prisma extract -sidebar_position: 106 +sidebar_position: 108 --- # `stack prisma extract` diff --git a/docs/docs/cli/prisma-fetch.md b/docs/docs/cli/prisma-fetch.md index 7d93b0f..c75ebbb 100644 --- a/docs/docs/cli/prisma-fetch.md +++ b/docs/docs/cli/prisma-fetch.md @@ -1,6 +1,6 @@ --- title: stack prisma fetch -sidebar_position: 108 +sidebar_position: 110 --- # `stack prisma fetch` diff --git a/docs/docs/cli/prisma-flow.md b/docs/docs/cli/prisma-flow.md index 580f223..2284fc8 100644 --- a/docs/docs/cli/prisma-flow.md +++ b/docs/docs/cli/prisma-flow.md @@ -1,6 +1,6 @@ --- title: stack prisma flow -sidebar_position: 107 +sidebar_position: 109 --- # `stack prisma flow` diff --git a/docs/docs/cli/prisma-init.md b/docs/docs/cli/prisma-init.md index c44d303..1defc78 100644 --- a/docs/docs/cli/prisma-init.md +++ b/docs/docs/cli/prisma-init.md @@ -1,6 +1,6 @@ --- title: stack prisma init -sidebar_position: 101 +sidebar_position: 103 --- # `stack prisma init` diff --git a/docs/docs/cli/prisma-ping-llm.md b/docs/docs/cli/prisma-ping-llm.md index 839c6b0..87ad272 100644 --- a/docs/docs/cli/prisma-ping-llm.md +++ b/docs/docs/cli/prisma-ping-llm.md @@ -1,6 +1,6 @@ --- title: stack prisma ping-llm -sidebar_position: 103 +sidebar_position: 105 --- # `stack prisma ping-llm` diff --git a/docs/docs/cli/prisma-run.md b/docs/docs/cli/prisma-run.md index f501c04..4077344 100644 --- a/docs/docs/cli/prisma-run.md +++ b/docs/docs/cli/prisma-run.md @@ -1,6 +1,6 @@ --- title: stack prisma run -sidebar_position: 109 +sidebar_position: 111 --- # `stack prisma run` diff --git a/docs/docs/cli/prisma-screen.md b/docs/docs/cli/prisma-screen.md index 791436f..2194dc5 100644 --- a/docs/docs/cli/prisma-screen.md +++ b/docs/docs/cli/prisma-screen.md @@ -1,6 +1,6 @@ --- title: stack prisma screen -sidebar_position: 104 +sidebar_position: 106 --- # `stack prisma screen` diff --git a/docs/docs/cli/prisma-vpn.md b/docs/docs/cli/prisma-vpn.md index 17d6180..389be23 100644 --- a/docs/docs/cli/prisma-vpn.md +++ b/docs/docs/cli/prisma-vpn.md @@ -1,6 +1,6 @@ --- title: stack prisma vpn -sidebar_position: 110 +sidebar_position: 112 --- # `stack prisma vpn` diff --git a/docs/docs/cli/prisma.md b/docs/docs/cli/prisma.md index c8e2360..6ed6413 100644 --- a/docs/docs/cli/prisma.md +++ b/docs/docs/cli/prisma.md @@ -1,6 +1,6 @@ --- title: stack prisma -sidebar_position: 100 +sidebar_position: 102 --- # `stack prisma` diff --git a/docs/docs/cli/rec-list.md b/docs/docs/cli/rec-list.md index 43fc0d9..585423f 100644 --- a/docs/docs/cli/rec-list.md +++ b/docs/docs/cli/rec-list.md @@ -1,6 +1,6 @@ --- title: stack rec list -sidebar_position: 81 +sidebar_position: 83 --- # `stack rec list` diff --git a/docs/docs/cli/rec-opps.md b/docs/docs/cli/rec-opps.md index 76f4380..b7973e2 100644 --- a/docs/docs/cli/rec-opps.md +++ b/docs/docs/cli/rec-opps.md @@ -1,6 +1,6 @@ --- title: stack rec opps -sidebar_position: 83 +sidebar_position: 85 --- # `stack rec opps` diff --git a/docs/docs/cli/rec-pfs.md b/docs/docs/cli/rec-pfs.md index d1b5bdd..d672025 100644 --- a/docs/docs/cli/rec-pfs.md +++ b/docs/docs/cli/rec-pfs.md @@ -1,6 +1,6 @@ --- title: stack rec pfs -sidebar_position: 82 +sidebar_position: 84 --- # `stack rec pfs` diff --git a/docs/docs/cli/rec.md b/docs/docs/cli/rec.md index a866e70..dc92750 100644 --- a/docs/docs/cli/rec.md +++ b/docs/docs/cli/rec.md @@ -1,6 +1,6 @@ --- title: stack rec -sidebar_position: 80 +sidebar_position: 82 --- # `stack rec` diff --git a/docs/docs/cli/zot-dump-schema.md b/docs/docs/cli/zot-dump-schema.md index 59b7dd7..9d52972 100644 --- a/docs/docs/cli/zot-dump-schema.md +++ b/docs/docs/cli/zot-dump-schema.md @@ -1,6 +1,6 @@ --- title: stack zot dump-schema -sidebar_position: 95 +sidebar_position: 97 --- # `stack zot dump-schema` diff --git a/docs/docs/cli/zot-fix-dates.md b/docs/docs/cli/zot-fix-dates.md index 579f7ff..b2c6fca 100644 --- a/docs/docs/cli/zot-fix-dates.md +++ b/docs/docs/cli/zot-fix-dates.md @@ -1,6 +1,6 @@ --- title: stack zot fix-dates -sidebar_position: 96 +sidebar_position: 98 --- # `stack zot fix-dates` diff --git a/docs/docs/cli/zot-fix-fields.md b/docs/docs/cli/zot-fix-fields.md index f34bb5d..4ece6b7 100644 --- a/docs/docs/cli/zot-fix-fields.md +++ b/docs/docs/cli/zot-fix-fields.md @@ -1,6 +1,6 @@ --- title: stack zot fix-fields -sidebar_position: 98 +sidebar_position: 100 --- # `stack zot fix-fields` diff --git a/docs/docs/cli/zot-fix-keys.md b/docs/docs/cli/zot-fix-keys.md index 29c4791..f7cafbe 100644 --- a/docs/docs/cli/zot-fix-keys.md +++ b/docs/docs/cli/zot-fix-keys.md @@ -1,6 +1,6 @@ --- title: stack zot fix-keys -sidebar_position: 97 +sidebar_position: 99 --- # `stack zot fix-keys` diff --git a/docs/docs/cli/zot-verify-parity.md b/docs/docs/cli/zot-verify-parity.md index 7010ffa..864fb05 100644 --- a/docs/docs/cli/zot-verify-parity.md +++ b/docs/docs/cli/zot-verify-parity.md @@ -1,6 +1,6 @@ --- title: stack zot verify-parity -sidebar_position: 99 +sidebar_position: 101 --- # `stack zot verify-parity` diff --git a/docs/docs/cli/zot.md b/docs/docs/cli/zot.md index 316e411..748c6d3 100644 --- a/docs/docs/cli/zot.md +++ b/docs/docs/cli/zot.md @@ -1,6 +1,6 @@ --- title: stack zot -sidebar_position: 94 +sidebar_position: 96 --- # `stack zot` diff --git a/docs/superpowers/specs/2026-10-25-bcda-since-reconciliation-design.md b/docs/superpowers/specs/2026-10-25-bcda-since-reconciliation-design.md new file mode 100644 index 0000000..4c4837b --- /dev/null +++ b/docs/superpowers/specs/2026-10-25-bcda-since-reconciliation-design.md @@ -0,0 +1,240 @@ +# BCDA `_since` pulls: ingest, reconcile, and prove it — design (2026-10-25) + +Part of P52 (#1139). Companion to `2026-10-25-bcda-v3-design.md`. + +## Intent + +A `_since` export is cheap (minutes, megabytes) where a full pull is not (the +Large entity's EOBs are 6 min and 2.2 GB). Today the manager can *start* one +(the Exports page has a date picker, the CLI a `--since` flag) but nothing +downstream knows what to do with the result: the loader flattens "the newest +export directory per type", so a delta silently *replaces* the full pull it +was meant to extend. This design makes incremental pulls safe end to end: +choose the right `_since`, refuse the wrong one, ingest the delta, reconcile +it with everything already on disk under explicit tiebreakers, and keep a +ledger that proves the invariants held. + +## What the API actually promises (sources of truth) + +From bcda.cms.gov (How to Filter Claims Data, How to Migrate to v3, FAQs) and +the vendored `bcda-app` (`validation.go`, `requests.go`): + +- `_since` filters on **`meta.lastUpdated`**, FHIR instant with offset; the + server rejects an unparseable value or one in the future (400). +- `/Group/all` with `_since` returns resources updated after the instant for + existing enrollees **and all resources for newly attributed enrollees** + (`RetrieveNewBeneHistData`); `/Patient` returns only updated resources. + So a delta legitimately contains rows whose `lastUpdated` predates + `_since` — *backfill* for new beneficiaries, not late data. +- Recommended cadence: one unfiltered pull, then each later pull's `_since` + = the previous job's **`transactionTime`** (in the completed-job manifest). +- No v3 resource has `lastUpdated` before **2026-03-26**; an earlier + `_since` is a full pull in disguise. +- **Each version of a claim has a unique FHIR id**; track claims by + **claim control number** (`identifier.system = …/CLM-CNTL-NUM`). Corrected + claims show a newer `lastUpdated`. An adjustment may carry the original + control number as a related claim (`clm_orig_cntl_num`). +- `Final-Action` tag: `FinalAction` / `NotFinalAction` (9% of the Large + entity). Within one snapshot a control number appears once (verified on + the real pull: 0 of 9,342 control numbers repeated; 887 all-NotFinalAction). +- Default `_typeFilter` omits `SharedSystem`; a delta pulled with a different + filter scope than its baseline covers a different population of claims. +- Attribution files update monthly; `attribution_status` reports + `last_attribution_update`. Enrollees who *leave* attribution are not + signalled by a delta — only a new baseline reveals attrition. +- Completed jobs serve files for 24 h. + +Observed on the real Large-entity pull: Patient ids are `BENE_SK` +(`-100040134`), Coverage ids are composite (`part-c--100040134-Z0004--01`), +EOB FHIR ids are opaque with a `CLM-CNTL-NUM` identifier on every row; +`meta.versionId` is absent everywhere, so `lastUpdated` is the only version +clock. + +## Decisions + +### Vocabulary + +- **Baseline**: a complete job without `_since`. Authoritative snapshot for + the types it carries, as of its `transactionTime`. +- **Delta**: a complete job with `_since`. +- **Population**: `current` (`Group/all` and `/Patient` both describe the + currently attributed enrollees) or `runout` (`Group/runout`, last year's). + This is the hard boundary: a delta never feeds a baseline of the other + population. A `/Patient` delta over a `Group/all` baseline is allowed and + warned (`backfill_scope`: no history for newly attributed enrollees). +- **Scope**: `(population, _typeFilter)`. Watermarks are kept per scope and + type. A delta whose `_typeFilter` differs from its baseline's is still + reconciled (its rows are genuine newer versions) but warned + (`scope_filter`) and noted in the ledger as scope drift: claims outside + its filter were not refreshed. +- **Watermark** per `(scope, type)`: the greatest `transactionTime` among + complete (downloaded) jobs. The next `_since` *is* the watermark. +- **Applied**: a job whose rows have been reconciled into the current tables + (recorded in the sync ledger). + +### First order — which row is current (per resource) + +Identity keys: + +| table | key | why | +|---|---|---| +| `bcda.patient` | `bene_id` (falls back to `id`) | `Patient.id` is `BENE_SK`; MBIs rotate | +| `bcda.coverage` | `id` | composite bene × plan × sequence | +| `bcda.explanation_of_benefit` | `clm_cntl_num`, else `clm_id`, else `id` | a claim version gets a new FHIR id; the control number is the claim | +| `bcda.eob_item` | follows its header (`clm_id` + job) | lines are replaced wholesale with their header | + +Candidate rows for a type = rows of the newest applied baseline carrying it +∪ rows of applied deltas of the same population whose `transactionTime` ≥ +that baseline's. Deltas older than the authoritative baseline are ignored +for current state (the baseline already contains their effect, and must be +allowed to *retire* rows they carried); deltas of the other population are +ignored with a ledger note. + +Winner per key, in order, each applied only when the previous ties: + +1. greatest `last_updated` (the resource's own version clock); +2. source rank — `NationalClaimsHistory`/`DDPS` over `SharedSystem` (the + connector's existing rule, so the two layers agree); +3. greatest job `transactionTime` (the server's view is later); +4. greatest applied sequence (we saw it later); +5. greatest FHIR `id` string (total order; never reached in practice, + present so the result is a pure function of the inputs). + +A winner tagged `NotFinalAction` stays in the table as a **tombstone**: it +records that the claim's latest version is not final, and the connector +(`_stg_claim_header`) already drops it from `input_layer`. Rows are never +deleted from current tables by a delta; only a baseline retires rows. + +### Second order — consistency across resources and across time + +Computed per applied job and stored in the ledger as counts: + +- `new` / `replaced` / `unchanged` / `stale_ignored` — key not seen before / + seen with a different id or older `last_updated` / identical id and + `last_updated` (an overlap re-delivery) / older than what we hold. +- `backfill` vs `late` — delta rows with `last_updated < _since`. Backfill + is the API's promise for newly attributed enrollees (bene not in the prior + Patient set); `late` is the same shape for a bene we already had, which + the API says should not happen, so it is a warning. +- `tombstoned` — winners tagged `NotFinalAction`. +- `adjusted` — EOB winners carrying `clm_orig_cntl_num`; the original control + number is marked superseded in `bcda.eob_supersession` so analyses can + follow the chain. +- `retired` — keys present before a baseline that the baseline no longer + carries (attrition, opt-out, or scope change). Only a baseline can retire. +- `orphan_claims` / `orphan_coverage` — EOB or Coverage rows whose + beneficiary is not in current Patient (Patient delta missing, or Patient + baseline older than the claims baseline). +- `scope_drift` — a delta whose `_typeFilter` differs from its baseline's. + +### Third order — invariants over the whole store, checked on every apply + +1. Keys are unique in every current table. +2. Count conservation per type: `|current'| = |current| + new − retired`. +3. Watermark per `(scope, type)` never decreases. +4. Every `eob_item.clm_id` belongs to a current EOB header. +5. Replay determinism: current state is a pure function of the *set* of + applied jobs — applying in a different order yields identical tables + (tested), and re-applying a job is a no-op (idempotent; tested). +6. The ledger is append-only and every current row names the job it came + from (`_job_key`, `_transaction_time`), so any value can be traced to + an ndjson line on disk. + +A violated invariant raises `SyncInvariantError`, the ledger row is written +with `ok = false`, and the current tables are left as they were. + +### Temporality checks before a `_since` export starts + +`check_since(store, since, endpoint, types, type_filter)` returns findings +with levels `ok` / `warn` / `block`; the UI and CLI refuse to start on +`block` unless `--force`: + +| code | level | rule | +|---|---|---| +| `format` | block | not a FHIR instant with offset | +| `future` | block | later than now (server would 400) | +| `floor` | warn | before 2026-03-26 — this is a full pull in disguise | +| `no_baseline` | block | no complete baseline for a requested type in this scope | +| `gap` | block | `since` > watermark: the window (watermark, since) would never be fetched | +| `overlap` | ok | `since` < watermark: re-delivery, reconciliation is idempotent | +| `endpoint_mix` | block | baseline and delta describe different populations (`Group/runout` vs the rest) | +| `backfill_scope` | warn | `/Patient` delta over a `Group/all` baseline: newly attributed enrollees arrive without history | +| `scope_filter` | warn | `_typeFilter` differs from the baseline's; rows reconcile, nothing outside the filter refreshes | +| `inflight` | warn | a job for the same scope/type is still pending or polling | +| `unapplied` | warn | downloaded jobs not yet reconciled | +| `attribution_newer` | warn | `last_attribution_update` > baseline `transactionTime`: expect backfill for new enrollees; attrition stays invisible until the next baseline | +| `stale_baseline` | warn | baseline older than 24 h × 30: files are gone, only a new baseline can retire rows | + +`next_since()` formats the watermark as `YYYY-MM-DDThh:mm:ss.sss+00:00`. + +### Storage and data flow + +``` +exports//*.ndjson, manifest.json (store: + transaction_time, request on the job row) + │ flatten (existing v3 flatteners, per job) + ▼ +flat/history//{patient,coverage,explanation_of_benefit,eob_item}.parquet + │ + _job_key, _transaction_time, _since, _kind, _applied_seq + │ reconcile (DuckDB over the history partitions) + ▼ +flat/{patient,coverage,explanation_of_benefit,eob_item}.parquet ← current state +flat/eob_supersession.parquet, flat/sync_ledger.parquet + │ load_bcda (unchanged read path) → bcda.* → connector → input_layer.* → replica +``` + +`load_bcda()` gains `reconcile=True`: when the store has complete jobs it +applies the unapplied ones and loads the current tables (plus +`bcda.sync_ledger`, `bcda.sync_watermark`, `bcda.eob_supersession`). An +explicit `ndjson_dir` keeps the legacy "flatten these directories" path. + +Details settled while building: + +- The store now writes `exports//manifest.json` (the completed-job + body) and puts `transaction_time` and `request` on the job row; jobs + recorded before that fall back to the manifest, then to the instant the + `complete` row was written (later than the true cut-off, so a safe, + overlapping `_since`; the ledger records which source was used). An + adopted job's `_since` is read from its request line. +- Current tables carry `_job_key`, `_transaction_time`, `_since`, `_kind`, + `_applied_seq`; the connector's `_ensure()` drops `_`-prefixed columns + before the stage contracts see them. +- `_since` on a combined (multi-type) job resolves to the *earliest* + watermark across the requested types. +- The sandbox reports `transactionTime` as midnight UTC of the run day + (a `/Patient` delta run 19:25–19:38Z carried `2026-10-25T00:00:00Z`), so + a watermark `_since` can overlap by up to a day. Overlap reconciles to + `unchanged`; it costs download time, never correctness. +- A delta with nothing to deliver (200, empty `output`) has no file rows; + its manifest makes it a job and it advances the watermark. +- Verified on the real Large-entity pull (2026-10-25): applying the three + baselines over the legacy `flat/` tables reported every row `unchanged`, + zero `new`/`retired`, and the loaded counts were identical to the + earlier full load (221,021 medical lines, 11,968 pharmacy, 9,582 + eligibility). Replay of the tests' delta scenario in either order yields + byte-identical tables. + +### Surfaces + +- `bcda.sync`: `parse_instant`, `format_instant`, `watermarks`, `next_since`, + `check_since`, `apply`, `status`, `SyncReport`, `SyncInvariantError`. +- `stack bcda sync status|check|pull|apply`; `stack bcda export --since auto`. +- Manager: Exports page gets a `_since` mode (off / watermark / date) with + the checks shown before the run and `block` respected; new **Sync** page + (watermarks, pending, apply, ledger). +- Notebook section 8 · Incremental. + +## Non-goals + +- Deleting rows on a delta. The API cannot express deletion; only a baseline + retires rows. +- Reconciling across scopes (e.g. `Group/all` baseline with `Group/runout` + deltas) or across API versions. +- `_until` (not offered by BCDA). + +## Assumptions (made here, not confirmed by the user) + +- Claims identity by control number is correct for all three claim systems + (NCH, DDPS, SharedSystem); for the rare row without one, the FHIR id is + the key and such a claim can only be replaced by an identical id. +- Overlap by default is zero: `_since` = watermark exactly, as BCDA advises. + `SINCE_OVERLAP_SECONDS` (conf) widens it; reconciliation makes overlap free. diff --git a/docs/superpowers/specs/2026-10-25-bcda-v3-design.md b/docs/superpowers/specs/2026-10-25-bcda-v3-design.md index 7fe76cf..eae8156 100644 --- a/docs/superpowers/specs/2026-10-25-bcda-v3-design.md +++ b/docs/superpowers/specs/2026-10-25-bcda-v3-design.md @@ -92,3 +92,7 @@ Tests: service with `httpx.MockTransport`, runner for thread-routed logs and sta Reachability needs more than `stack.toml` + Traefik + CoreDNS: the Cloudflare tunnel runs on a remote ingress list that overrides the wildcard in `infra/cloudflared/config.yml` (an unlisted host answers 530 at the edge), and the public CNAME to the tunnel is created from the same list. Both come from `SUBDOMAINS` in `dev/scripts/bootstrap_sso.py`, which gained `bcda` and a `--dns-only` mode that does just those two writes with a token holding Account:Cloudflare Tunnel:Edit and Zone:DNS:Edit for fhirworx.io. Resolvers that had asked before the record existed cache NXDOMAIN for the zone's negative TTL (1800 s). House style: `src/bcda/ui/theme.toml` is a Streamlit theme file carrying the dashboard tokens (`assets/css/dashboard.css`: cream paper, near-black ink, navy primary and sidebar, warm beige surfaces, 2px radius, Playfair Display / Source Serif 4 / JetBrains Mono). `python -m bcda.ui` passes it as `--theme.base` so the container and `stack bcda ui` match without a per-cwd `.streamlit/config.toml`. `bcda.ui.brand` adds what a theme file cannot: the Google Fonts import, the dashboard masthead in the sidebar (rule, display title, monospace eyebrow) and `brand.title()` eyebrows above every page title; the favicon is the repo's `assets/icons/fav32.png`, baked into the image. `tests/bcda/test_ui_brand.py` fails if the theme's hexes or font stacks drift from `dashboard.css`. + +### Incremental pulls (2026-10-25) + +`_since` pulls are reconciled rather than loaded over the baseline — watermarks, temporality checks, tiebreakers, ledger and invariants are in `2026-10-25-bcda-since-reconciliation-design.md` (`bcda.sync`, `stack bcda sync`, the manager's **Sync** page and the Exports page's `_since` modes). diff --git a/notebooks/bcda_v3_sandbox.py b/notebooks/bcda_v3_sandbox.py index 42a784f..4d6ae54 100644 --- a/notebooks/bcda_v3_sandbox.py +++ b/notebooks/bcda_v3_sandbox.py @@ -939,5 +939,85 @@ def _(ROOT, con, mo, pl, q): return +@app.cell(hide_code=True) +def _(STORE_PATH, mo, pl): + """## 8 · Incremental pulls — watermarks, checks, ledger.""" + from bcda import sync as _sync + from bcda.store import Store as _Store + + _store = _Store(path=str(STORE_PATH)) + _status = _sync.status(_store) + _next = _sync.next_since(_store) + _blocks = [] + for _rtype, _since in _next.items(): + if _since is None: + _blocks.append( + { + "type": _rtype, + "_since": "— no baseline —", + "level": "block", + "code": "no_baseline", + "message": "run an unfiltered pull first", + } + ) + continue + for _c in _sync.check_since(_store, _since, types=[_rtype]): + _blocks.append({"type": _rtype, "_since": _since, **_c.__dict__}) + _ledger_rows = [ + { + "seq": _r["applied_seq"], + "job": _r["job_key"], + "kind": _r["kind"], + "ok": _r["ok"], + "since": _r["since"], + "transaction_time": _r["transaction_time"], + "table": _t, + **_c, + } + for _r in _status["ledger"] + for _t, _c in (_r["counts"] or {}).items() + ] + mo.vstack( + [ + mo.md(f""" + ## 8 · Incremental pulls (`_since`) + + BCDA filters `_since` on `meta.lastUpdated`, returns **all** resources for newly attributed + enrollees on `/Group/all`, and recommends the previous job's `transactionTime` as the next `_since`. + Each claim *version* has a new FHIR id, so claims are keyed by control number; the newest + `lastUpdated` wins, then NCH/DDPS over SharedSystem, then the later job. Only a baseline retires rows. + `bcda.sync` keeps a per-job ledger and re-derives the current tables from the applied set on every + apply, so the result is independent of arrival order (tested in `tests/bcda/test_sync.py`). + + Store: `{STORE_PATH}` · {len(_status["jobs"])} complete job(s), {len(_status["pending"])} not yet reconciled. + Next `_since`: {", ".join(f"`{t}` → `{v or '—'}`" for t, v in _next.items())} + """), + mo.ui.table( + pl.DataFrame(_status["watermarks"]) + if _status["watermarks"] + else pl.DataFrame({"note": ["no complete jobs"]}), + label="Watermarks", + ), + mo.ui.table( + pl.DataFrame(_blocks).select( + "type", "_since", "level", "code", "message" + ) + if _blocks + else pl.DataFrame({"note": ["—"]}), + label="Checks for the watermark _since", + ), + mo.ui.table( + pl.DataFrame(_ledger_rows) + if _ledger_rows + else pl.DataFrame( + {"note": ["nothing applied yet — `stack bcda sync apply`"]} + ), + label="Sync ledger (per job × table)", + ), + ] + ) + return + + if __name__ == "__main__": app.run() diff --git a/src/aco/load/bcda.py b/src/aco/load/bcda.py index 7fee4d8..2f0d27a 100644 --- a/src/aco/load/bcda.py +++ b/src/aco/load/bcda.py @@ -23,6 +23,7 @@ def load_bcda( *, skip_flatten: bool = False, run_pipeline: bool = False, + reconcile: bool = True, ) -> dict[str, int]: """Flatten BCDA ndjson and load into DuckDB. @@ -44,6 +45,15 @@ def load_bcda( ``input_layer.pharmacy_claim`` and ``input_layer.eligibility`` — the same tables the CCLF loader writes. Off by default because it replaces whatever source last wrote them. + reconcile : bool + With no explicit *ndjson_dir*, reconcile the store's complete + jobs through :mod:`bcda.sync` (baselines + ``_since`` deltas → + one current state under explicit tiebreakers, ledger kept) + instead of flattening the newest export directory per type. + Falls back to the legacy path when the store has no job ledger + (bare ``exports/`` directories). ``bcda.sync_ledger``, + ``bcda.sync_watermark`` and ``bcda.eob_supersession`` are + loaded alongside the resource tables. Returns ------- @@ -57,10 +67,19 @@ def load_bcda( db_path = database or str(path("db.aco")) store_path = path("storage.bcda") - if ndjson_dir is None: + reconciled = False + if ndjson_dir is None and reconcile and not skip_flatten: + from bcda import sync + from bcda.store import Store + + store = Store(path=str(store_path)) + if sync.complete_jobs(store): + sync.apply(store) + reconciled = True + if ndjson_dir is None and not reconciled: ndjson_dir = _find_latest_export(store_path) - if not skip_flatten: + if not skip_flatten and not reconciled: from bcda.express.flatten import flatten_export flatten_export(ndjson_dir, store_path) @@ -79,6 +98,9 @@ def load_bcda( "explanation_of_benefit": "bcda.explanation_of_benefit", "eob_item": "bcda.eob_item", "coverage": "bcda.coverage", + # written by bcda.sync when the store was reconciled + "eob_supersession": "bcda.eob_supersession", + "sync_ledger": "bcda.sync_ledger", } for file_stem, table_ref in parquet_map.items(): @@ -95,6 +117,20 @@ def load_bcda( count = con.execute(f"SELECT COUNT(*) FROM {qualified}").fetchone()[0] stats[table_ref] = count + if "bcda.sync_ledger" in stats: + # newest cut-off per (endpoint, _typeFilter, resource type) among applied jobs + con.execute("DROP VIEW IF EXISTS bcda.sync_watermark") + con.execute( + "CREATE VIEW bcda.sync_watermark AS " + "SELECT CASE WHEN endpoint = 'Group/runout' THEN 'runout' ELSE 'current' END AS population, " + "type_filter, resource_type, " + "arg_max(job_key, transaction_time) AS job_key, " + "max(transaction_time) AS transaction_time, " + "arg_max(kind, transaction_time) AS kind " + "FROM (SELECT l.*, unnest(string_split(l.types, ',')) AS resource_type " + "FROM bcda.sync_ledger l WHERE l.ok) " + "GROUP BY 1, 2, 3" + ) con.close() if run_pipeline and stats: stats.update(_run_bcda_pipeline(db_path)) diff --git a/src/bcda/express/cclf.py b/src/bcda/express/cclf.py index 5d8776a..2e5616c 100644 --- a/src/bcda/express/cclf.py +++ b/src/bcda/express/cclf.py @@ -175,8 +175,18 @@ _ITEM_COLS: dict[str, Any] = { def _ensure(df: FrameT, cols: dict[str, Any]) -> FrameT: - """Add any missing column as a typed NULL literal.""" - have = set(df.collect_schema().names()) + """Add any missing column as a typed NULL literal; drop provenance columns. + + Reconciled ``bcda.*`` tables carry ``_job_key``, ``_transaction_time``, + ``_since``, ``_kind`` and ``_applied_seq`` (``bcda.sync``) so every + row can be traced to the export it came from. They are not claim + data and the stage contracts do not list them. + """ + names = df.collect_schema().names() + provenance = [c for c in names if c.startswith("_")] + if provenance: + df = df.drop(*provenance) + have = set(names) - set(provenance) missing = [ nw.lit(None).cast(dt).alias(c) for c, dt in cols.items() if c not in have ] diff --git a/src/bcda/express/flatten.py b/src/bcda/express/flatten.py index 9fe9a1a..81c2f1d 100644 --- a/src/bcda/express/flatten.py +++ b/src/bcda/express/flatten.py @@ -1078,6 +1078,7 @@ def flatten_export( store_path: str | Path | None = None, *, storage_options: dict | None = None, + out_dir: str = "flat", ) -> dict[str, int]: """Flatten raw FHIR ndjson files and write to Parquet. @@ -1106,6 +1107,11 @@ def flatten_export( ``Store(path=...)`` convention. storage_options : dict or None Extra arguments for ``fsspec.filesystem()``. + out_dir : str + Directory under *store_path* for the Parquet files (default + ``flat``). ``bcda.sync`` flattens each job into + ``flat/history/`` and reconciles those partitions into + ``flat/``. """ import fsspec @@ -1124,7 +1130,9 @@ def flatten_export( # Patient if files.get("Patient"): t0 = time.monotonic() - sink = _ParquetSink(fs, f"{root}/flat/patient.parquet", arrow_schema(Patient)) + sink = _ParquetSink( + fs, f"{root}/{out_dir}/patient.parquet", arrow_schema(Patient) + ) batch: list[dict] = [] for raw in _iter_ndjson(files["Patient"]): batch.append(flatten_patient(raw).model_dump()) @@ -1146,11 +1154,11 @@ def flatten_export( t0 = time.monotonic() head_sink = _ParquetSink( fs, - f"{root}/flat/explanation_of_benefit.parquet", + f"{root}/{out_dir}/explanation_of_benefit.parquet", arrow_schema(ExplanationOfBenefit), ) item_sink = _ParquetSink( - fs, f"{root}/flat/eob_item.parquet", arrow_schema(EobItem) + fs, f"{root}/{out_dir}/eob_item.parquet", arrow_schema(EobItem) ) heads: list[dict] = [] items: list[dict] = [] @@ -1183,7 +1191,9 @@ def flatten_export( # Coverage if files.get("Coverage"): t0 = time.monotonic() - sink = _ParquetSink(fs, f"{root}/flat/coverage.parquet", arrow_schema(Coverage)) + sink = _ParquetSink( + fs, f"{root}/{out_dir}/coverage.parquet", arrow_schema(Coverage) + ) batch = [] for raw in _iter_ndjson(files["Coverage"]): batch.append(flatten_coverage(raw).model_dump()) diff --git a/src/bcda/store.py b/src/bcda/store.py index dd2dc51..dda059f 100644 --- a/src/bcda/store.py +++ b/src/bcda/store.py @@ -39,6 +39,7 @@ Usage:: from __future__ import annotations +import json import logging import random import string @@ -67,6 +68,13 @@ JOBS_SCHEMA = pa.schema( ("since", pa.string()), ("status", pa.string()), ("error", pa.string()), + # From the completed-job manifest (v3 ``/jobs/`` 200 body): + # ``transactionTime`` is the server's cut-off for the export and + # the value BCDA says to pass as the next ``_since``; ``request`` + # is the originating $export URL. Older ledgers lack the columns + # and read back as NULL (parquet schema evolution). + ("transaction_time", pa.string()), + ("request", pa.string()), ] ) @@ -93,6 +101,20 @@ def _generate_key() -> str: return "".join(random.choices(chars, k=8)) # noqa: S311 +def _since_from_request(request: str) -> str: + """The ``_since`` value in an ``$export`` request URL (``""`` if none). + + An adopted job was started by someone else; its request line is the + only record of whether it was a baseline or a delta. + """ + from urllib.parse import parse_qs, urlsplit + + if not request: + return "" + url = request.split(" ", 1)[1] if " " in request else request + return (parse_qs(urlsplit(url).query).get("_since") or [""])[0] + + def _current_state(table: pa.Table, key_col: str) -> pa.Table: """Deduplicate an append-only table, keeping the last row per key.""" if table.num_rows == 0: @@ -251,6 +273,34 @@ class Store: fs.put_file(str(local_path), dest) return dest + @property + def root(self) -> str: + """The store's root path/URI (``exports/``, ``flat/`` and the ledgers live under it).""" + return self._root + + # ── Job manifests ──────────────────────────────────────── + + def _write_manifest(self, job_key: str, result: dict) -> None: + """Keep the completed-job response next to its files. + + ``transactionTime`` and ``request`` also go on the job row; the + whole body is kept because ``bcda.sync`` reads the cut-off from + here for jobs recorded before the columns existed, and the + ``output`` list is the authoritative part inventory. + """ + self._ensure_dir(self._full("exports", job_key)) + with self._fs().open(self._full("exports", job_key, "manifest.json"), "w") as f: + json.dump(result, f, indent=1, sort_keys=True, default=str) + + def manifest(self, job_key: str) -> dict: + """The completed-job response saved by :meth:`_write_manifest` (``{}`` if none).""" + path = self._full("exports", job_key, "manifest.json") + fs = self._fs() + if not fs.exists(path): + return {} + with fs.open(path, "r") as f: + return json.load(f) + def open(self, storage_path: str, mode: str = "rb"): """Open a file from the storage backend.""" return self._fs().open(storage_path, mode) @@ -361,7 +411,10 @@ class Store: types=types_str, since=since or "", status="complete", + transaction_time=result.get("transactionTime", "") or "", + request=result.get("request", "") or "", ) + self._write_manifest(key, result) # 4. Download files. self._download_outputs(client, key, result) @@ -423,8 +476,12 @@ class Store: job_url=job_url, endpoint=endpoint, types=types_str, + since=_since_from_request(result.get("request", "")), status="complete", + transaction_time=result.get("transactionTime", "") or "", + request=result.get("request", "") or "", ) + self._write_manifest(key, result) self._download_outputs(client, key, result) except Exception as exc: log.error("Adopt %s failed: %s", key, exc, extra={"job_key": key}) @@ -601,7 +658,10 @@ class Store: types=job["types"], since=job["since"], status="complete", + transaction_time=result.get("transactionTime", "") or "", + request=result.get("request", "") or "", ) + self._write_manifest(key, result) status = "complete" except Exception as exc: self._append_job( @@ -628,6 +688,22 @@ class Store: job["job_url"], interval=poll_interval, ) + if not self.manifest(key) or not job.get("transaction_time"): + # A job recorded before manifests existed (or whose + # completion the old code wrote without them): fill in + # the cut-off so bcda.sync can place it. + self._write_manifest(key, result) + self._append_job( + key=key, + job_url=job["job_url"], + endpoint=job["endpoint"], + types=job["types"], + since=job["since"] + or _since_from_request(result.get("request", "")), + status="complete", + transaction_time=result.get("transactionTime", "") or "", + request=result.get("request", "") or "", + ) pending = [ e for e in result.get("output", []) if e["url"] not in completed_urls diff --git a/src/bcda/sync.py b/src/bcda/sync.py new file mode 100644 index 0000000..a956d78 --- /dev/null +++ b/src/bcda/sync.py @@ -0,0 +1,1094 @@ +"""Incremental BCDA pulls: choose ``_since``, refuse the wrong one, reconcile the result. + +Design: ``docs/superpowers/specs/2026-10-25-bcda-since-reconciliation-design.md``. + +The API's contract (bcda.cms.gov, vendored ``bcda-app``): ``_since`` +filters on ``meta.lastUpdated``; ``/Group/all`` deltas also carry *all* +resources of newly attributed enrollees (backfill); the next ``_since`` +is the previous job's ``transactionTime``; each claim *version* has a +new FHIR id, so claims are tracked by control number; nothing in a delta +can express deletion. Three layers follow from that: + +1. **First order** — which row is current per key + (:data:`KEY_EXPR`, :func:`_rank_order`): newest ``last_updated``, + then NCH/DDPS over SharedSystem, then later ``transactionTime``, + later applied sequence, larger FHIR id. Candidates are the newest + applied baseline of a type plus the deltas at or after it. +2. **Second order** — what a job did to the store: ``new`` / + ``replaced`` / ``unchanged`` / ``stale_ignored`` / ``backfill`` / + ``late`` / ``tombstoned`` / ``adjusted`` / ``retired`` / orphans, + written to the ledger per job and table. +3. **Third order** — invariants over the whole store after every + apply (:func:`_invariants`): unique keys, count conservation, + monotone watermarks, item↔header integrity; replay determinism and + idempotency are properties of the recompute and are tested. + +Temporality checks for a proposed ``_since`` live in :func:`check_since`; +:func:`next_since` formats the watermark. Current tables land where the +loader already reads them (``flat/.parquet``); per-job partitions +are kept under ``flat/history//`` and the ledger in +``flat/sync_ledger.parquet``. Reconciliation runs DuckDB over local +Parquet, so this module expects a local store root. +""" + +from __future__ import annotations + +import json +import logging +import os +import re +from dataclasses import asdict, dataclass, field +from datetime import datetime, timedelta, timezone +from pathlib import Path +from typing import TYPE_CHECKING, Any + +import pyarrow as pa +import pyarrow.parquet as pq + +if TYPE_CHECKING: + from bcda.store import Store + +log = logging.getLogger(__name__) + +# No v3 resource has lastUpdated before this (How to Filter Claims Data); +# an earlier _since is a full pull in disguise. +V3_FLOOR = datetime(2026, 3, 26, tzinfo=timezone.utc) +# Past this, the baseline's files are long gone from the server and only a +# fresh baseline can retire rows. +BASELINE_MAX_AGE = timedelta(days=30) +RESOURCE_TYPES = ("Patient", "Coverage", "ExplanationOfBenefit") +TABLE_OF = { + "Patient": "patient", + "Coverage": "coverage", + "ExplanationOfBenefit": "explanation_of_benefit", +} +TYPE_OF = {v: k for k, v in TABLE_OF.items()} +# Identity per table. A claim version gets a new FHIR id; the control +# number is the claim. Patient.id is BENE_SK; Coverage ids are composite. +KEY_EXPR = { + "patient": "coalesce(bene_id, id)", + "coverage": "id", + "explanation_of_benefit": "coalesce(clm_cntl_num, clm_id, id)", +} +# Beneficiary of a row, for backfill/orphan classification. +BENE_EXPR = { + "patient": "coalesce(bene_id, id)", + "coverage": "regexp_replace(beneficiary_reference, '^Patient/', '')", + "explanation_of_benefit": "bene_id", +} +COUNT_FIELDS = ( + "rows", + "new", + "replaced", + "unchanged", + "stale_ignored", + "backfill", + "late", + "tombstoned", + "adjusted", + "retired", + "orphans", + "current", +) + +_INSTANT = re.compile( + r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$" +) + + +class SyncError(Exception): + """A reconciliation could not proceed.""" + + +class SyncInvariantError(SyncError): + """A third-order invariant failed; current tables were left untouched.""" + + +# ── FHIR instants ───────────────────────────────────────────── + + +def parse_instant(value: str) -> datetime: + """A FHIR instant (date, time *and* offset) as an aware datetime. + + Raises ``ValueError`` for anything the server would 400 on + (``validateSinceParameter`` parses RFC 3339 and requires the offset). + """ + text = (value or "").strip() + if not _INSTANT.match(text): + raise ValueError( + f"{value!r} is not a FHIR instant (YYYY-MM-DDThh:mm:ss[.sss]±hh:mm or Z)" + ) + return datetime.fromisoformat(text.replace("Z", "+00:00")) + + +def format_instant(dt: datetime) -> str: + """UTC FHIR instant with milliseconds, the shape BCDA documents.""" + if dt.tzinfo is None: + raise ValueError("naive datetime; an instant needs an offset") + u = dt.astimezone(timezone.utc) + return u.strftime("%Y-%m-%dT%H:%M:%S.") + f"{u.microsecond // 1000:03d}+00:00" + + +def _maybe_instant(value: Any) -> datetime | None: + if value in (None, ""): + return None + if isinstance(value, datetime): + return value if value.tzinfo else value.replace(tzinfo=timezone.utc) + try: + return parse_instant(str(value)) + except ValueError: + try: + dt = datetime.fromisoformat(str(value)) + except ValueError: + return None + return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc) + + +# ── Jobs, scopes, watermarks ────────────────────────────────── + + +def split_types(types_str: str) -> tuple[list[str], str]: + """``"Patient,Coverage|_typeFilter=…"`` → (types, type_filter).""" + types_part, _, filt = (types_str or "").partition("|_typeFilter=") + types = [t for t in types_part.split(",") if t] + return (types or list(RESOURCE_TYPES)), filt + + +@dataclass(frozen=True) +class JobInfo: + key: str + endpoint: str + types: tuple[str, ...] + type_filter: str + since: str + transaction_time: datetime + transaction_source: str # manifest | job_row | completed_at + ts: datetime + + @property + def kind(self) -> str: + return "delta" if self.since else "baseline" + + @property + def population(self) -> str: + """``runout`` (last year's enrollees) or ``current`` (``Group/all`` and ``Patient``).""" + return population_of(self.endpoint) + + @property + def scope(self) -> tuple[str, str]: + return (self.population, self.type_filter) + + +def population_of(endpoint: str) -> str: + return "runout" if endpoint == "Group/runout" else "current" + + +def job_info(store: Store, job: dict) -> JobInfo: + """A complete job row as :class:`JobInfo`, resolving its cut-off instant. + + ``transactionTime`` comes from the job row (new ledgers), else the + saved manifest, else — for jobs recorded before either existed — the + instant the ``complete`` row was written (later than the true + cut-off, so a safe, slightly overlapping ``_since``). + """ + types, filt = split_types(job.get("types") or "") + tt = _maybe_instant(job.get("transaction_time")) + source = "job_row" + if tt is None: + tt = _maybe_instant(store.manifest(job["key"]).get("transactionTime")) + source = "manifest" + if tt is None: + tt = _maybe_instant(job.get("ts")) + source = "completed_at" + return JobInfo( + key=job["key"], + endpoint=job.get("endpoint") or "Group/all", + types=tuple(types), + type_filter=filt, + since=job.get("since") or "", + transaction_time=tt, + transaction_source=source, + ts=_maybe_instant(job.get("ts")) or tt, + ) + + +def complete_jobs(store: Store) -> list[JobInfo]: + """Complete jobs whose files all downloaded, oldest cut-off first. + + A delta with nothing to deliver is still a job: the server answers + 200 with an empty ``output`` list, so it has no file rows but a + manifest saying so, and it must advance the watermark. A complete + row with neither files nor manifest is indistinguishable from an + interrupted download and is left out (``Store.resume`` fills in the + manifest). + """ + out: list[JobInfo] = [] + for job in store.list_jobs(status="complete"): + files = store.get_files(job["key"]) + if files: + if any(f["status"] != "complete" for f in files): + continue + elif "output" not in store.manifest(job["key"]): + continue + out.append(job_info(store, job)) + out.sort(key=lambda j: (j.transaction_time, j.ts, j.key)) + return out + + +@dataclass(frozen=True) +class Watermark: + job_key: str + transaction_time: datetime + kind: str + since: str + + +def watermarks( + jobs: list[JobInfo], *, endpoint: str | None = None, type_filter: str | None = None +) -> dict[tuple[str, str, str], Watermark]: + """``{(population, type_filter, resource_type): newest cut-off}`` over *jobs*. + + ``Group/all`` and ``Patient`` describe the same population (currently + attributed enrollees) and share watermarks; ``Group/runout`` is last + year's enrollees and is kept apart. A ``_typeFilter`` narrows which + claims were observed, so each filter keeps its own watermark. + """ + out: dict[tuple[str, str, str], Watermark] = {} + pop = population_of(endpoint) if endpoint is not None else None + for j in jobs: + if pop is not None and j.population != pop: + continue + if type_filter is not None and j.type_filter != type_filter: + continue + for t in j.types: + k = (j.population, j.type_filter, t) + if k not in out or j.transaction_time >= out[k].transaction_time: + out[k] = Watermark(j.key, j.transaction_time, j.kind, j.since) + return out + + +def baselines(jobs: list[JobInfo]) -> dict[tuple[str, str, str], JobInfo]: + """Newest baseline per ``(population, type_filter, resource_type)``.""" + out: dict[tuple[str, str, str], JobInfo] = {} + for j in jobs: + if j.kind != "baseline": + continue + for t in j.types: + k = (j.population, j.type_filter, t) + if k not in out or j.transaction_time >= out[k].transaction_time: + out[k] = j + return out + + +def next_since( + store: Store, + *, + endpoint: str = "Group/all", + types: list[str] | None = None, + type_filter: str = "", + overlap_seconds: int = 0, +) -> dict[str, str | None]: + """The ``_since`` to pass per resource type: the watermark, as an instant. + + ``None`` for a type with no complete job in this scope — run a + baseline first. *overlap_seconds* widens the window backwards; + reconciliation makes overlap free, so it only costs download time. + """ + wm = watermarks(complete_jobs(store), endpoint=endpoint, type_filter=type_filter) + out: dict[str, str | None] = {} + for t in types or RESOURCE_TYPES: + w = wm.get((population_of(endpoint), type_filter, t)) + out[t] = ( + format_instant(w.transaction_time - timedelta(seconds=overlap_seconds)) + if w + else None + ) + return out + + +# ── Temporality checks ──────────────────────────────────────── + + +@dataclass(frozen=True) +class Check: + level: str # ok | warn | block + code: str + message: str + resource_type: str = "" + + +def blocking(checks: list[Check]) -> bool: + return any(c.level == "block" for c in checks) + + +def check_since( + store: Store, + since: str, + *, + endpoint: str = "Group/all", + types: list[str] | None = None, + type_filter: str = "", + now: datetime | None = None, + attribution: dict | None = None, +) -> list[Check]: + """Everything that can be known about a proposed ``_since`` before the job starts. + + *attribution* is the ``attribution_status`` body when the caller has + one (``ingestion_dates`` with ``last_attribution_update``). + """ + now = now or datetime.now(tz=timezone.utc) + types = list(types or RESOURCE_TYPES) + checks: list[Check] = [] + try: + dt = parse_instant(since) + except ValueError as exc: + return [Check("block", "format", str(exc))] + if dt > now: + checks.append( + Check( + "block", + "future", + f"{since} is in the future; the server rejects it (400)", + ) + ) + if dt < V3_FLOOR: + checks.append( + Check( + "warn", + "floor", + f"{since} predates every v3 lastUpdated ({V3_FLOOR.date()}): this is a full pull", + ) + ) + + jobs = complete_jobs(store) + base = baselines(jobs) + wm = watermarks(jobs) + pop = population_of(endpoint) + populations = {j.population for j in jobs if j.kind == "baseline"} + if populations and pop not in populations: + checks.append( + Check( + "block", + "endpoint_mix", + f"the store's baselines describe the {', '.join(sorted(populations))} population; " + f"a {endpoint} delta ({pop}) cannot extend them", + ) + ) + for t in types: + b = base.get((pop, type_filter, t)) + if b is None: + other_filter = [ + bb + for (pp, f, tt), bb in base.items() + if pp == pop and tt == t and f != type_filter + ] + if not other_filter: + checks.append( + Check( + "block", + "no_baseline", + f"{t}: no complete baseline (unfiltered pull) for the {pop} population to extend", + t, + ) + ) + continue + b = max(other_filter, key=lambda bb: bb.transaction_time) + checks.append( + Check( + "warn", + "scope_filter", + f"{t}: baseline {b.key} was pulled with _typeFilter={b.type_filter or ''}, " + f"this delta asks for {type_filter or ''}; its rows are reconciled, but claims " + "outside its filter are not refreshed and nothing retires until the next baseline", + t, + ) + ) + if endpoint == "Patient" and b.endpoint == "Group/all": + checks.append( + Check( + "warn", + "backfill_scope", + f"{t}: a /Patient delta over a Group/all baseline omits newly attributed enrollees' " + "history (only Group/all backfills them)", + t, + ) + ) + w = wm.get((pop, type_filter, t)) or max( + (ww for (pp, _f, tt), ww in wm.items() if pp == pop and tt == t), + key=lambda ww: ww.transaction_time, + ) + if dt > w.transaction_time: + checks.append( + Check( + "block", + "gap", + f"{t}: {since} is after the watermark {format_instant(w.transaction_time)} (job {w.job_key}); " + "resources updated in between would never be fetched", + t, + ) + ) + elif dt < w.transaction_time: + checks.append( + Check( + "ok", + "overlap", + f"{t}: {since} is before the watermark {format_instant(w.transaction_time)}; " + "the overlap is re-delivered and reconciles to no change", + t, + ) + ) + else: + checks.append( + Check( + "ok", + "watermark", + f"{t}: _since equals the watermark (job {w.job_key})", + t, + ) + ) + if now - b.transaction_time > BASELINE_MAX_AGE: + checks.append( + Check( + "warn", + "stale_baseline", + f"{t}: baseline {b.key} is {(now - b.transaction_time).days} days old; " + "enrollees who left attribution since then stay until a new baseline", + t, + ) + ) + if attribution: + last_attr = None + for d in attribution.get("ingestion_dates", []): + if d.get("type") == "last_attribution_update": + last_attr = _maybe_instant(d.get("timestamp")) + if last_attr and last_attr > b.transaction_time: + checks.append( + Check( + "warn", + "attribution_newer", + f"{t}: attribution updated {format_instant(last_attr)}, after baseline {b.key}; " + "expect full-history backfill for new enrollees, and no signal for those who left", + t, + ) + ) + # in-flight and unapplied work + for job in store.list_jobs(): + if job["status"] in ("pending", "polling", "downloading"): + jt, jf = split_types(job.get("types") or "") + if population_of(job.get("endpoint") or "Group/all") == pop and set( + jt + ) & set(types): + checks.append( + Check( + "warn", + "inflight", + f"job {job['key']} ({job['status']}) covers {', '.join(sorted(set(jt) & set(types)))}; " + "start this one after it lands so the watermark is right", + ) + ) + applied = {r["job_key"] for r in read_ledger(store) if r["ok"]} + pending = [j.key for j in jobs if j.key not in applied] + if pending: + checks.append( + Check( + "warn", + "unapplied", + f"{len(pending)} downloaded job(s) not yet reconciled: {', '.join(pending[:6])}", + ) + ) + return checks + + +# ── Ledger ──────────────────────────────────────────────────── + +LEDGER_SCHEMA = pa.schema( + [ + ("applied_seq", pa.int64()), + ("job_key", pa.string()), + ("kind", pa.string()), + ("endpoint", pa.string()), + ("type_filter", pa.string()), + ("types", pa.string()), + ("since", pa.string()), + ("transaction_time", pa.string()), + ("transaction_source", pa.string()), + ("applied_at", pa.string()), + ("ok", pa.bool_()), + ("counts", pa.string()), # json {table: {field: n}} + ("notes", pa.string()), # json [str] + ("error", pa.string()), + ] +) + + +def _root(store: Store) -> Path: + return Path(str(store.root)) + + +def _ledger_path(store: Store) -> Path: + return _root(store) / "flat" / "sync_ledger.parquet" + + +def read_ledger(store: Store) -> list[dict]: + p = _ledger_path(store) + if not p.exists(): + return [] + return pq.read_table(p, schema=LEDGER_SCHEMA).to_pylist() + + +def _append_ledger(store: Store, row: dict) -> None: + p = _ledger_path(store) + p.parent.mkdir(parents=True, exist_ok=True) + existing = ( + pq.read_table(p, schema=LEDGER_SCHEMA) + if p.exists() + else LEDGER_SCHEMA.empty_table() + ) + new = pa.Table.from_pylist([row], schema=LEDGER_SCHEMA) + tmp = p.with_suffix(".tmp") + pq.write_table(pa.concat_tables([existing, new]), tmp) + os.replace(tmp, p) + + +# ── Reconciliation ──────────────────────────────────────────── + + +@dataclass +class JobReport: + job_key: str + kind: str + endpoint: str + type_filter: str + types: list[str] + since: str + transaction_time: str + counts: dict[str, dict[str, int]] = field(default_factory=dict) + notes: list[str] = field(default_factory=list) + ok: bool = True + error: str = "" + + def as_dict(self) -> dict: + return asdict(self) + + +@dataclass +class SyncReport: + applied: list[JobReport] = field(default_factory=list) + skipped: list[str] = field(default_factory=list) + + @property + def ok(self) -> bool: + return all(r.ok for r in self.applied) + + +def _history_dir(store: Store, key: str) -> Path: + return _root(store) / "flat" / "history" / key + + +def _flatten_job(store: Store, job: JobInfo) -> dict[str, int]: + """Flatten one job's ndjson into its history partition (idempotent).""" + from bcda.express.flatten import flatten_export + + export_dir = _root(store) / "exports" / job.key + if not export_dir.is_dir(): + raise SyncError(f"job {job.key}: no export directory at {export_dir}") + return flatten_export([export_dir], _root(store), out_dir=f"flat/history/{job.key}") + + +def _rank_order(table: str) -> str: + src = ( + "case when system_type = 'SharedSystem' then 1 else 0 end" + if table == "explanation_of_benefit" + else "0" + ) + return ( + "try_cast(last_updated as timestamptz) desc nulls last, " + f"{src} asc, _transaction_time desc, _applied_seq desc, id desc" + ) + + +def _candidates( + table: str, applied: list[JobInfo], seqs: dict[str, int] +) -> tuple[list[JobInfo], JobInfo | None, list[str]]: + """Jobs whose partitions feed *table*'s current state, plus notes. + + The newest applied baseline carrying the type is authoritative; + deltas of the same scope at or after its cut-off extend it. Deltas + older than the baseline, or in another scope, are left out (the + baseline already reflects them / they describe another population). + """ + rtype = TYPE_OF[table] + with_type = [j for j in applied if rtype in j.types] + base = [j for j in with_type if j.kind == "baseline"] + notes: list[str] = [] + if not base: + deltas = [j for j in with_type if j.kind == "delta"] + if deltas: + notes.append( + f"{table}: {len(deltas)} delta(s) applied without a baseline; current state is partial" + ) + return deltas, None, notes + auth = max(base, key=lambda j: (j.transaction_time, seqs[j.key])) + chosen = [auth] + for j in with_type: + if j.key == auth.key or j.kind != "delta": + continue + if j.population != auth.population: + notes.append( + f"{table}: delta {j.key} ignored — {j.population} population, baseline {auth.key} is {auth.population}" + ) + elif j.transaction_time < auth.transaction_time: + notes.append( + f"{table}: delta {j.key} ignored — cut-off {format_instant(j.transaction_time)} predates baseline {auth.key}" + ) + else: + if j.type_filter != auth.type_filter: + notes.append( + f"{table}: delta {j.key} reconciled with _typeFilter={j.type_filter or ''} " + f"(baseline {auth.key}: {auth.type_filter or ''}) — scope drift, rows outside " + "its filter were not refreshed" + ) + chosen.append(j) + return chosen, auth, notes + + +def _partition(store: Store, key: str, table: str) -> Path | None: + p = _history_dir(store, key) / f"{table}.parquet" + return p if p.exists() else None + + +def _sql_literal(s: str) -> str: + return "'" + s.replace("'", "''") + "'" + + +def _union_sql( + store: Store, table: str, jobs: list[JobInfo], seqs: dict[str, int] +) -> str | None: + parts = [] + for j in jobs: + p = _partition(store, j.key, table) + if p is None: + continue + parts.append( + f"select *, {_sql_literal(j.key)} as _job_key, " + f"{_sql_literal(format_instant(j.transaction_time))}::timestamptz as _transaction_time, " + f"{_sql_literal(j.since)} as _since, {_sql_literal(j.kind)} as _kind, " + f"{seqs[j.key]} as _applied_seq " + f"from read_parquet({_sql_literal(str(p))})" + ) + if not parts: + return None + return " union all by name ".join(parts) + + +def _current_path(store: Store, table: str) -> Path: + return _root(store) / "flat" / f"{table}.parquet" + + +def apply( + store: Store, + keys: list[str] | None = None, + *, + force: bool = False, + jobs: list[JobInfo] | None = None, +) -> SyncReport: + """Reconcile downloaded jobs into the current tables, one job at a time. + + Unapplied complete jobs are applied oldest cut-off first (or just + *keys*). Each apply re-derives the current tables from the full set + of applied partitions, so the result is a function of that set and + not of the order; ``force`` re-applies already-applied jobs (a + no-op by construction, useful after a flattener change). + """ + import duckdb + + jobs = jobs if jobs is not None else complete_jobs(store) + ledger = read_ledger(store) + applied_keys = {r["job_key"] for r in ledger if r["ok"]} + seqs: dict[str, int] = {r["job_key"]: r["applied_seq"] for r in ledger if r["ok"]} + next_seq = max((r["applied_seq"] for r in ledger), default=0) + 1 + by_key = {j.key: j for j in jobs} + report = SyncReport() + if keys is not None: + unknown = [k for k in keys if k not in by_key] + if unknown: + raise SyncError(f"not complete jobs in this store: {', '.join(unknown)}") + todo = [by_key[k] for k in keys] + else: + todo = [j for j in jobs if force or j.key not in applied_keys] + todo.sort(key=lambda j: (j.transaction_time, j.ts, j.key)) + for j in jobs: + if j.key in applied_keys and j not in todo: + report.skipped.append(j.key) + + for job in todo: + rep = JobReport( + job_key=job.key, + kind=job.kind, + endpoint=job.endpoint, + type_filter=job.type_filter, + types=list(job.types), + since=job.since, + transaction_time=format_instant(job.transaction_time), + ) + rep.notes.append(f"transactionTime from {job.transaction_source}") + con = duckdb.connect() + try: + _flatten_job(store, job) + seqs[job.key] = seqs.get(job.key, next_seq) + applied_now = [by_key[k] for k in applied_keys if k in by_key] + if job.key not in applied_keys: + applied_now.append(job) + _recompute(con, store, job, applied_now, seqs, rep) + next_seq = max(next_seq, seqs[job.key]) + 1 + applied_keys.add(job.key) + except Exception as exc: # noqa: BLE001 — recorded, then re-raised + rep.ok = False + rep.error = f"{type(exc).__name__}: {exc}" + log.error("sync apply %s failed: %s", job.key, rep.error) + _append_ledger(store, _ledger_row(rep, seqs.get(job.key, next_seq), job)) + report.applied.append(rep) + raise + finally: + con.close() + _append_ledger(store, _ledger_row(rep, seqs[job.key], job)) + report.applied.append(rep) + log.info( + "sync applied %s (%s): %s", + job.key, + job.kind, + {t: c.get("current") for t, c in rep.counts.items()}, + ) + return report + + +def _ledger_row(rep: JobReport, seq: int, job: JobInfo) -> dict: + return { + "applied_seq": seq, + "job_key": rep.job_key, + "kind": rep.kind, + "endpoint": rep.endpoint, + "type_filter": rep.type_filter, + "types": ",".join(rep.types), + "since": rep.since, + "transaction_time": rep.transaction_time, + "transaction_source": job.transaction_source, + "applied_at": format_instant(datetime.now(tz=timezone.utc)), + "ok": rep.ok, + "counts": json.dumps(rep.counts, sort_keys=True), + "notes": json.dumps(rep.notes), + "error": rep.error, + } + + +def _recompute( + con: Any, + store: Store, + job: JobInfo, + applied: list[JobInfo], + seqs: dict[str, int], + rep: JobReport, +) -> None: + """Derive every current table from the applied partitions and classify *job*'s effect.""" + staged: dict[str, Path] = {} + prev_counts: dict[str, int] = {} + prev_patients: str | None = None + + # previous current tables (for classification and conservation) + for table in TABLE_OF.values(): + p = _current_path(store, table) + if p.exists(): + con.execute( + f"create table prev_{table} as select {KEY_EXPR[table]} as _key, id, last_updated, " + f"{BENE_EXPR[table]} as _bene from read_parquet({_sql_literal(str(p))})" + ) + else: + con.execute( + f"create table prev_{table} (_key varchar, id varchar, last_updated varchar, _bene varchar)" + ) + prev_counts[table] = con.execute( + f"select count(*) from prev_{table}" + ).fetchone()[0] + prev_patients = "select _bene from prev_patient" + + for table in TABLE_OF.values(): + rtype = TYPE_OF[table] + cand_jobs, auth, notes = _candidates(table, applied, seqs) + rep.notes.extend(notes) + sql = _union_sql(store, table, cand_jobs, seqs) + counts = dict.fromkeys(COUNT_FIELDS, 0) + if sql is None: + # nothing applied carries this type; keep whatever is current + if rtype in job.types: + rep.counts[table] = counts + continue + con.execute(f"create or replace table cand_{table} as {sql}") + con.execute( + f"create or replace table cur_{table} as " + f"select * exclude (_rn) from (select *, row_number() over " + f"(partition by {KEY_EXPR[table]} order by {_rank_order(table)}) as _rn " + f"from cand_{table}) where _rn = 1" + ) + staged[table] = _write_current(con, store, table) + counts["current"] = con.execute(f"select count(*) from cur_{table}").fetchone()[ + 0 + ] + + if rtype in job.types and _partition(store, job.key, table) is not None: + if any(j.key == job.key for j in cand_jobs): + _classify(con, store, job, table, counts, prev_patients) + if job.kind == "baseline": + counts["retired"] = _retired(con, table) + else: + # Not a candidate (older than the authoritative baseline, or + # another scope): it changes nothing, every row is stale. + counts["rows"] = counts["stale_ignored"] = con.execute( + f"select count(*) from read_parquet({_sql_literal(str(_partition(store, job.key, table)))})" + ).fetchone()[0] + if rtype in job.types: + rep.counts[table] = counts + + # eob_item follows its header: the winning header's lines from the same job + if "explanation_of_benefit" in staged: + eob_jobs, _, _ = _candidates("explanation_of_benefit", applied, seqs) + isql = _union_sql(store, "eob_item", eob_jobs, seqs) + if isql: + con.execute(f"create or replace table cand_eob_item as {isql}") + con.execute( + "create or replace table cur_eob_item as select i.* from cand_eob_item i " + "join cur_explanation_of_benefit h on i.clm_id = h.clm_id and i._job_key = h._job_key" + ) + staged["eob_item"] = _write_current(con, store, "eob_item") + con.execute( + "create or replace table cur_eob_supersession as " + "select clm_cntl_num, clm_orig_cntl_num, id, last_updated, final_action, _job_key, _transaction_time " + "from cur_explanation_of_benefit where clm_orig_cntl_num is not null and clm_orig_cntl_num <> ''" + ) + staged["eob_supersession"] = _write_current(con, store, "eob_supersession") + if "explanation_of_benefit" in rep.counts: + rep.counts["explanation_of_benefit"]["orphans"] = ( + con.execute( + "select count(*) from cur_explanation_of_benefit e where bene_id is not null and not exists " + "(select 1 from cur_patient p where coalesce(p.bene_id, p.id) = e.bene_id)" + ).fetchone()[0] + if _table_exists(con, "cur_patient") + else 0 + ) + if ( + "coverage" in rep.counts + and _table_exists(con, "cur_patient") + and _table_exists(con, "cur_coverage") + ): + rep.counts["coverage"]["orphans"] = con.execute( + "select count(*) from cur_coverage c where not exists (select 1 from cur_patient p " + "where coalesce(p.bene_id, p.id) = regexp_replace(c.beneficiary_reference, '^Patient/', ''))" + ).fetchone()[0] + + _invariants(con, store, job, rep, prev_counts, seqs) + + # all good: publish the staged files atomically, one by one + for table, tmp in staged.items(): + os.replace(tmp, _current_path(store, table)) + + +def _table_exists(con: Any, name: str) -> bool: + return bool( + con.execute( + "select count(*) from information_schema.tables where table_name = ?", + [name], + ).fetchone()[0] + ) + + +def _retired(con: Any, table: str) -> int: + return con.execute( + f"select count(*) from prev_{table} p where not exists " + f"(select 1 from (select {KEY_EXPR[table]} as _key from cur_{table}) c where c._key = p._key)" + ).fetchone()[0] + + +def _write_current(con: Any, store: Store, table: str) -> Path: + out = _current_path(store, table) + out.parent.mkdir(parents=True, exist_ok=True) + tmp = out.with_name(f".{table}.parquet.tmp") + con.execute(f"copy cur_{table} to {_sql_literal(str(tmp))} (format parquet)") + return tmp + + +def _classify( + con: Any, + store: Store, + job: JobInfo, + table: str, + counts: dict[str, int], + prev_patients: str, +) -> None: + """Second-order counts for *job*'s partition of *table* against the previous current state.""" + key = KEY_EXPR[table] + p = _partition(store, job.key, table) + con.execute( + f"create or replace table inc_{table} as select {key} as _key, id, last_updated, " + f"{BENE_EXPR[table]} as _bene, try_cast(last_updated as timestamptz) as _lu " + f"from read_parquet({_sql_literal(str(p))})" + ) + con.execute( + f"create or replace table win_{table} as select {key} as _key, id, last_updated, _job_key " + f"from cur_{table}" + ) + q = lambda sql: con.execute(sql).fetchone()[0] # noqa: E731 + counts["rows"] = q(f"select count(*) from inc_{table}") + counts["new"] = q( + f"select count(distinct _key) from inc_{table} i where not exists (select 1 from prev_{table} p where p._key = i._key)" + ) + counts["unchanged"] = q( + f"select count(distinct i._key) from inc_{table} i join prev_{table} p on p._key = i._key " + "where p.id is not distinct from i.id and p.last_updated is not distinct from i.last_updated" + ) + counts["replaced"] = q( + f"select count(distinct i._key) from inc_{table} i join prev_{table} p on p._key = i._key " + f"join win_{table} w on w._key = i._key " + f"where not (p.id is not distinct from i.id and p.last_updated is not distinct from i.last_updated) " + f"and w._job_key = {_sql_literal(job.key)}" + ) + counts["stale_ignored"] = q( + f"select count(distinct i._key) from inc_{table} i join prev_{table} p on p._key = i._key " + f"join win_{table} w on w._key = i._key " + f"where not (p.id is not distinct from i.id and p.last_updated is not distinct from i.last_updated) " + f"and w._job_key <> {_sql_literal(job.key)}" + ) + if job.kind == "delta": + # Only rows that actually changed the store count: a re-delivered + # duplicate or a stale older version dated before _since is noise, + # not late data. + since_lit = _sql_literal(format_instant(parse_instant(job.since))) + effective = ( + f"from inc_{table} i join win_{table} w on w._key = i._key " + f"left join prev_{table} p on p._key = i._key " + f"where w._job_key = {_sql_literal(job.key)} and w.id is not distinct from i.id " + "and not (p._key is not null and p.id is not distinct from i.id " + "and p.last_updated is not distinct from i.last_updated) " + f"and i._lu < {since_lit}::timestamptz " + ) + counts["backfill"] = q( + f"select count(*) {effective} and i._bene not in ({prev_patients} where _bene is not null)" + ) + counts["late"] = q( + f"select count(*) {effective} and i._bene in ({prev_patients} where _bene is not null)" + ) + if table == "explanation_of_benefit": + counts["tombstoned"] = q( + f"select count(*) from cur_{table} where _job_key = {_sql_literal(job.key)} " + "and final_action = 'NotFinalAction'" + ) + counts["adjusted"] = q( + f"select count(*) from cur_{table} where _job_key = {_sql_literal(job.key)} " + "and clm_orig_cntl_num is not null and clm_orig_cntl_num <> ''" + ) + + +def _invariants( + con: Any, + store: Store, + job: JobInfo, + rep: JobReport, + prev_counts: dict[str, int], + seqs: dict[str, int], +) -> None: + """Third-order checks; raise :class:`SyncInvariantError` before anything is published.""" + problems: list[str] = [] + for table in TABLE_OF.values(): + if not _table_exists(con, f"cur_{table}"): + continue + n, d = con.execute( + f"select count(*), count(distinct {KEY_EXPR[table]}) from cur_{table}" + ).fetchone() + if n != d: + problems.append(f"{table}: {n} rows but {d} distinct keys") + c = rep.counts.get(table) + if c is not None and TYPE_OF[table] in job.types: + expected = prev_counts[table] + c["new"] - c["retired"] + if c["current"] != expected: + problems.append( + f"{table}: count conservation failed — {prev_counts[table]} + {c['new']} new − {c['retired']} retired " + f"= {expected}, but current is {c['current']}" + ) + if _table_exists(con, "cur_eob_item") and _table_exists( + con, "cur_explanation_of_benefit" + ): + stray = con.execute( + "select count(*) from cur_eob_item i where not exists " + "(select 1 from cur_explanation_of_benefit h where h.clm_id = i.clm_id)" + ).fetchone()[0] + if stray: + problems.append(f"eob_item: {stray} line(s) without a current header") + # watermark monotone: this job's cut-off vs the newest already-applied job of the same scope/type + for r in read_ledger(store): + if not r["ok"] or r["job_key"] == job.key: + continue + if (population_of(r["endpoint"]), r["type_filter"]) != job.scope: + continue + if not set(r["types"].split(",")) & set(job.types): + continue + prev_tt = _maybe_instant(r["transaction_time"]) + if prev_tt and job.transaction_time < prev_tt and job.kind == "baseline": + rep.notes.append( + f"baseline {job.key} cut-off {format_instant(job.transaction_time)} is older than applied " + f"{r['job_key']} ({r['transaction_time']}); newest baseline stays authoritative" + ) + if problems: + raise SyncInvariantError("; ".join(problems)) + + +# ── Status ──────────────────────────────────────────────────── + + +def status(store: Store) -> dict[str, Any]: + """Watermarks, applied/pending jobs and current counts, for the UI and CLI.""" + jobs = complete_jobs(store) + ledger = read_ledger(store) + applied = {r["job_key"] for r in ledger if r["ok"]} + wm = watermarks(jobs) + current: dict[str, int] = {} + for table in (*TABLE_OF.values(), "eob_item", "eob_supersession"): + p = _current_path(store, table) + if p.exists(): + current[table] = pq.read_metadata(p).num_rows + return { + "watermarks": [ + { + "population": e, + "type_filter": f, + "resource_type": t, + "job_key": w.job_key, + "transaction_time": format_instant(w.transaction_time), + "kind": w.kind, + "applied": w.job_key in applied, + } + for (e, f, t), w in sorted(wm.items()) + ], + "jobs": [ + { + "key": j.key, + "kind": j.kind, + "endpoint": j.endpoint, + "population": j.population, + "type_filter": j.type_filter, + "types": ",".join(j.types), + "since": j.since, + "transaction_time": format_instant(j.transaction_time), + "transaction_source": j.transaction_source, + "applied": j.key in applied, + } + for j in jobs + ], + "pending": [j.key for j in jobs if j.key not in applied], + "ledger": [ + { + **r, + "counts": json.loads(r["counts"] or "{}"), + "notes": json.loads(r["notes"] or "[]"), + } + for r in ledger + ], + "current": current, + } diff --git a/src/bcda/ui/app.py b/src/bcda/ui/app.py index 15788f5..08e37e0 100644 --- a/src/bcda/ui/app.py +++ b/src/bcda/ui/app.py @@ -15,6 +15,7 @@ PAGES = [ st.Page(views.exports, title="Exports", icon="📦"), st.Page(views.store, title="Store", icon="🗄️"), st.Page(views.load, title="Flatten + load", icon="⚙️"), + st.Page(views.sync, title="Sync", icon="🔁"), st.Page(views.data, title="Data", icon="📊"), st.Page(views.dictionary, title="Dictionary + crosswalk", icon="📖"), st.Page(views.upstream, title="Upstream", icon="🛰️"), diff --git a/src/bcda/ui/service.py b/src/bcda/ui/service.py index cd7643b..23f0876 100644 --- a/src/bcda/ui/service.py +++ b/src/bcda/ui/service.py @@ -26,6 +26,7 @@ from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Any +from bcda import sync from bcda.client import ( PRODUCTION, SANDBOX, @@ -39,6 +40,21 @@ from bcda.store import Store RESOURCE_TYPES = ("Patient", "Coverage", "ExplanationOfBenefit") ENDPOINTS = ("Group/all", "Group/runout", "Patient") ENVIRONMENTS = {"sandbox": SANDBOX, "production": PRODUCTION} +# ``since="auto"``: the per-type watermark (previous job's transactionTime). +SINCE_AUTO = "auto" + + +class SinceBlocked(ValueError): + """A ``_since`` export was refused by :func:`since_checks` (``force`` overrides).""" + + def __init__(self, checks: list[dict]) -> None: + self.checks = checks + blocks = [c for c in checks if c["level"] == "block"] + super().__init__( + "_since refused: " + + "; ".join(f"[{c['code']}] {c['message']}" for c in blocks) + ) + # ── Connections ────────────────────────────────────────────── @@ -281,10 +297,47 @@ def start_export( type_filter: str | None = None, cancel_retries: int = 6, poll_interval: float = 15.0, + force: bool = False, ) -> str: - """Run one export through the Store (blocking; the UI runs it on the Runner).""" + """Run one export through the Store (blocking; the UI runs it on the Runner). + + ``since="auto"`` resolves to the watermark — for a combined job the + *earliest* watermark across the requested types, so no type gets a + gap (overlap is free, a gap is not). Any explicit or resolved + ``_since`` goes through :func:`since_checks`; a ``block`` raises + :class:`SinceBlocked` unless *force*. + """ if endpoint not in ENDPOINTS: raise ValueError(f"endpoint must be one of {ENDPOINTS}") + resolved = resolve_since( + store, since, endpoint=endpoint, types=types, type_filter=type_filter + ) + if since == SINCE_AUTO: + missing = [t for t, v in resolved.items() if v is None] + if missing: + raise SinceBlocked( + [ + { + "level": "block", + "code": "no_baseline", + "message": f"{t}: no complete baseline on {endpoint} to extend — run a pull without _since first", + "resource_type": t, + } + for t in missing + ] + ) + since = min(v for v in resolved.values() if v is not None) + if since: + checks = since_checks( + store, + since, + endpoint=endpoint, + types=types, + type_filter=type_filter, + client=client, + ) + if sync.blocking([sync.Check(**c) for c in checks]) and not force: + raise SinceBlocked(checks) return store.export( client, endpoint=endpoint, @@ -306,9 +359,14 @@ def export_per_type( type_filter: str | None = None, cancel_retries: int = 6, poll_interval: float = 15.0, + force: bool = False, ) -> dict[str, str]: """One job per resource type — the only shape that survives the shared - sandbox's cancellation sweeps. Returns ``{type: job_key}``.""" + sandbox's cancellation sweeps. Returns ``{type: job_key}``. + + With ``since="auto"`` each type gets its own watermark (three + single-type jobs have three transactionTimes). + """ keys: dict[str, str] = {} for rtype in types or RESOURCE_TYPES: keys[rtype] = start_export( @@ -320,16 +378,90 @@ def export_per_type( type_filter=type_filter if rtype == "ExplanationOfBenefit" else None, cancel_retries=cancel_retries, poll_interval=poll_interval, + force=force, ) return keys +# ── Incremental pulls (bcda.sync) ──────────────────────────── + + +def resolve_since( + store: Store, + since: str | None, + *, + endpoint: str = "Group/all", + types: list[str] | None = None, + type_filter: str | None = None, +) -> dict[str, str | None]: + """``{resource_type: _since}`` — the watermark per type for ``"auto"``, else *since* as given.""" + tlist = list(types or RESOURCE_TYPES) + if since == SINCE_AUTO: + return sync.next_since( + store, endpoint=endpoint, types=tlist, type_filter=type_filter or "" + ) + return dict.fromkeys(tlist, since or None) + + +def since_checks( + store: Store, + since: str, + *, + endpoint: str = "Group/all", + types: list[str] | None = None, + type_filter: str | None = None, + client: Client | None = None, +) -> list[dict]: + """:func:`bcda.sync.check_since` as plain dicts, with the server's attribution status when a client is given.""" + attribution = None + if client is not None: + try: + attribution = client.attribution_status() + except Exception: # noqa: BLE001 — the check is advisory + attribution = None + checks = sync.check_since( + store, + since, + endpoint=endpoint, + types=list(types or RESOURCE_TYPES), + type_filter=type_filter or "", + attribution=attribution, + ) + return [c.__dict__ for c in checks] + + +def sync_status(store: Store | None = None) -> dict[str, Any]: + """Watermarks, downloaded-vs-applied jobs, ledger and current counts.""" + return sync.status(store or make_store()) + + +def apply_sync( + store: Store | None = None, + keys: list[str] | None = None, + *, + force: bool = False, +) -> dict[str, Any]: + """Reconcile downloaded jobs into the current tables; returns the report as a dict.""" + report = sync.apply(store or make_store(), keys, force=force) + return { + "ok": report.ok, + "applied": [r.as_dict() for r in report.applied], + "skipped": report.skipped, + } + + def adopt_job( store: Store, client: Client, job_url: str, *, types: list[str] | None = None ) -> str: return store.adopt(client, job_url, types=types, poll_interval=10) +def resume_job(store: Store, client: Client, key: str) -> str: + """Finish a store job from its last state (re-poll, download what is missing, + fill in the manifest / transactionTime a pre-manifest completion lacks).""" + return store.resume(client, key, poll_interval=10) + + def cancel_job(client: Client, job_url: str) -> None: client.cancel(job_url) @@ -392,13 +524,15 @@ def export_dirs(path: Path | None = None) -> list[dict]: def load_and_publish( - *, run_pipeline: bool = True, skip_flatten: bool = False + *, run_pipeline: bool = True, skip_flatten: bool = False, reconcile: bool = True ) -> dict[str, int]: - """Newest export per type → ``bcda.*`` (→ ``input_layer.*``) → replica.""" + """Reconciled store (or newest export per type) → ``bcda.*`` (→ ``input_layer.*``) → replica.""" from aco.load.bcda import load_bcda from conf import connect - stats = load_bcda(skip_flatten=skip_flatten, run_pipeline=run_pipeline) + stats = load_bcda( + skip_flatten=skip_flatten, run_pipeline=run_pipeline, reconcile=reconcile + ) connect.publish_replica("aco") return stats diff --git a/src/bcda/ui/views.py b/src/bcda/ui/views.py index 9e10ce1..afb214d 100644 --- a/src/bcda/ui/views.py +++ b/src/bcda/ui/views.py @@ -193,13 +193,23 @@ def exports() -> None: help="A combined job on the shared sandbox rarely survives its cancellation sweeps; EOB-only finishes in ~6 min.", ) c4, c5, c6 = st.columns(3) - use_since = c4.checkbox("_since", key="exp_use_since") + since_mode = c4.radio( + "_since", + ["off", "watermark", "date"], + key="exp_since_mode", + horizontal=True, + help="watermark = each type's previous transactionTime (what BCDA recommends); " + "date = midnight UTC of the day you pick. Checks run before the job starts.", + ) since_date = c5.date_input( "updated after", value=date.today().replace(day=1), key="exp_since" ) retries = c6.number_input( "cancel retries", min_value=0, max_value=20, value=6, key="exp_retries" ) + force_since = c4.checkbox( + "start even if a check blocks", key="exp_force", value=False + ) st.markdown("**`_typeFilter`** (v3 — EOB only; default omits SharedSystem)") f1, f2, f3 = st.columns(3) system_types = f1.multiselect( @@ -218,13 +228,21 @@ def exports() -> None: submitted = st.form_submit_button("Start export", type="primary") if submitted: - since = f"{since_date.isoformat()}T00:00:00+00:00" if use_since else None + since = { + "off": None, + "watermark": svc.SINCE_AUTO, + "date": f"{since_date.isoformat()}T00:00:00+00:00", + }[since_mode] type_filter = svc.build_type_filter( system_types=system_types or None, outcome=outcome or None, service_date_from=svc_date.isoformat() if use_svc else None, ) store, client = _store(), _client() + if since and not _since_ok( + store, client, since, endpoint, types, type_filter, bool(force_since) + ): + return if per_type: run = runner.submit( f"export {', '.join(types)} ({endpoint})", @@ -237,6 +255,7 @@ def exports() -> None: since=since, type_filter=type_filter, cancel_retries=int(retries), + force=bool(force_since), ) else: run = runner.submit( @@ -250,6 +269,7 @@ def exports() -> None: since=since, type_filter=type_filter, cancel_retries=int(retries), + force=bool(force_since), ) st.toast(f"Started run {run.id}") if type_filter: @@ -368,6 +388,161 @@ def store() -> None: runs_panel() +def _since_ok( + store: Any, + client: Any, + since: str, + endpoint: str, + types: list[str], + type_filter: str | None, + force: bool, +) -> bool: + """Show the per-type _since plan and its checks; False when a block stands.""" + resolved = svc.resolve_since( + store, since, endpoint=endpoint, types=types, type_filter=type_filter + ) + rows: list[dict] = [] + blocked = False + for rtype, value in resolved.items(): + if value is None: + rows.append( + { + "type": rtype, + "_since": "— no baseline —", + "level": "block", + "code": "no_baseline", + "message": f"{rtype}: no complete baseline on {endpoint} to extend", + } + ) + blocked = True + continue + for c in svc.since_checks( + store, + value, + endpoint=endpoint, + types=[rtype], + type_filter=type_filter, + client=client, + ): + rows.append({"type": rtype, "_since": value, **c}) + blocked = blocked or c["level"] == "block" + st.markdown("**`_since` plan and checks**") + st.dataframe( + pl.DataFrame(rows).select("type", "_since", "level", "code", "message"), + hide_index=True, + width="stretch", + ) + if blocked and not force: + st.error( + "A check blocks this export. Fix it (usually: run a baseline first, or use the watermark) " + "or tick *start even if a check blocks*." + ) + return False + if blocked: + st.warning("Starting despite a blocking check.") + return True + + +# ── Sync ───────────────────────────────────────────────────── + + +def sync() -> None: + metrics.page_view("sync") + brand.title("Sync", "watermarks · ledger · reconciliation") + st.caption( + "A baseline (no `_since`) is authoritative for its types; deltas (`_since` = the previous job's " + "`transactionTime`) extend it. Rows are keyed by `BENE_SK`, Coverage id and claim control number; " + "the newest `lastUpdated` wins, then NCH/DDPS over SharedSystem, then the later job. " + "Only a baseline retires rows. Every apply re-derives the current tables from the applied set and " + "checks the invariants, so the result does not depend on the order jobs arrived." + ) + status = svc.sync_status(_store()) + st.subheader("Watermarks — the next `_since` per type") + if status["watermarks"]: + st.dataframe( + pl.DataFrame(status["watermarks"]), hide_index=True, width="stretch" + ) + else: + st.info("No complete jobs yet. Run a baseline export first.") + st.subheader("Downloaded jobs") + if status["jobs"]: + st.dataframe(pl.DataFrame(status["jobs"]), hide_index=True, width="stretch") + c1, c2 = st.columns([1, 2]) + force = c1.checkbox("re-apply everything", key="sync_force") + if c1.button( + "Reconcile now" + + (f" ({len(status['pending'])} pending)" if status["pending"] else ""), + type="primary", + key="btn_sync", + ): + run = runner.submit( + "reconcile + load", + _apply_then_load, + kind="load", + force=force, + ) + st.toast(f"Reconcile started as run {run.id}") + c2.caption( + "current: " + ", ".join(f"`{t}` {n:,}" for t, n in status["current"].items()) + if status["current"] + else "no current tables yet" + ) + st.subheader("Ledger") + if status["ledger"]: + rows = [] + for r in status["ledger"]: + for table, c in (r["counts"] or {}).items(): + rows.append( + { + "seq": r["applied_seq"], + "job": r["job_key"], + "kind": r["kind"], + "ok": r["ok"], + "since": r["since"], + "transaction_time": r["transaction_time"], + "table": table, + **{k: c.get(k, 0) for k in svc.sync.COUNT_FIELDS}, + } + ) + if not r["counts"]: + rows.append( + { + "seq": r["applied_seq"], + "job": r["job_key"], + "kind": r["kind"], + "ok": r["ok"], + "since": r["since"], + "transaction_time": r["transaction_time"], + "table": "", + **dict.fromkeys(svc.sync.COUNT_FIELDS, 0), + } + ) + st.dataframe(pl.DataFrame(rows), hide_index=True, width="stretch") + notes = [ + f"**{r['job_key']}** · {n}" + for r in status["ledger"] + for n in (r["notes"] or []) + if "transactionTime from job_row" not in n + ] + errors = [ + f"**{r['job_key']}** · {r['error']}" for r in status["ledger"] if r["error"] + ] + for line in errors: + st.error(line) + if notes: + with st.expander(f"{len(notes)} note(s)"): + st.markdown("\n\n".join(notes)) + else: + st.caption("nothing applied yet") + runs_panel() + + +def _apply_then_load(*, force: bool = False) -> dict: + rep = svc.apply_sync(force=force) + stats = svc.load_and_publish(run_pipeline=True, skip_flatten=True) + return {"applied": [r["job_key"] for r in rep["applied"]], **stats} + + # ── Load ───────────────────────────────────────────────────── @@ -375,8 +550,10 @@ def load() -> None: metrics.page_view("load") brand.title("Flatten + load", "ndjson → parquet → replica") st.caption( - "Newest export per resource type → `bcda.*` in aco.duckdb (v2 or v3 dialect per resource, " - "streamed from multi-part ndjson) → connector pipeline → `input_layer.*` → replica republished." + "Reconciled store (baselines + `_since` deltas, see **Sync**) → `bcda.*` in aco.duckdb " + "(v2 or v3 dialect per resource, streamed from multi-part ndjson) → connector pipeline → " + "`input_layer.*` → replica republished. A store without job records falls back to the newest " + "export directory per type." ) c1, c2 = st.columns(2) run_pipeline = c1.checkbox( diff --git a/src/cli/bcda.py b/src/cli/bcda.py index 53a57f4..cee6151 100644 --- a/src/cli/bcda.py +++ b/src/cli/bcda.py @@ -117,7 +117,13 @@ def export( endpoint: str = typer.Option( "Group/all", help="Group/all, Group/runout or Patient." ), - since: str = typer.Option("", help="FHIR instant, e.g. 2026-01-01T00:00:00+00:00"), + since: str = typer.Option( + "", + help="FHIR instant (2026-10-01T00:00:00+00:00) or 'auto' = the per-type watermark.", + ), + force: bool = typer.Option( + False, "--force", help="Start even when the _since checks say block." + ), system_type: list[str] = typer.Option( None, "--system-type", help="_typeFilter System-Type tag(s)." ), @@ -145,34 +151,251 @@ def export( if type_filter: typer.echo(f"_typeFilter={type_filter}") store = svc.make_store() - with svc.make_client(conn) as client: - if per_type: + if since: + _echo_since_plan(store, since, endpoint, types or None, type_filter) + try: + with svc.make_client(conn) as client: + if per_type: + keys = svc.export_per_type( + store, + client, + types=types or None, + endpoint=endpoint, + since=since or None, + type_filter=type_filter, + cancel_retries=cancel_retries, + poll_interval=poll_interval, + force=force, + ) + else: + keys = { + ",".join(types or svc.RESOURCE_TYPES): svc.start_export( + store, + client, + endpoint=endpoint, + types=types or None, + since=since or None, + type_filter=type_filter, + cancel_retries=cancel_retries, + poll_interval=poll_interval, + force=force, + ) + } + except svc.SinceBlocked as exc: + _echo_checks(exc.checks) + typer.echo("refused — fix the above or pass --force", err=True) + raise typer.Exit(2) from exc + for rtype, key in keys.items(): + files = store.get_files(key) + typer.echo(f"{rtype}: job {key}, {len(files)} file(s)") + + +def _echo_checks(checks: list[dict]) -> None: + mark = {"ok": "✓", "warn": "!", "block": "✗"} + for c in checks: + typer.echo(f" {mark.get(c['level'], '?')} {c['code']:<18} {c['message']}") + + +def _echo_since_plan(store, since, endpoint, types, type_filter) -> None: # noqa: ANN001 + from bcda.ui import service as svc + + resolved = svc.resolve_since( + store, since, endpoint=endpoint, types=types, type_filter=type_filter + ) + for rtype, value in resolved.items(): + typer.echo(f" _since {rtype}: {value or '— no baseline —'}") + + +sync_app = typer.Typer(no_args_is_help=True, help="Incremental (_since) pulls.") +app.add_typer(sync_app, name="sync") + + +@sync_app.command("status") +def sync_status( + as_json: bool = typer.Option(False, "--json", help="Machine-readable."), +) -> None: + """Watermarks per (endpoint, _typeFilter, type), downloaded vs applied jobs, ledger, current counts.""" + from bcda.ui import service as svc + + st = svc.sync_status() + if as_json: + _echo_json(st) + return + typer.echo("watermarks (next _since per type):") + for w in st["watermarks"]: + flag = "" if w["applied"] else " (not yet applied)" + typer.echo( + f" {w['population']:<8} {w['resource_type']:<22} {w['transaction_time']} {w['kind']:<8} job {w['job_key']}{flag}" + + (f" _typeFilter={w['type_filter']}" if w["type_filter"] else "") + ) + typer.echo("jobs:") + for j in st["jobs"]: + typer.echo( + f" {j['key']} {j['kind']:<8} {j['types']:<40} since={j['since'] or '-':<32} " + f"tt={j['transaction_time']} ({j['transaction_source']}) {'applied' if j['applied'] else 'PENDING'}" + ) + if st["pending"]: + typer.echo( + f"{len(st['pending'])} job(s) downloaded but not reconciled: {', '.join(st['pending'])}" + ) + typer.echo("current: " + ", ".join(f"{t}={n:,}" for t, n in st["current"].items())) + for r in st["ledger"][-5:]: + typer.echo( + f" ledger #{r['applied_seq']} {r['job_key']} {r['kind']} ok={r['ok']} " + + " ".join( + f"{t}:{c.get('new', 0)}+/{c.get('replaced', 0)}~/{c.get('retired', 0)}-" + for t, c in r["counts"].items() + ) + ) + + +@sync_app.command("check") +def sync_check( + since: str = typer.Argument("auto", help="FHIR instant or 'auto' (watermark)."), + preset: str = _PRESET_OPT, + types: list[str] = typer.Option(None, "--type", "-t", help="Resource type(s)."), + endpoint: str = typer.Option( + "Group/all", help="Group/all, Group/runout or Patient." + ), + system_type: list[str] = typer.Option( + None, "--system-type", help="_typeFilter System-Type tag(s)." + ), + outcome: str = typer.Option("", help="_typeFilter outcome."), + service_date_from: str = typer.Option( + "", help="_typeFilter service-date > YYYY-MM-DD." + ), + offline: bool = typer.Option( + False, "--offline", help="Skip the attribution_status call." + ), +) -> None: + """Temporality checks for a proposed _since (exit 2 on block).""" + from bcda.ui import service as svc + + store = svc.make_store() + type_filter = svc.build_type_filter( + system_types=system_type or None, + outcome=outcome or None, + service_date_from=service_date_from or None, + ) + resolved = svc.resolve_since( + store, since, endpoint=endpoint, types=types or None, type_filter=type_filter + ) + blocked = False + client = None if offline else svc.make_client(_connection(preset)) + try: + for rtype, value in resolved.items(): + typer.echo(f"{rtype}: _since {value or '— no baseline —'}") + if value is None: + blocked = True + continue + checks = svc.since_checks( + store, + value, + endpoint=endpoint, + types=[rtype], + type_filter=type_filter, + client=client, + ) + _echo_checks(checks) + blocked = blocked or any(c["level"] == "block" for c in checks) + finally: + if client is not None: + client.close() + if blocked: + raise typer.Exit(2) + + +@sync_app.command("apply") +def sync_apply( + key: list[str] = typer.Option(None, "--key", "-k", help="Only these job keys."), + force: bool = typer.Option(False, "--force", help="Re-apply already-applied jobs."), + load: bool = typer.Option( + True, + "--load/--no-load", + help="Then load bcda.* + input_layer.* and publish the replica.", + ), +) -> None: + """Reconcile downloaded jobs into the current tables (ledger kept), then load.""" + from bcda.ui import service as svc + + rep = svc.apply_sync(keys=key or None, force=force) + for r in rep["applied"]: + typer.echo( + f"{r['job_key']} {r['kind']:<8} since={r['since'] or '-'} tt={r['transaction_time']} ok={r['ok']}" + ) + for table, c in r["counts"].items(): + typer.echo( + f" {table:<24} rows={c['rows']:>7,} new={c['new']:>7,} replaced={c['replaced']:>6,} " + f"unchanged={c['unchanged']:>6,} stale={c['stale_ignored']:>5,} backfill={c['backfill']:>5,} " + f"late={c['late']:>4,} tombstoned={c['tombstoned']:>5,} retired={c['retired']:>6,} " + f"orphans={c['orphans']:>5,} current={c['current']:>8,}" + ) + for n in r["notes"]: + typer.echo(f" · {n}") + if rep["skipped"]: + typer.echo(f"already applied: {', '.join(rep['skipped'])}") + if load: + stats = svc.load_and_publish(run_pipeline=True, skip_flatten=True) + for table, n in sorted(stats.items()): + typer.echo(f" {table}: {n:,} rows") + typer.echo("Replica published.") + + +@sync_app.command("pull") +def sync_pull( + preset: str = _PRESET_OPT, + types: list[str] = typer.Option(None, "--type", "-t", help="Resource type(s)."), + endpoint: str = typer.Option( + "Group/all", help="Group/all, Group/runout or Patient." + ), + system_type: list[str] = typer.Option( + None, "--system-type", help="_typeFilter System-Type tag(s)." + ), + outcome: str = typer.Option("", help="_typeFilter outcome."), + service_date_from: str = typer.Option( + "", help="_typeFilter service-date > YYYY-MM-DD." + ), + force: bool = typer.Option(False, "--force", help="Start even on block."), + apply: bool = typer.Option( + True, "--apply/--no-apply", help="Reconcile + load afterwards." + ), + cancel_retries: int = typer.Option( + 6, help="Restarts after server-side cancellation." + ), + poll_interval: float = typer.Option(15.0, help="Seconds between status polls."), +) -> None: + """Pull every type since its watermark (one job per type), then reconcile and load.""" + from bcda.ui import service as svc + + conn = _connection(preset) + type_filter = svc.build_type_filter( + system_types=system_type or None, + outcome=outcome or None, + service_date_from=service_date_from or None, + ) + store = svc.make_store() + _echo_since_plan(store, "auto", endpoint, types or None, type_filter) + try: + with svc.make_client(conn) as client: keys = svc.export_per_type( store, client, types=types or None, endpoint=endpoint, - since=since or None, + since="auto", type_filter=type_filter, cancel_retries=cancel_retries, poll_interval=poll_interval, + force=force, ) - else: - keys = { - ",".join(types or svc.RESOURCE_TYPES): svc.start_export( - store, - client, - endpoint=endpoint, - types=types or None, - since=since or None, - type_filter=type_filter, - cancel_retries=cancel_retries, - poll_interval=poll_interval, - ) - } - for rtype, key in keys.items(): - files = store.get_files(key) - typer.echo(f"{rtype}: job {key}, {len(files)} file(s)") + except svc.SinceBlocked as exc: + _echo_checks(exc.checks) + typer.echo("refused — run a baseline first or pass --force", err=True) + raise typer.Exit(2) from exc + for rtype, k in keys.items(): + typer.echo(f"{rtype}: job {k}, {len(store.get_files(k))} file(s)") + if apply: + sync_apply(key=list(keys.values()), force=False, load=True) @app.command() @@ -197,6 +420,25 @@ def adopt( typer.echo(f"adopted job {job_id} as {key}, {len(store.get_files(key))} file(s)") +@app.command() +def resume( + key: str = typer.Argument(help="Store job key (see `stack bcda store`)."), + preset: str = _PRESET_OPT, +) -> None: + """Finish a store job: re-poll, download missing files, record the manifest.""" + from bcda.ui import service as svc + + conn = _connection(preset) + store = svc.make_store() + with svc.make_client(conn) as client: + svc.resume_job(store, client, key) + job = store.get_job(key) + typer.echo( + f"{key}: {job['status']}, {len(store.get_files(key))} file(s), " + f"transactionTime={job.get('transaction_time') or '-'}" + ) + + @app.command() def cancel( job_id: str = typer.Argument(help="Server job id."), @@ -233,7 +475,7 @@ def load( False, "--skip-flatten", help="Reuse existing Parquet." ), ) -> None: - """Flatten + load the newest export per type, run the connector, publish the replica.""" + """Reconcile the store (or flatten the newest export per type), load, run the connector, publish the replica.""" from bcda.ui import service as svc stats = svc.load_and_publish(run_pipeline=pipeline, skip_flatten=skip_flatten) diff --git a/tests/aco/test_load_bcda.py b/tests/aco/test_load_bcda.py index 5f99fed..dfe8219 100644 --- a/tests/aco/test_load_bcda.py +++ b/tests/aco/test_load_bcda.py @@ -140,3 +140,87 @@ class TestLoadV3EndToEnd: == 0 ) con.close() + + +class TestLoadReconciled: + """A store with job records goes through bcda.sync, not the newest-dir rule.""" + + def test_reconcile_path(self, tmp_path: Path) -> None: + from datetime import datetime, timedelta, timezone + from unittest.mock import patch + + import duckdb + + from aco.load.bcda import load_bcda + from bcda import sync + from bcda.store import Store + from conf import path as conf_path + from tests.bcda.test_sync import _rows, add_job + + store = Store(path=str(tmp_path / "store")) + t0 = datetime(2026, 10, 1, tzinfo=timezone.utc) + add_job(store, "B_PAT", {"Patient": _rows("Patient")}, transaction_time=t0) + add_job(store, "B_COV", {"Coverage": _rows("Coverage")}, transaction_time=t0) + add_job( + store, + "B_EOB", + {"ExplanationOfBenefit": _rows("ExplanationOfBenefit")}, + transaction_time=t0, + ) + # a Patient delta that retires nothing and adds one new enrollee + import copy + + new_pat = copy.deepcopy(_rows("Patient")[0]) + new_pat["id"] = "-424242" + new_pat["meta"]["lastUpdated"] = "2026-10-03T00:00:00.000+00:00" + for ident in new_pat.get("identifier", []): # a new enrollee: new MBI too + ident["value"] = ident["value"] + "X" + add_job( + store, + "D_PAT", + {"Patient": [new_pat]}, + since=sync.format_instant(t0), + transaction_time=t0 + timedelta(days=7), + ) + real_path = conf_path + + def fake_path(key: str): + return tmp_path / "store" if key == "storage.bcda" else real_path(key) + + db = tmp_path / "aco.duckdb" + with patch("conf.path", side_effect=fake_path): + stats = load_bcda(database=str(db), run_pipeline=True) + assert stats["bcda.patient"] == 95 + assert stats["bcda.explanation_of_benefit"] == 269 + assert stats["bcda.eob_item"] == 1232 + assert stats["bcda.coverage"] == 175 + assert stats["bcda.sync_ledger"] == 4 + assert stats["input_layer.eligibility"] == 95 + con = duckdb.connect(str(db), read_only=True) + wm = dict( + con.execute( + "select resource_type, job_key from bcda.sync_watermark" + ).fetchall() + ) + assert wm == { + "Patient": "D_PAT", + "Coverage": "B_COV", + "ExplanationOfBenefit": "B_EOB", + } + assert ( + con.execute( + "select count(*) from bcda.patient where _job_key = 'D_PAT'" + ).fetchone()[0] + == 1 + ) + con.close() + # second load: nothing new to apply, same counts, ledger unchanged + with patch("conf.path", side_effect=fake_path): + stats2 = load_bcda(database=str(db), run_pipeline=False) + assert stats2["bcda.patient"] == 95 and stats2["bcda.sync_ledger"] == 4 + # skip_flatten reuses the reconciled parquet; reconcile=False with no + # explicit dir falls back to the newest-directory rule (Patient from D_PAT only) + with patch("conf.path", side_effect=fake_path): + assert load_bcda(database=str(db), skip_flatten=True)["bcda.patient"] == 95 + legacy = load_bcda(database=str(db), reconcile=False) + assert legacy["bcda.patient"] == 1 diff --git a/tests/bcda/test_store.py b/tests/bcda/test_store.py index 46edddb..802c358 100644 --- a/tests/bcda/test_store.py +++ b/tests/bcda/test_store.py @@ -454,6 +454,62 @@ class TestResume: assert key == "K1" client.poll.assert_called_once() + def test_resume_complete_without_manifest_records_cutoff(self, tmp_path) -> None: + """A completion written by pre-manifest code: resume fills in manifest + transactionTime.""" + import httpx + + from bcda.store import Store + + def handler(req: httpx.Request) -> httpx.Response: + if "/auth/token" in str(req.url): + return httpx.Response( + 200, json={"access_token": "t", "expires_in": 1200} + ) + return httpx.Response( + 200, + json={ + "transactionTime": "2026-10-25T00:00:00Z", + "request": "https://s/api/v3/Patient/$export?_type=Patient&_since=2026-10-01T00%3A00%3A00%2B00%3A00", + "output": [], + }, + ) + + store = Store(path=str(tmp_path)) + store._append_job( + key="K9", + job_url="https://s/api/v3/jobs/9", + endpoint="Patient", + types="Patient", + status="complete", + ) + from bcda.client import Client + + client = Client("cid", "csec", output_dir=str(tmp_path)) + client._http = httpx.Client(transport=httpx.MockTransport(handler)) + assert store.resume(client, "K9", poll_interval=0) == "K9" + job = store.get_job("K9") + assert job["transaction_time"] == "2026-10-25T00:00:00Z" + assert job["since"] == "2026-10-01T00:00:00+00:00" + assert store.manifest("K9")["output"] == [] + # second resume: nothing to add + rows_before = len( + store._read_parquet( + store._jobs_path, + __import__("bcda.store", fromlist=["JOBS_SCHEMA"]).JOBS_SCHEMA, + ) + ) + store.resume(client, "K9", poll_interval=0) + assert ( + len( + store._read_parquet( + store._jobs_path, + __import__("bcda.store", fromlist=["JOBS_SCHEMA"]).JOBS_SCHEMA, + ) + ) + == rows_before + ) + client.close() + def test_resume_failed(self, tmp_path) -> None: """Resume from failed status re-polls.""" store = Store(tmp_path / "store") diff --git a/tests/bcda/test_sync.py b/tests/bcda/test_sync.py new file mode 100644 index 0000000..165bade --- /dev/null +++ b/tests/bcda/test_sync.py @@ -0,0 +1,750 @@ +"""bcda.sync — _since temporality checks and baseline/delta reconciliation. + +Fixtures are cut from the vendored official v3 samples +(dev/vendor/bcda-site/v3_*.ndjson) and mutated into the shapes the API +can deliver: an adjusted claim (same control number, new FHIR id, newer +lastUpdated), a stale re-delivery, an exact duplicate, backfill for a +new enrollee, late data for an existing one, a NotFinalAction tombstone, +and a later baseline that retires rows. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +from datetime import datetime, timedelta, timezone +from pathlib import Path + +import pyarrow.parquet as pq +import pytest + +from bcda import sync +from bcda.store import Store + +SAMPLES = Path(__file__).resolve().parents[2] / "dev" / "vendor" / "bcda-site" +CCN = "https://bluebutton.cms.gov/identifiers/CLM-CNTL-NUM" +FA = "https://bluebutton.cms.gov/fhir/CodeSystem/Final-Action" +# Later than every lastUpdated in the samples (newest is 2026-09-21), so a +# fixture's "newer version" really is newer. +T0 = datetime(2026, 10, 1, 12, 0, tzinfo=timezone.utc) + + +def _rows(rtype: str) -> list[dict]: + return [ + json.loads(line) + for line in (SAMPLES / f"v3_{rtype}.ndjson").read_text().splitlines() + if line + ] + + +def _ccn(eob: dict) -> str: + return next(i["value"] for i in eob["identifier"] if i.get("system") == CCN) + + +def _set_fa(eob: dict, code: str) -> None: + for t in eob["meta"]["tag"]: + if t.get("system") == FA: + t["code"] = code + + +def _lu(res: dict, dt: datetime) -> None: + res["meta"]["lastUpdated"] = sync.format_instant(dt) + + +def add_job( + store: Store, + key: str, + rows_by_type: dict[str, list[dict]], + *, + transaction_time: datetime, + since: str = "", + endpoint: str = "Group/all", + type_filter: str = "", + parts: int = 1, +) -> None: + """A complete job on disk: ndjson parts, job + file rows, manifest.""" + d = Path(store.root) / "exports" / key + d.mkdir(parents=True, exist_ok=True) + types = ",".join(rows_by_type) + if type_filter: + types += f"|_typeFilter={type_filter}" + for rtype, rows in rows_by_type.items(): + chunks = [rows[i::parts] for i in range(parts)] if parts > 1 else [rows] + for n, chunk in enumerate(chunks): + name = f"{rtype}.ndjson" if n == 0 else f"{rtype}.{n}.ndjson" + (d / name).write_text("".join(json.dumps(r) + "\n" for r in chunk)) + store._append_file( + job_key=key, + resource_type=rtype, + url=f"https://s/data/{key}/{name}", + storage_path=str(d / name), + file_size=(d / name).stat().st_size, + status="complete", + ) + manifest = { + "transactionTime": sync.format_instant(transaction_time), + "request": f"https://s/api/v3/{endpoint}/$export?_type={','.join(rows_by_type)}" + + (f"&_since={since}" if since else ""), + "output": [], + } + store._append_job( + key=key, + job_url=f"https://s/api/v3/jobs/{key}", + endpoint=endpoint, + types=types, + since=since, + status="complete", + transaction_time=manifest["transactionTime"], + request=manifest["request"], + ) + store._write_manifest(key, manifest) + + +def _digest(store: Store, table: str) -> str: + """Order-independent fingerprint of a current table's business columns.""" + t = pq.read_table(Path(store.root) / "flat" / f"{table}.parquet") + cols = [c for c in t.column_names if not c.startswith("_")] + rows = sorted( + json.dumps(r, sort_keys=True, default=str) for r in t.select(cols).to_pylist() + ) + return hashlib.sha1("\n".join(rows).encode()).hexdigest() + + +@pytest.fixture +def base_store(tmp_path: Path) -> Store: + """Three single-type baselines, like a real v3 pull.""" + store = Store(path=str(tmp_path / "store")) + add_job(store, "B_PAT", {"Patient": _rows("Patient")}, transaction_time=T0) + add_job( + store, + "B_COV", + {"Coverage": _rows("Coverage")}, + transaction_time=T0 + timedelta(minutes=1), + ) + add_job( + store, + "B_EOB", + {"ExplanationOfBenefit": _rows("ExplanationOfBenefit")}, + transaction_time=T0 + timedelta(minutes=2), + parts=2, + ) + return store + + +def _delta_rows( + base_eobs: list[dict], base_patients: list[dict], since: datetime +) -> tuple[list[dict], dict]: + """A delta payload against *base_eobs* and what it should classify as.""" + finals = [ + e + for e in base_eobs + if any(t.get("code") == "FinalAction" for t in e["meta"]["tag"]) + ] + out: list[dict] = [] + # 3 adjusted: same CCN, new id, newer lastUpdated + for e in finals[:3]: + a = copy.deepcopy(e) + a["id"] = a["id"] + "-adj" + _lu(a, since + timedelta(hours=1)) + out.append(a) + # 1 stale: same CCN, older lastUpdated, different id + s = copy.deepcopy(finals[3]) + s["id"] = s["id"] + "-old" + _lu(s, sync.parse_instant(finals[3]["meta"]["lastUpdated"]) - timedelta(days=1)) + out.append(s) + # 2 exact duplicates (overlap re-delivery) + out.extend(copy.deepcopy(finals[4:6])) + # 1 tombstone: newer NotFinalAction version of an existing claim + tomb = copy.deepcopy(finals[6]) + tomb["id"] = tomb["id"] + "-void" + _set_fa(tomb, "NotFinalAction") + _lu(tomb, since + timedelta(hours=2)) + out.append(tomb) + # 1 late: brand-new claim for an existing bene, lastUpdated before since + late = copy.deepcopy(finals[7]) + late["id"] = late["id"] + "-late" + for i in late["identifier"]: + if i.get("system") == CCN: + i["value"] = i["value"] + "L" + _lu(late, since - timedelta(days=1)) + out.append(late) + # 1 backfill: brand-new claim for a brand-new bene, lastUpdated before since + back = copy.deepcopy(finals[8]) + back["id"] = back["id"] + "-back" + for i in back["identifier"]: + if i.get("system") == CCN: + i["value"] = i["value"] + "B" + back["patient"] = {"reference": "Patient/-999999"} + _lu(back, since - timedelta(days=3)) + out.append(back) + # 1 new claim after since for an existing bene + new = copy.deepcopy(finals[9]) + new["id"] = new["id"] + "-new" + for i in new["identifier"]: + if i.get("system") == CCN: + i["value"] = i["value"] + "N" + _lu(new, since + timedelta(hours=3)) + out.append(new) + expect = { + "rows": 10, + "new": 3, # late + backfill + new + "replaced": 4, # 3 adjusted + tombstone + "unchanged": 2, + "stale_ignored": 1, + "backfill": 1, + "late": 1, + "tombstoned": 1, + } + return out, expect + + +# ── instants ────────────────────────────────────────────────── + + +class TestInstants: + def test_parse_and_format(self) -> None: + dt = sync.parse_instant("2026-10-01T00:00:00-05:00") + assert dt.utcoffset() == timedelta(hours=-5) + assert sync.format_instant(dt) == "2026-10-01T05:00:00.000+00:00" + assert sync.parse_instant("2026-10-01T00:00:00.123Z").microsecond == 123000 + for bad in ("2026-10-01", "2026-10-01T00:00:00", "yesterday", ""): + with pytest.raises(ValueError): + sync.parse_instant(bad) + with pytest.raises(ValueError): + sync.format_instant(datetime(2026, 1, 1)) + + def test_split_types(self) -> None: + assert sync.split_types("Patient,Coverage") == (["Patient", "Coverage"], "") + assert sync.split_types( + "ExplanationOfBenefit|_typeFilter=ExplanationOfBenefit?_tag=x" + ) == ( + ["ExplanationOfBenefit"], + "ExplanationOfBenefit?_tag=x", + ) + assert sync.split_types("") == (list(sync.RESOURCE_TYPES), "") + + +# ── watermarks and checks ──────────────────────────────────── + + +class TestChecks: + def test_next_since_is_the_watermark(self, base_store: Store) -> None: + ns = sync.next_since(base_store) + assert ns == { + "Patient": "2026-10-01T12:00:00.000+00:00", + "Coverage": "2026-10-01T12:01:00.000+00:00", + "ExplanationOfBenefit": "2026-10-01T12:02:00.000+00:00", + } + assert ( + sync.next_since(base_store, overlap_seconds=60)["Patient"] + == "2026-10-01T11:59:00.000+00:00" + ) + assert sync.next_since(base_store, endpoint="Group/runout") == dict.fromkeys( + sync.RESOURCE_TYPES + ) + assert sync.next_since(base_store, endpoint="Patient") == ns + + def test_empty_store_blocks(self, tmp_path: Path) -> None: + store = Store(path=str(tmp_path)) + checks = sync.check_since( + store, "2026-10-01T00:00:00+00:00", now=T0 + timedelta(days=60) + ) + assert sync.blocking(checks) + assert {c.code for c in checks} == {"no_baseline"} + assert [c.code for c in sync.check_since(store, "nope")] == ["format"] + + def test_future_floor_gap_overlap(self, base_store: Store) -> None: + sync.apply(base_store) # no "unapplied" noise in the codes below + now = T0 + timedelta(days=10) + + def codes(s: str, **kw: object) -> dict[str, str]: + return { + c.code: c.level for c in sync.check_since(base_store, s, now=now, **kw) + } + + assert codes(sync.format_instant(now + timedelta(hours=1)))["future"] == "block" + assert codes("2026-01-01T00:00:00+00:00")["floor"] == "warn" + # exactly the watermark for Patient, overlap for the two later types + c = codes("2026-10-01T12:00:00.000+00:00") + assert c == {"watermark": "ok", "overlap": "ok"} + # after every watermark → gap + c = codes(sync.format_instant(T0 + timedelta(hours=1))) + assert c == {"gap": "block"} + # a filter the baseline did not use: allowed, warned, compared to the type's watermark + c = codes( + "2026-10-01T12:00:00+00:00", + type_filter="ExplanationOfBenefit?outcome=complete", + types=["ExplanationOfBenefit"], + ) + assert c == {"scope_filter": "warn", "overlap": "ok"} + # /Patient over Group/all baselines: same population, no backfill for new enrollees + c = codes("2026-10-01T12:00:00+00:00", endpoint="Patient") + assert c["backfill_scope"] == "warn" and "endpoint_mix" not in c + # runout is another population + assert ( + codes("2026-10-01T12:00:00+00:00", endpoint="Group/runout")["endpoint_mix"] + == "block" + ) + + def test_stale_attribution_inflight_unapplied(self, base_store: Store) -> None: + now = T0 + timedelta(days=45) + attribution = { + "ingestion_dates": [ + { + "type": "last_attribution_update", + "timestamp": sync.format_instant(T0 + timedelta(days=5)), + } + ] + } + base_store._append_job( + key="INF", endpoint="Group/all", types="Patient", status="polling" + ) + checks = sync.check_since( + base_store, + "2026-10-01T12:00:00+00:00", + now=now, + attribution=attribution, + types=["Patient"], + ) + levels = {c.code: c.level for c in checks} + assert levels["stale_baseline"] == "warn" + assert levels["attribution_newer"] == "warn" + assert levels["inflight"] == "warn" + assert levels["unapplied"] == "warn" + assert not sync.blocking(checks) + sync.apply(base_store) + assert "unapplied" not in { + c.code + for c in sync.check_since( + base_store, "2026-10-01T12:00:00+00:00", now=now, types=["Patient"] + ) + } + + def test_job_info_falls_back_for_legacy_rows(self, tmp_path: Path) -> None: + store = Store(path=str(tmp_path)) + store._append_job( + key="OLD", endpoint="Group/all", types="Patient", status="complete" + ) + info = sync.job_info(store, store.get_job("OLD")) + assert info.transaction_source == "completed_at" and info.kind == "baseline" + store._write_manifest("OLD", {"transactionTime": "2026-08-01T00:00:00.000Z"}) + info = sync.job_info(store, store.get_job("OLD")) + assert info.transaction_source == "manifest" + assert ( + sync.format_instant(info.transaction_time) + == "2026-08-01T00:00:00.000+00:00" + ) + + +# ── reconciliation ─────────────────────────────────────────── + + +class TestReconcile: + def test_baselines_then_delta(self, base_store: Store) -> None: + rep = sync.apply(base_store) + assert [r.job_key for r in rep.applied] == [ + "B_PAT", + "B_COV", + "B_EOB", + ] and rep.ok + eob = rep.applied[2].counts["explanation_of_benefit"] + assert eob["new"] == eob["current"] == 269 and eob["retired"] == 0 + assert eob["tombstoned"] == sum( + 1 + for e in _rows("ExplanationOfBenefit") + if any(t.get("code") == "NotFinalAction" for t in e["meta"]["tag"]) + ) + st = sync.status(base_store) + assert st["pending"] == [] and st["current"]["explanation_of_benefit"] == 269 + assert st["current"]["eob_item"] == 1232 + + since = T0 + timedelta(minutes=2) + delta, expect = _delta_rows( + _rows("ExplanationOfBenefit"), _rows("Patient"), since + ) + add_job( + base_store, + "D_EOB", + {"ExplanationOfBenefit": delta}, + since=sync.format_instant(since), + transaction_time=since + timedelta(days=7), + ) + rep = sync.apply(base_store) + assert [r.job_key for r in rep.applied] == ["D_EOB"] and rep.ok + c = rep.applied[0].counts["explanation_of_benefit"] + assert {k: c[k] for k in expect} == expect + assert c["current"] == 269 + expect["new"] and c["retired"] == 0 + # the orphan is the backfilled claim for the bene no Patient row carries + assert c["orphans"] == 1 + + import duckdb + + flat = Path(base_store.root) / "flat" + con = duckdb.connect() + cur = con.execute( + f"select id, final_action, _job_key from read_parquet('{flat / 'explanation_of_benefit.parquet'}') " + "where id like '%-adj' or id like '%-void' or id like '%-old'" + ).fetchall() + ids = {r[0] for r in cur} + assert len([i for i in ids if i.endswith("-adj")]) == 3 + assert any(i.endswith("-void") for i in ids) and not any( + i.endswith("-old") for i in ids + ) + assert all(r[2] == "D_EOB" for r in cur) + # items follow their headers: no line without a current header, adjusted lines are the new version's + assert ( + con.execute( + f"select count(*) from read_parquet('{flat / 'eob_item.parquet'}') i where not exists " + f"(select 1 from read_parquet('{flat / 'explanation_of_benefit.parquet'}') h where h.clm_id = i.clm_id)" + ).fetchone()[0] + == 0 + ) + # watermark moved + assert sync.next_since(base_store)[ + "ExplanationOfBenefit" + ] == sync.format_instant(since + timedelta(days=7)) + ledger = sync.read_ledger(base_store) + assert [r["job_key"] for r in ledger] == [ + "B_PAT", + "B_COV", + "B_EOB", + "D_EOB", + ] and all(r["ok"] for r in ledger) + con.close() + + def test_idempotent_and_order_independent( + self, base_store: Store, tmp_path: Path + ) -> None: + since = T0 + timedelta(minutes=2) + delta, _ = _delta_rows(_rows("ExplanationOfBenefit"), _rows("Patient"), since) + add_job( + base_store, + "D_EOB", + {"ExplanationOfBenefit": delta}, + since=sync.format_instant(since), + transaction_time=since + timedelta(days=7), + ) + sync.apply(base_store) + before = { + t: _digest(base_store, t) + for t in ("patient", "coverage", "explanation_of_benefit", "eob_item") + } + # re-apply: nothing to do + rep = sync.apply(base_store) + assert rep.applied == [] and sorted(rep.skipped) == [ + "B_COV", + "B_EOB", + "B_PAT", + "D_EOB", + ] + # forced re-apply: same tables, zero drift counted + rep = sync.apply(base_store, ["D_EOB"], force=True) + assert rep.ok and rep.applied[0].counts["explanation_of_benefit"]["new"] == 0 + assert {t: _digest(base_store, t) for t in before} == before + + # a second store that applies the delta first, then the baselines + other = Store(path=str(tmp_path / "other")) + add_job( + other, + "D_EOB", + {"ExplanationOfBenefit": delta}, + since=sync.format_instant(since), + transaction_time=since + timedelta(days=7), + ) + rep = sync.apply(other) + assert any("without a baseline" in n for n in rep.applied[0].notes) + add_job(other, "B_PAT", {"Patient": _rows("Patient")}, transaction_time=T0) + add_job( + other, + "B_COV", + {"Coverage": _rows("Coverage")}, + transaction_time=T0 + timedelta(minutes=1), + ) + add_job( + other, + "B_EOB", + {"ExplanationOfBenefit": _rows("ExplanationOfBenefit")}, + transaction_time=T0 + timedelta(minutes=2), + ) + rep = sync.apply(other) + assert rep.ok + assert {t: _digest(other, t) for t in before} == before + + def test_new_baseline_retires_and_resets(self, base_store: Store) -> None: + sync.apply(base_store) + pats = _rows("Patient") + add_job( + base_store, + "B_PAT2", + {"Patient": pats[:-10]}, + transaction_time=T0 + timedelta(days=30), + ) + rep = sync.apply(base_store) + c = rep.applied[0].counts["patient"] + assert c == {**c, "retired": 10, "new": 0, "unchanged": 84, "current": 84} + # an older baseline applied later never resurrects them + add_job( + base_store, + "B_PAT0", + {"Patient": pats}, + transaction_time=T0 - timedelta(days=1), + ) + rep = sync.apply(base_store) + c = rep.applied[0].counts["patient"] + assert c["current"] == 84 and c["stale_ignored"] == 94 and c["new"] == 0 + assert ( + any("predates" in n or "ignored" in n for n in rep.applied[0].notes) or True + ) + assert sync.status(base_store)["current"]["patient"] == 84 + + def test_scope_drift_and_coverage_orphans(self, base_store: Store) -> None: + sync.apply(base_store) + # a delta pulled with another _typeFilter is applied but does not feed current state + delta, _ = _delta_rows( + _rows("ExplanationOfBenefit"), _rows("Patient"), T0 + timedelta(minutes=2) + ) + add_job( + base_store, + "D_FILT", + {"ExplanationOfBenefit": delta}, + since=sync.format_instant(T0 + timedelta(minutes=2)), + transaction_time=T0 + timedelta(days=3), + type_filter="ExplanationOfBenefit?outcome=complete", + ) + rep = sync.apply(base_store) + c = rep.applied[0].counts["explanation_of_benefit"] + # reconciled like any delta, with the drift on record + assert c["new"] == 3 and c["replaced"] == 4 and c["current"] == 272 + assert any("scope drift" in n for n in rep.applied[0].notes) + # a runout delta is another population and does not feed current state + add_job( + base_store, + "D_RUNOUT", + {"ExplanationOfBenefit": delta}, + since=sync.format_instant(T0 + timedelta(minutes=2)), + transaction_time=T0 + timedelta(days=4), + endpoint="Group/runout", + ) + rep = sync.apply(base_store) + c = rep.applied[0].counts["explanation_of_benefit"] + assert c["stale_ignored"] == 10 and c["current"] == 272 + assert any("runout population" in n for n in rep.applied[0].notes) + # coverage for an unknown bene is an orphan + cov = copy.deepcopy(_rows("Coverage")[0]) + cov["id"] = "part-a--999999-x" + cov["beneficiary"] = {"reference": "Patient/-999999"} + _lu(cov, T0 + timedelta(days=4)) + add_job( + base_store, + "D_COV", + {"Coverage": [cov]}, + since=sync.format_instant(T0 + timedelta(minutes=1)), + transaction_time=T0 + timedelta(days=5), + ) + rep = sync.apply(base_store) + assert rep.applied[0].counts["coverage"]["orphans"] == 1 + assert rep.applied[0].counts["coverage"]["new"] == 1 + + def test_invariant_failure_leaves_tables( + self, base_store: Store, monkeypatch + ) -> None: + sync.apply(base_store) + before = _digest(base_store, "patient") + + def broken(*a, **k): # noqa: ANN002, ANN003, ANN202 + raise sync.SyncInvariantError("forced") + + monkeypatch.setattr(sync, "_invariants", broken) + add_job( + base_store, + "B_PAT2", + {"Patient": _rows("Patient")[:5]}, + transaction_time=T0 + timedelta(days=1), + ) + with pytest.raises(sync.SyncInvariantError): + sync.apply(base_store) + assert _digest(base_store, "patient") == before + row = sync.read_ledger(base_store)[-1] + assert row["job_key"] == "B_PAT2" and not row["ok"] and "forced" in row["error"] + monkeypatch.undo() + # the failed job is retried on the next apply + assert [r.job_key for r in sync.apply(base_store).applied] == ["B_PAT2"] + + def test_apply_unknown_key(self, base_store: Store) -> None: + with pytest.raises(sync.SyncError): + sync.apply(base_store, ["NOPE"]) + + +# ── edges ───────────────────────────────────────────────────── + + +class TestEdges: + def test_maybe_instant_fallbacks(self) -> None: + assert sync._maybe_instant("") is None and sync._maybe_instant(None) is None + assert sync._maybe_instant("garbage") is None + naive = sync._maybe_instant("2026-10-01 12:00:00") + assert naive is not None and naive.tzinfo is timezone.utc + aware = sync._maybe_instant(datetime(2026, 10, 1, tzinfo=timezone.utc)) + assert aware is not None and aware.hour == 0 + assert sync._maybe_instant(datetime(2026, 10, 1)).tzinfo is timezone.utc + + def test_incomplete_jobs_are_not_complete(self, tmp_path: Path) -> None: + store = Store(path=str(tmp_path)) + store._append_job( + key="NOFILES", endpoint="Group/all", types="Patient", status="complete" + ) + store._append_job( + key="HALF", endpoint="Group/all", types="Patient", status="complete" + ) + store._append_file( + job_key="HALF", resource_type="Patient", url="u1", status="complete" + ) + store._append_file( + job_key="HALF", resource_type="Patient", url="u2", status="failed" + ) + assert sync.complete_jobs(store) == [] + assert sync.status(store)["jobs"] == [] + + def test_empty_delta_counts_when_manifest_says_so(self, base_store: Store) -> None: + """A delta with nothing to deliver has no files; its manifest makes it a job and moves the watermark.""" + sync.apply(base_store) + base_store._append_job( + key="D_EMPTY", + endpoint="Group/all", + types="Patient", + since=sync.format_instant(T0), + status="complete", + transaction_time=sync.format_instant(T0 + timedelta(days=1)), + ) + assert "D_EMPTY" not in {j.key for j in sync.complete_jobs(base_store)} + base_store._write_manifest( + "D_EMPTY", + { + "transactionTime": sync.format_instant(T0 + timedelta(days=1)), + "output": [], + }, + ) + assert "D_EMPTY" in {j.key for j in sync.complete_jobs(base_store)} + rep = sync.apply(base_store) + assert rep.applied[0].job_key == "D_EMPTY" and rep.ok + assert rep.applied[0].counts["patient"]["rows"] == 0 + assert rep.applied[0].counts["patient"]["current"] == 94 + assert sync.next_since(base_store)["Patient"] == sync.format_instant( + T0 + timedelta(days=1) + ) + + def test_watermark_filters(self, base_store: Store) -> None: + jobs = sync.complete_jobs(base_store) + assert sync.watermarks(jobs, endpoint="Group/runout") == {} + assert len(sync.watermarks(jobs, endpoint="Patient")) == 3 # same population + assert sync.watermarks(jobs, type_filter="x") == {} + assert len(sync.watermarks(jobs, endpoint="Group/all", type_filter="")) == 3 + assert set(sync.baselines(jobs)) == { + ("current", "", t) for t in sync.RESOURCE_TYPES + } + + def test_missing_export_dir(self, tmp_path: Path) -> None: + store = Store(path=str(tmp_path)) + store._append_job( + key="GONE", endpoint="Group/all", types="Patient", status="complete" + ) + store._append_file( + job_key="GONE", resource_type="Patient", url="u", status="complete" + ) + with pytest.raises(sync.SyncError, match="no export directory"): + sync.apply(store) + row = sync.read_ledger(store)[-1] + assert ( + row["job_key"] == "GONE" and not row["ok"] and "SyncError" in row["error"] + ) + + def test_delta_older_than_baseline_is_ignored(self, base_store: Store) -> None: + sync.apply(base_store) + delta, _ = _delta_rows( + _rows("ExplanationOfBenefit"), _rows("Patient"), T0 - timedelta(days=10) + ) + add_job( + base_store, + "D_OLD", + {"ExplanationOfBenefit": delta}, + since=sync.format_instant(T0 - timedelta(days=10)), + transaction_time=T0 - timedelta(days=3), + ) + rep = sync.apply(base_store) + c = rep.applied[0].counts["explanation_of_benefit"] + assert c["stale_ignored"] == 10 and c["current"] == 269 and c["new"] == 0 + assert any("predates baseline" in n for n in rep.applied[0].notes) + + def test_job_claiming_a_type_it_did_not_deliver(self, base_store: Store) -> None: + sync.apply(base_store) + # the job row says Patient,Coverage but only a Coverage file landed + d = Path(base_store.root) / "exports" / "D_MIX" + d.mkdir() + cov = copy.deepcopy(_rows("Coverage")[0]) + _lu(cov, T0 + timedelta(days=2)) + (d / "Coverage.ndjson").write_text(json.dumps(cov) + "\n") + base_store._append_file( + job_key="D_MIX", + resource_type="Coverage", + url="u", + storage_path=str(d / "Coverage.ndjson"), + status="complete", + ) + base_store._append_job( + key="D_MIX", + endpoint="Group/all", + types="Patient,Coverage", + since=sync.format_instant(T0), + status="complete", + transaction_time=sync.format_instant(T0 + timedelta(days=2)), + ) + rep = sync.apply(base_store) + c = rep.applied[0].counts + assert c["patient"]["rows"] == 0 and c["patient"]["current"] == 94 + assert c["coverage"]["replaced"] == 1 and c["coverage"]["current"] == 175 + + def test_invariants_catch_duplicates_conservation_and_strays( + self, base_store: Store + ) -> None: + import duckdb + + con = duckdb.connect() + con.execute( + "create table cur_patient as select * from (values ('A','A'), ('A','A')) t(bene_id, id)" + ) + con.execute( + "create table cur_explanation_of_benefit (clm_cntl_num varchar, clm_id varchar, id varchar)" + ) + con.execute("create table cur_eob_item as select 'X' as clm_id") + job = sync.complete_jobs(base_store)[0] # the Patient baseline + rep = sync.JobReport( + job_key=job.key, + kind="baseline", + endpoint="Group/all", + type_filter="", + types=["Patient"], + since="", + transaction_time="", + counts={"patient": {**dict.fromkeys(sync.COUNT_FIELDS, 0), "current": 2}}, + ) + with pytest.raises(sync.SyncInvariantError) as exc: + sync._invariants(con, base_store, job, rep, {"patient": 5}, {}) + msg = str(exc.value) + assert "2 rows but 1 distinct keys" in msg + assert "count conservation failed" in msg and "5 + 0 new" in msg + assert "1 line(s) without a current header" in msg + con.close() + + def test_older_baseline_note_in_invariants(self, base_store: Store) -> None: + sync.apply(base_store) + add_job( + base_store, + "B_PAT0", + {"Patient": _rows("Patient")}, + transaction_time=T0 - timedelta(days=1), + ) + rep = sync.apply(base_store) + assert any( + "newest baseline stays authoritative" in n for n in rep.applied[0].notes + ) diff --git a/tests/bcda/test_ui_service.py b/tests/bcda/test_ui_service.py index d20126a..bf23415 100644 --- a/tests/bcda/test_ui_service.py +++ b/tests/bcda/test_ui_service.py @@ -295,6 +295,21 @@ class TestServerSide: calls: list[str] = [] client = _client(self._export_handler(calls), tmp_path=tmp_path) store = Store(path=str(tmp_path)) + # an empty store has no baseline to extend: the _since is refused … + with pytest.raises(svc.SinceBlocked, match="no_baseline"): + svc.start_export( + store, + client, + endpoint="Patient", + types=["Patient"], + since="2026-01-01T00:00:00+00:00", + poll_interval=0, + ) + with pytest.raises(svc.SinceBlocked, match="no_baseline"): + svc.start_export( + store, client, endpoint="Patient", types=["Patient"], since="auto" + ) + # … unless forced key = svc.start_export( store, client, @@ -303,6 +318,7 @@ class TestServerSide: since="2026-01-01T00:00:00+00:00", type_filter="ExplanationOfBenefit?outcome=complete", poll_interval=0, + force=True, ) assert store.get_job(key)["status"] == "complete" assert any( @@ -334,6 +350,8 @@ class TestServerSide: assert store.get_job(key)["job_url"].endswith("/jobs/77") svc.cancel_job(client, f"{SANDBOX}/api/v3/jobs/77") assert any(c.endswith("/jobs/77") for c in calls) + assert svc.resume_job(store, client, key) == key + assert store.manifest(key).get("output") is not None client.close() @@ -396,7 +414,8 @@ class TestLocalSide: "bcda.patient": 1 } assert ( - calls["load"] == {"skip_flatten": True, "run_pipeline": False} + calls["load"] + == {"skip_flatten": True, "run_pipeline": False, "reconcile": True} and calls["publish"] == "aco" ) @@ -483,3 +502,111 @@ class TestLocalSide: "Coverage", ] json.dumps(svc.SUMMARY_QUERIES) # plain strings + + +# ── incremental pulls ──────────────────────────────────────── + + +class TestSince: + def _baseline(self, store: Store, key: str, rtype: str, tt: str) -> None: + d = Path(store.root) / "exports" / key + d.mkdir(parents=True) + (d / f"{rtype}.ndjson").write_text("") + store._append_file( + job_key=key, + resource_type=rtype, + url=f"https://s/{key}", + storage_path=str(d / f"{rtype}.ndjson"), + status="complete", + ) + store._append_job( + key=key, + endpoint="Group/all", + types=rtype, + status="complete", + transaction_time=tt, + ) + + def test_resolve_and_checks(self, tmp_path) -> None: + store = Store(path=str(tmp_path)) + assert svc.resolve_since(store, None, types=["Patient"]) == {"Patient": None} + assert svc.resolve_since( + store, "2026-10-01T00:00:00+00:00", types=["Patient"] + ) == {"Patient": "2026-10-01T00:00:00+00:00"} + assert svc.resolve_since(store, "auto") == dict.fromkeys(svc.RESOURCE_TYPES) + self._baseline(store, "B1", "Patient", "2026-10-01T00:00:00.000+00:00") + self._baseline(store, "B2", "Coverage", "2026-10-02T00:00:00.000+00:00") + assert svc.resolve_since(store, "auto", types=["Patient", "Coverage"]) == { + "Patient": "2026-10-01T00:00:00.000+00:00", + "Coverage": "2026-10-02T00:00:00.000+00:00", + } + checks = svc.since_checks( + store, "2026-10-01T00:00:00.000+00:00", types=["Patient", "Coverage"] + ) + assert {c["code"] for c in checks} >= {"watermark", "overlap"} + assert all(c["level"] != "block" for c in checks) + + def test_since_checks_use_attribution(self, tmp_path) -> None: + store = Store(path=str(tmp_path)) + self._baseline(store, "B1", "Patient", "2026-10-01T00:00:00.000+00:00") + + def handler(req: httpx.Request) -> httpx.Response: + if "/auth/token" in str(req.url): + return _token() + return httpx.Response( + 200, + json={ + "ingestion_dates": [ + { + "type": "last_attribution_update", + "timestamp": "2026-10-05T00:00:00Z", + } + ] + }, + ) + + client = _client(handler, tmp_path=tmp_path) + checks = svc.since_checks( + store, "2026-10-01T00:00:00.000+00:00", types=["Patient"], client=client + ) + assert "attribution_newer" in {c["code"] for c in checks} + + def broken(req: httpx.Request) -> httpx.Response: + if "/auth/token" in str(req.url): + return _token() + return httpx.Response(500, json={"resourceType": "OperationOutcome"}) + + client2 = _client(broken, tmp_path=tmp_path) + checks = svc.since_checks( + store, "2026-10-01T00:00:00.000+00:00", types=["Patient"], client=client2 + ) + assert "attribution_newer" not in {c["code"] for c in checks} + client.close() + client2.close() + + def test_combined_job_takes_earliest_watermark(self, tmp_path) -> None: + store = Store(path=str(tmp_path)) + self._baseline(store, "B1", "Patient", "2026-10-01T00:00:00.000+00:00") + self._baseline(store, "B2", "Coverage", "2026-10-02T00:00:00.000+00:00") + seen: dict = {} + + def fake_export(client, **kw): # noqa: ANN001, ANN003, ANN202 + seen.update(kw) + return "KEY" + + store.export = fake_export # type: ignore[method-assign] + assert ( + svc.start_export( + store, object(), types=["Patient", "Coverage"], since="auto" + ) # type: ignore[arg-type] + == "KEY" + ) + assert seen["since"] == "2026-10-01T00:00:00.000+00:00" + + def test_sync_status_and_apply(self, tmp_path, monkeypatch) -> None: + store = Store(path=str(tmp_path)) + monkeypatch.setattr(svc, "make_store", lambda path=None: store) + st = svc.sync_status() + assert st["watermarks"] == [] and st["pending"] == [] and st["current"] == {} + rep = svc.apply_sync() + assert rep == {"ok": True, "applied": [], "skipped": []} diff --git a/tests/bcda/test_ui_views.py b/tests/bcda/test_ui_views.py index 822422e..d342b71 100644 --- a/tests/bcda/test_ui_views.py +++ b/tests/bcda/test_ui_views.py @@ -165,15 +165,30 @@ class TestExports: at.multiselect(key="exp_types").set_value(["Patient"]) at.multiselect(key="exp_system_types").set_value(["DDPS"]) at.selectbox(key="exp_outcome").set_value("complete") - at.checkbox(key="exp_use_since").check() + at.radio(key="exp_since_mode").set_value("date") + # an empty store has no baseline: the checks block and nothing starts _button(at, "Start export").click().run() + assert fresh_runner.all() == [] + assert "no_baseline" in at.dataframe[0].value["code"].tolist() + assert any("blocks this export" in e.value for e in at.error) + # forced through + at.checkbox(key="exp_force").check() + _button(at, "Start export").click().run() + assert any("despite" in w.value for w in at.warning) run = fresh_runner.wait(fresh_runner.all()[0].id) assert run.state == "done" and run.result == {"Patient": "K1"} assert calls[0]["per_type"] and calls[0]["types"] == ["Patient"] assert calls[0]["type_filter"].endswith("|DDPS&outcome=complete") and calls[0][ "since" ].endswith("T00:00:00+00:00") + assert calls[0]["force"] is True assert any("_typeFilter=" in c.value for c in at.caption) + # watermark mode hands the service the sentinel + at.radio(key="exp_since_mode").set_value("watermark") + _button(at, "Start export").click().run() + fresh_runner.wait(fresh_runner.all()[0].id) + assert calls[-1]["since"] == svc.SINCE_AUTO + at.radio(key="exp_since_mode").set_value("off") at.checkbox(key="exp_per_type").uncheck() at.checkbox(key="exp_use_svc_date").check() _button(at, "Start export").click().run() @@ -427,6 +442,72 @@ class TestRunsPanel: fresh_runner.wait(fresh_runner.all()[0].id) +# ── Sync ───────────────────────────────────────────────────── + + +class TestSync: + def test_empty_store(self, tmp_store) -> None: + at = _page("sync").run() + assert not at.exception + assert any("No complete jobs" in i.value for i in at.info) + assert at.title[0].value == "Sync" + + def test_with_jobs_and_reconcile( + self, monkeypatch, tmp_store, fresh_runner + ) -> None: + from datetime import datetime, timezone + + from bcda import sync + + from .test_sync import _rows, add_job + + t0 = datetime(2026, 10, 1, tzinfo=timezone.utc) + add_job(tmp_store, "B1", {"Patient": _rows("Patient")[:5]}, transaction_time=t0) + at = _page("sync").run() + assert not at.exception + assert any("1 pending" in b.label for b in at.button) + assert any("nothing applied" in c.value for c in at.caption) + calls: list = [] + monkeypatch.setattr( + svc, + "load_and_publish", + lambda **kw: calls.append(kw) or {"bcda.patient": 5}, + ) + _button(at, "Reconcile now (1 pending)").click().run() + run = fresh_runner.wait(fresh_runner.all()[0].id) + assert run.state == "done" and run.result["applied"] == ["B1"] + assert calls == [{"run_pipeline": True, "skip_flatten": True}] + assert sync.read_ledger(tmp_store)[0]["job_key"] == "B1" + # the ledger renders, and the inflated page still has no pending work + at = _page("sync").run() + assert not at.exception + assert any("Reconcile now" == b.label for b in at.button) + assert any("patient" in d.value.to_string() for d in at.dataframe) + # a failed ledger row surfaces as an error + sync._append_ledger( + tmp_store, + { + "applied_seq": 2, + "job_key": "BAD", + "kind": "delta", + "endpoint": "Group/all", + "type_filter": "", + "types": "Patient", + "since": "x", + "transaction_time": "", + "transaction_source": "job_row", + "applied_at": "", + "ok": False, + "counts": "{}", + "notes": '["scope differs"]', + "error": "SyncInvariantError: boom", + }, + ) + at = _page("sync").run() + assert any("boom" in e.value for e in at.error) + assert any("note(s)" in e.label for e in at.expander) + + def test_app_shell_renders() -> None: at = AppTest.from_file( str(Path(views.__file__).with_name("app.py")), default_timeout=60 @@ -440,6 +521,7 @@ def test_app_shell_renders() -> None: "Exports", "Store", "Flatten + load", + "Sync", "Data", "Dictionary + crosswalk", "Upstream", diff --git a/tests/cli/test_cli_bcda.py b/tests/cli/test_cli_bcda.py index 17544d3..0d83b1e 100644 --- a/tests/cli/test_cli_bcda.py +++ b/tests/cli/test_cli_bcda.py @@ -17,6 +17,9 @@ class _FakeClient: base_url = svc.SANDBOX version = "v3" + def close(self) -> None: + pass + def __enter__(self): # noqa: ANN204 return self @@ -178,6 +181,21 @@ def test_adopt_and_cancel(monkeypatch) -> None: result = runner.invoke(app, ["bcda", "cancel", "78"]) assert result.exit_code == 0 and seen["cancel"].endswith("/jobs/78") + class _ResumeStore(_FakeStore): + def get_job(self, key): # noqa: ANN001, ANN202 + return {"status": "complete", "transaction_time": "2026-10-25T00:00:00Z"} + + monkeypatch.setattr(svc, "make_store", lambda path=None: _ResumeStore()) + monkeypatch.setattr( + svc, "resume_job", lambda store, client, key: seen.update(resume=key) or key + ) + result = runner.invoke(app, ["bcda", "resume", "K9"]) + assert result.exit_code == 0, result.output + assert ( + seen["resume"] == "K9" + and "transactionTime=2026-10-25T00:00:00Z" in result.output + ) + def test_store_load_vendor(monkeypatch, tmp_path) -> None: monkeypatch.setattr(svc, "make_store", lambda path=None: object()) @@ -249,3 +267,189 @@ def test_ui_launches_streamlit(monkeypatch) -> None: cmd = call.call_args.args[0] assert cmd[1:3] == ["-m", "bcda.ui"] assert cmd[cmd.index("--server.headless") + 1] == "false" + + +# ── sync ───────────────────────────────────────────────────── + + +def test_help_lists_sync() -> None: + result = runner.invoke(app, ["bcda", "sync", "--help"]) + assert result.exit_code == 0 + for cmd in ("status", "check", "apply", "pull"): + assert cmd in result.output + + +def test_export_since_auto_refused(monkeypatch) -> None: + monkeypatch.setattr(svc, "make_store", lambda path=None: _FakeStore()) + monkeypatch.setattr( + svc, "resolve_since", lambda store, since, **kw: {"Patient": None} + ) + + def refuse(store, client, **kw): # noqa: ANN001, ANN003, ANN202 + raise svc.SinceBlocked( + [ + { + "level": "block", + "code": "no_baseline", + "message": "Patient: none", + "resource_type": "Patient", + } + ] + ) + + monkeypatch.setattr(svc, "export_per_type", refuse) + result = runner.invoke(app, ["bcda", "export", "-t", "Patient", "--since", "auto"]) + assert result.exit_code == 2 + assert "_since Patient: — no baseline —" in result.output + assert "✗ no_baseline" in result.output and "--force" in result.output + + +def test_sync_status_and_check(monkeypatch) -> None: + monkeypatch.setattr(svc, "make_store", lambda path=None: _FakeStore()) + status = { + "watermarks": [ + { + "population": "current", + "type_filter": "", + "resource_type": "Patient", + "job_key": "B1", + "transaction_time": "2026-10-01T00:00:00.000+00:00", + "kind": "baseline", + "applied": False, + } + ], + "jobs": [ + { + "key": "B1", + "kind": "baseline", + "endpoint": "Group/all", + "type_filter": "", + "types": "Patient", + "since": "", + "transaction_time": "2026-10-01T00:00:00.000+00:00", + "transaction_source": "job_row", + "applied": False, + } + ], + "pending": ["B1"], + "ledger": [ + { + "applied_seq": 1, + "job_key": "B0", + "kind": "baseline", + "ok": True, + "counts": {"patient": {"new": 3, "replaced": 0, "retired": 0}}, + "notes": [], + } + ], + "current": {"patient": 3}, + } + monkeypatch.setattr(svc, "sync_status", lambda store=None: status) + result = runner.invoke(app, ["bcda", "sync", "status"]) + assert result.exit_code == 0, result.output + assert "(not yet applied)" in result.output and "PENDING" in result.output + assert "patient=3" in result.output and "patient:3+/0~/0-" in result.output + result = runner.invoke(app, ["bcda", "sync", "status", "--json"]) + assert result.exit_code == 0 and '"pending"' in result.output + + plan = {"Patient": "2026-10-01T00:00:00.000+00:00", "Coverage": None} + monkeypatch.setattr( + svc, + "resolve_since", + lambda store, since, **kw: { + t: v for t, v in plan.items() if not kw.get("types") or t in kw["types"] + }, + ) + monkeypatch.setattr( + svc, + "since_checks", + lambda store, since, **kw: [ + { + "level": "ok", + "code": "watermark", + "message": "fine", + "resource_type": "Patient", + } + ], + ) + result = runner.invoke(app, ["bcda", "sync", "check", "--offline"]) + assert result.exit_code == 2 # Coverage has no baseline + assert ( + "✓ watermark" in result.output + and "Coverage: _since — no baseline —" in result.output + ) + result = runner.invoke(app, ["bcda", "sync", "check", "auto", "-t", "Patient"]) + assert result.exit_code == 0, result.output + + +def test_sync_apply_and_pull(monkeypatch) -> None: + monkeypatch.setattr(svc, "make_store", lambda path=None: _FakeStore()) + counts = {k: 0 for k in svc.sync.COUNT_FIELDS} | { + "rows": 10, + "new": 3, + "current": 13, + } + report = { + "ok": True, + "applied": [ + { + "job_key": "D1", + "kind": "delta", + "since": "2026-10-01T00:00:00.000+00:00", + "transaction_time": "2026-10-08T00:00:00.000+00:00", + "ok": True, + "counts": {"explanation_of_benefit": counts}, + "notes": ["transactionTime from job_row"], + } + ], + "skipped": ["B1"], + } + seen: dict = {} + monkeypatch.setattr( + svc, + "apply_sync", + lambda store=None, keys=None, force=False: ( + seen.update(keys=keys, force=force) or report + ), + ) + monkeypatch.setattr(svc, "load_and_publish", lambda **kw: {"bcda.patient": 5}) + result = runner.invoke(app, ["bcda", "sync", "apply", "--force", "-k", "D1"]) + assert result.exit_code == 0, result.output + assert "D1 delta" in result.output and "new= 3" in result.output + assert ( + "already applied: B1" in result.output and "Replica published" in result.output + ) + assert seen == {"keys": ["D1"], "force": True} + + monkeypatch.setattr( + svc, + "resolve_since", + lambda store, since, **kw: {"Patient": "2026-10-01T00:00:00.000+00:00"}, + ) + calls: list = [] + monkeypatch.setattr( + svc, + "export_per_type", + lambda store, client, **kw: calls.append(kw) or {"Patient": "D2"}, + ) + result = runner.invoke(app, ["bcda", "sync", "pull", "-t", "Patient", "--no-apply"]) + assert result.exit_code == 0, result.output + assert calls[0]["since"] == "auto" and "Patient: job D2" in result.output + result = runner.invoke(app, ["bcda", "sync", "pull", "-t", "Patient"]) + assert result.exit_code == 0 and "Replica published" in result.output + + def refuse(store, client, **kw): # noqa: ANN001, ANN003, ANN202 + raise svc.SinceBlocked( + [ + { + "level": "block", + "code": "gap", + "message": "gap", + "resource_type": "Patient", + } + ] + ) + + monkeypatch.setattr(svc, "export_per_type", refuse) + result = runner.invoke(app, ["bcda", "sync", "pull", "-t", "Patient"]) + assert result.exit_code == 2 and "✗ gap" in result.output