# dag_tools Project Context
This document provides high-level context for AI tools and agents exploring this repository.

## Domain
`dag_tools` is the foundational, shared library for all of our Dagster data engineering projects. It does not run specific ETL pipelines itself. Instead, it provides the generalized infrastructure that other projects (like `pub-tools`) rely upon.

## Architecture
This repository contains:
1.  **IO Managers**: Custom Dagster IO Managers for handling data serialization/deserialization across cloud storage (S3) and databases (DuckDB, Postgres). Includes advanced native `ArrowIOManager` coercing S3 PyArrow formats into Pandas DataFrames.
2.  **Resources**: Reusable clients and connections (e.g., API clients, database connection pools, `dlt` pipeline wrappers, `ArrowResource`, `S3SensorResource`).
3.  **Sensors & Schedules**: There is **no sensor library and no schedule library** here. `dag_tools/sensors/` holds an empty `__init__.py` and there is no `dag_tools/schedules/` package at all -- every sensor and every schedule in this repository is built by a **component**, from that component's YAML, which is the standing rule (`AGENTS.md` §2). Sensors: `S3SensorComponent` (new objects under a prefix -> one run per object, registering a **dynamic** partition per key, the key's slashes replaced; it *excludes* `metadata.json` by default rather than reading flags out of it, and it does no chronological or PyArrow partitioning), `RestateDltSyncComponent` (three), `GristIngestComponent`, and `ClassificationPropagationComponent` (one sensor and no assets). Schedules: `DltPipelineComponent`'s per-pipeline `schedule:` block, built in Python, created **stopped**, selecting only its own pipeline's asset keys. Nothing generalized sits underneath them; a sensor that is wanted without a component does not exist yet.
4.  **Asset Wrappers**: Traditional Python factory functions or decorators that standardize repetitive `@asset` patterns across the organization.
5.  **Components**: Formal Dagster 1.12 GA Declarative Components (`dagster.components`). Components use the `Component, Resolvable, Model` pattern and allow downstream users to deploy complex pipelines the full set, under `dag_tools/components/`: `s3_sensor`, `dlt_pipeline`, `dbt_project`, `datahub_lineage`, `grist_ingest`, `restate_dlt_sync`, `restate_api_sync`, `otel_api_sync`, `read_audit`, `tagged_warehouse`, `contract_mapping`, `warehouse_source`, `classification_propagation`) using pure YAML architecture. Schemas are plain `pydantic.BaseModel` classes.
6.  **Utilities**: Helper functions for logging, metadata formatting, AssetKey normalization (`AssetNormalizationRegistry`), testing, dynamic Kubernetes resource tag resolution (`dag_tools.utils.k8s`), and multi-environment dbt compilation/validation (`scripts/compile_and_validate_dbt.py`).
7.  **Restate Handlers (Data Plane)**: Generic durable execution handlers (`GenericOracleAckService`, `GenericOracleControlService`, `GenericApiSyncService`, `ApiCallPlanService`, `SapInductionService` -- the five keys in `serve.SERVICE_REGISTRY`; `ApiCallPlanService` is a **VirtualObject**, keyed per execution group, and the other four are plain services) that execute isolated API pushes and Database commits durably. Every handler whose parameter is a payload reads and refuses it **inside** its `ctx.run` step, because a bound bounds the step and a refusal raised out at the handler fails the *invocation*, which Restate retries with no attempt bound at all; `db_retry` holds the one refusal (`MalformedPayload`), the bound (`run_options`) and the two guards -- `terminal_on_damage` for a step that connects to a database, `terminal_on_refusal` for one that does not. The `SapInductionService` implements a **Durable State Machine** (NEW -> PENDING -> SUCCESS) with persistent retry tracking.
7a. **Inventory Contract (`dag_tools.inventory`)**: The shared structural-inventory schema for Dagster assets. A versioned `AssetRecord` pydantic model (`schema_version`, IO manager FQN + `family`, partitions/mapping FQNs, resource classes, integration libs, automation condition type, freshness/backfill, tags, asset checks, jobs, and a DataHub URN sidecar) plus a soft-failing extractor that walks a `Definitions`. **Two consumers**: the runtime Domain Broker (uses `io_manager_family` for mesh routing) and the `dagtools survey` CLI (publishes per-build inventory to MinIO for the Dagster upgrade qualification system). Evolution is **additive-only**; the long-lived Broker and the CI survey will be reading each other's records across versions.
7b. **Qualification System (`dag_tools.qual`)**: The desktop `dagtools` CLI (Typer) and the MinIO/S3 registry that backs it. `dag_tools.qual.registry` provides the `S3Storage` (immutable vs. mutable put modes), `InventoryRegistry` (composes layout + storage; `publish_build` writes per-SHA artifacts immutably then a mutable `latest.json` pointer LAST so readers never observe partial builds), and `compute_staleness` (the staleness reporter behind `dagtools registry status`). The layout module (`registry/layout.py`) owns every object-store key string. `dag_tools.qual.survey` provides `run_survey` — the publisher that loads every code location with `-W all` warning capture, refuses to publish if **any** load fails, and otherwise introspects assets, automation, io_managers summary, and dbt projects (custom-translator flagged). `dag_tools.qual.qualify` provides Q0 of Phase 2: `create_qualification` pins the registry's inventory snapshot into a `QualificationManifest` (immutable per qual_id), records the baseline/candidate version pair, and diffs non-Dagster library pins into `co_upgrade_risks[]` so a hidden dbt-core / warehouse bump can't propagate as a false Dagster regression. `dag_tools.qual.classes` provides Q1: `build_class_matrix` reads the manifest's pinned inventories (NOT the registry's current latest), groups assets by the recipe key (compute kind, IO manager FQN, partitioning, resources, integration libs, asset checks, automation condition + custom dbt translator FQNs), hashes each class deterministically (SHA-256[:12]), picks representatives spanning repos with `regression`-tag preference, classifies each as `RUNNABLE` / `SYNTHETIC_REQUIRED` / `OBSERVE_ONLY` by opt-in tags, and publishes `equivalence_classes.json` + `equivalence_classes.md` immutably. `dag_tools.qual.graphql` provides a version-tolerant `DagsterGraphQLClient` (launch + poll + event-log over httpx, no GraphQL library dependency, auth via `env:VAR_NAME` resolution). `dag_tools.qual.runs` provides Q2: `run_side` launches every RUNNABLE representative through the test deployment's Dagster GraphQL, polls each to terminal, builds a `RunRecord` (materializations + asset-check results + metadata-key union + failure step keys) and persists it under `qualifications/<qual_id>/<side>/runs/<class_hash>/<run_id>.json`. The per-`(qual_id, side)` `QualRunState` (pending/launched/passed/failed/skipped) is mirrored to the registry after every transition for desktop-crash recovery — re-invocation skips PASSED, reconciles LAUNCHED via run-id lookup rather than relaunching. `dag_tools.qual.preflight` provides Q3: `run_preflight` runs three checks against the test deployment via GraphQL — version matches the manifest's baseline/candidate (with `1.12.x`-style wildcard support), every code location reports `LOADED` (per-location error surfaced for triage), and (candidate side only) a deterministic sample of PASSED baseline runs still renders. Publishes `preflight.json` immutably. `dag_tools.qual.verdict` provides Q6 — the operator payoff: `build_verdict` walks every artifact under a qual_id (manifest, class matrix, both sides' state + run records, candidate preflight), diffs each representative's baseline vs candidate run for success / materialization count + asset-key set / metadata KEY-set (values may differ) / asset-check parity, rolls up to per-class verdicts, then applies the recipe's GO logic. Strict by default — `GapAcceptance` opt-ins are required to skip deferred orchestration, missing synthetic probe coverage, and co_upgrade_risks. Publishes `verdict.json` + `UPGRADE_VERDICT.md` immutably. `dag_tools.qual.synthetic` provides Q5 (generation): `generate_bundle` walks the class matrix, emits a self-contained Dagster module per `SYNTHETIC_REQUIRED` class (real IO manager FQN imported by name with an `InMemoryIOManager` fallback so the code location always loads; deterministic dict payload; upstream/downstream pair asserting payload identity after the IO manager round-trip; class-unique `io_manager_<short>` resource key so N probes merge cleanly), and produces a `ProbeManifest`. `publish_bundle` writes every `<class_hash>.py` to `qualifications/<qual_id>/probes/` first and only then `probe_manifest.json` (same "pointer-last" invariant as `latest.json`). `write_local_bundle` mirrors the bundle to `~/.dagtools/quals/<id>/probes/` for operator pickup. Generated probes deliberately do NOT import `dag_tools.qual.*` so the `dag-tools-probes` location's deploy cycle stays decoupled from `dag-tools` releases. v1 deferrals (partitions defs, partition mappings, custom dbt translators) surface as `ProbeModule.notes` so operators see the gap rather than silently miss it. `dag_tools.probes_location` is the deployable Dagster code location operators point their test deployment at — `load_probes_from_dir` dynamically loads every `<class_hash>.py` from `DAGTOOLS_PROBES_DIR`, merges via `Definitions.merge`, and soft-fails per probe so one broken file never blocks the whole location. The location loads cleanly with no probes deployed (so it can be deployed once and added to over time). `dag_tools.qual.probes` provides Q5c: `run_probes_side` launches each probe's downstream asset (deps pulls upstream automatically) against the `dag-tools-probes` user-code location via the same Dagster GraphQL launcher Q2 uses, polls to terminal, builds a `RunRecord` (reusing the Q2 schema for symmetry), and persists under `<side>/probes/runs/<class_hash>/<run_id>.json`. The per-(qual_id, side) `ProbeRunState` lives in a SEPARATE slot from the runnable-rep state (`<side>/probes/state.json` vs `<side>/state.json`) — a class can be both RUNNABLE (covered by rep) and SYNTHETIC_REQUIRED (covered by probe) with neither path clobbering the other. PASSED is sacred; LAUNCHED probes reconcile via run-id lookup rather than relaunching. Q6 reads probe state AND probe RunRecords on both sides: synthetic classes with PASSED probes on both sides AND (when records exist) a clean per-record diff count toward `synthetic_classes_with_probe_coverage` (removing the missing-coverage blocker), and synthetic classes whose probes either ran-and-FAILED or DIVERGED (both PASSED but materialization / metadata / asset-check parity broke) populate `synthetic_classes_red` and block GO **regardless** of `--accept-synthetic-coverage-missing` (which only excuses *missing* coverage). `ClassVerdict.probe_diff` carries the per-class diff for `UPGRADE_VERDICT.md` so operators see exactly what diverged. Graceful degradation: PASSED states with no readable run record still count as covered — the diff augments, doesn't supplant the status check. `dag_tools.qual.probes.status` (Q5d) provides `check_probes_status`: a GraphQL cross-reference of the probe manifest against the test deployment's `dag-tools-probes` location. Per probe it determines fully_loaded (both upstream + downstream loaded), partially_loaded (one missing — usually a probe-side import error), or missing (operator hasn't redeployed yet, `DAGTOOLS_PROBES_DIR` points elsewhere, or location is ERROR); also flags `unexpected_probe_asset_keys` from stale bundles still in the probes dir. `ABSENT` is reported as a distinct location load status when the workspace doesn't even register the location. CLI exposes `dagtools survey`, `dagtools registry status`, `dagtools qual init`, `dagtools qual classes`, `dagtools qual run`, `dagtools qual preflight`, `dagtools qual synthetic`, `dagtools qual probes run`, `dagtools qual probes status`, and `dagtools qual report`; `templates/Jenkinsfile.survey` is the Jenkins shared-library snippet. Phase 1 done; Phase 2 Q0+Q1+Q2+Q3+Q4+Q5 (generation + deploy target + runner)+Q6 (with probe coverage integration) done. The Q2 IO round-trip probe and local orchestration snapshots are deferred (orchestration is a separate command).

7c. **OTel -> API Mapping Engine (`dag_tools.otel_api_sync`)**: The pure (Dagster-free, Restate-free) engine behind `OtelApiSyncComponent` and `ApiCallPlanService`. A YAML spec groups ClickHouse telemetry rows into **execution groups**, derives named collections per group, and renders an ordered **call plan** -- fully pre-rendered HTTP calls with fallbacks attached. Rendering is Dagster-side (dry-run visibility, no worker redeploy on mapping edits); execution is Restate-side (group-keyed VirtualObject, per-call durability). Four invariants are load-bearing and have named regression tests: templates render through a combined **Native + Sandboxed** Jinja environment so single-expression leaves keep real JSON types (OTel attributes are `Map(String, String)`); **fallbacks are scoped to what failed** (`mode: item`, or `mode: aggregate` which banks per-item fragments and issues one bulk call for only the failures) because bulk endpoints tend to have replace semantics; the handler treats **HTTP status as data** so a 404 reaches its fallback instead of being retried forever; and **re-dispatch is suppressed twice** (Dagster-side ledger + the object's completed-plan-hash state) since keying serializes but does not deduplicate.
7d. **Read Audit (`dag_tools.audit` + `ReadAuditComponent`)**: The read-only first step of classification work — a report of what the pipelines' identity actually reads, which asset explains each read, and which reads nothing explains. The gap is the deliverable: it sizes the classification registry and it is the number a query tag exists to drive down. `dag_tools.audit` is a **pure** package (no Dagster, no `dag_tools.qual`): `history.py` builds the SELECT against the operator's query-history relation and returns SQL plus bound parameters rather than executing it (same split as `otel_api_sync._staging_url` — CI installs no driver), and `reads.py` attributes each read six ways, in order of how much inference each needs: a query tag naming the asset, a tag naming a single-asset run, correlation against exactly one single-asset run window, then `ambiguous` / `unattributed` / `not_a_pipeline`. The last three are the report, not failures of it: an unexplained object stays in `unexplained_relations` **and** is broken out by cause, because untagged closes by deploying the tagged resource, ambiguous by narrowing a run's selection, and a non-pipeline read (the gateway's verified `on_behalf_of`) is a brokering decision rather than an attribution gap. `coverage` is `None`, not 1.0, when nothing was read. **Nothing in the package names a relation, column, level or identity — not even as a default**; the operator's names arrive through YAML and leave in the report. `ReadAuditComponent` is the primary surface (`examples/read_audit` runs against a synthetic export with no warehouse and no credentials); `dagtools audit` is a thin second door. The component's only warehouse contact is `fetch_rows(statement, parameters)` on an injected resource — the seam `TaggedWarehouseComponent` implements.

7e. **Tagged Warehouse (`dag_tools.resources.warehouse` + `TaggedWarehouseComponent`)**: The resource that closes the gap 7d measures. Every query it sends carries a query tag of `{principal, asset_key, run_id}` — principal is `pipeline:<name>` or the gateway's verified `on_behalf_of` — and **a query it cannot attribute is not sent**: `plan_tagged_query` refuses an empty tag and `execute_plan` re-checks `carries_tag` at the one chokepoint that touches a connection, before the connection is even resolved. `dag_tools.audit.warehouse` decides how the tag travels as data (a `QueryPlan` of ordered `PlanStep`s, never executed): `placement: comment` puts the tag in the statement text, `placement: session` runs the operator's own statement first with the tag **bound** as `:tag` — the library ships no dialect and guesses none, and a session statement that does not bind `:tag` fails the code-location load rather than attributing every later read to nothing. A resource cannot know which asset is reading (`InitResourceContext` exposes `run` / `dagster_run` / `run_id` and no `asset_key` — measured), so `fetch_rows` self-tags the run and `for_asset(context)` / `for_user(authz_id)` sharpen it to an asset key or a verified person. The connection has **no environment fallback** and is resolved to a URL (never an engine) during validation, so a typo fails the load and no driver is imported while a code location loads. It drops in under 7d unchanged — same `fetch_rows` seam, named by `resource_key` — and `examples/tagged_warehouse` proves it end to end against sqlite with no credentials.

7f. **Contract Mapping (`dag_tools.contract_mapping` + `ContractMappingComponent`)**: The pure (Dagster-free, dbt-free) engine that turns a **data contract** plus a **source schema** into the dbt model that satisfies it and the tests that prove it still does. `load_contract` / `load_mapping` / `build_mapping_plan` reconcile the two documents into a `MappingPlan`; `render_dbt_artifacts` renders the model, an enforced model contract and one singular test per rule; `apply_to_rows` / `check_rows` run the same plan over Python rows, which is what makes the mapping semantics testable with no warehouse. The component is the primary surface and the plan is built at the **code location load** when the contract is a file — a mapping that reads a column the source does not have, fails to produce a column a governed read selects, or disagrees with the contract about write cadence fails there rather than in a run an hour later; a **served** contract is fetched at materialization instead, because a code location must not fail to load because a service is down, and `expect_contract_id` is what stops a service that starts serving a different document from silently re-pointing the mapping. The line between a refusal and a note is whether the emitted artifact would be **wrong**: a test that could not be written (the contract names its period calendar rather than listing it; no warehouse type is declared) is a `note` on the materialization, not a failure. **Nothing is guessed to fill a gap** — no default warehouse type, no default cast template, no default non-finite predicate, no inferred calendar — because each wrong guess emits SQL that fails at the warehouse for a reason unrelated to the data; and `config.contract.enforced` is emitted only when *every* column has a declared type. Type fidelity is the engine's hard edge: integer text parses exactly past 2**53, a `numeric` column keeps the source's written form, and a non-finite value is refused by field name rather than rendered. The **asset of record is the physical platform's dataset URN** from the contract, never a `dagster` platform URN; the raw table's URN and the Dagster asset attach as lineage. `examples/contract_mapping` runs with no warehouse, no dbt project and no credentials, and `dag_tools_tests/test_contract_mapping_proof.py` proves the shipped mapping reproduces the shipped fixture exactly, types included, by inverting every transform the plan declares.
7g. **Warehouse Source (`dag_tools.warehouse_source` + `WarehouseSourceComponent`)**: Step 4a of the classification build and the first reader of the deployment's mounted dimensions document (`DAGTOOLS_CLASSIFICATION_LEVELS`, default `/etc/dagtools/classification/levels.yaml`, top-level key `classification_dimensions`). One component instance describes one source dataset — where it physically lives, which columns carry which `{dimension: values}` label, who owns it, and whether the labels came from the board or from a catalog tag — and materializes it as a Dagster **observable source asset**: no data is moved, the observation records a row count, an order-sensitive schema hash and an optional as-of watermark, and the published catalog payload carries per-column glossary terms plus a `classification_origin` property. **The asset of record is the PHYSICAL platform's dataset URN**; a `dagster` platform URN is refused at the code-location load, and the Dagster asset attaches as lineage in the fabric read off the operator's own URN, so a broker authorizing a read and a catalog describing it name one object. `dag_tools.warehouse_source` is **pure** (no Dagster, no DataHub, no SQLAlchemy, no dlt — asserted by a test that restores `sys.modules`, since a re-import mints a second copy of every exception class): the dimensions document, the label algebra (exactly one hierarchical dimension, a ceiling on it, conjunctive values elsewhere, most-restrictive as the top rung plus every facet), the observation plan and the catalog payload are all testable without infrastructure. The component reads the document at **materialization** as well as at load — the mount is the authority at the moment of the read — and an absent document fails the **run**, never the code-location load, so deny-by-default costs nothing but a missing ConfigMap cannot take the location's other assets down. Reads go through the tagged warehouse resource (7e) by `resource_key` via `fetch_columns`, which is a seam of its own because an empty table yields no rows to read names off. An unlabelled column is published most restrictive in every dimension and counted as `defaulted_columns`; a labelled column the source no longer has fails loudly rather than defaulting. Unlike the dbt publisher, **a catalog failure fails the materialization** — here the publish is the deliverable — and `dry_run` shows the exact payload with no server. No `schemaMetadata` aspect is emitted, because only column names were read. **Nothing in the package or the component names a database, schema, table, column, dimension or value**, not even as a default; `examples/warehouse_source` runs end to end against sqlite with no credentials and loads on the 1.10.19 compat floor. Downstream propagation is step 4b/4c, next door in 7h.

7h. **Classification Propagation (`ClassificationPropagationComponent`)**: Steps 4b/4c -- 7g labels a source, where a human decided what the labels ARE; this labels everything downstream, where nobody decides anything, because the label of a derived column is a consequence of what it read. The component builds **one sensor and no assets**: for each derived dataset it watches, every new materialization is read for its `dagster/column_lineage`, each output column's label is composed from the source columns that column came from, and the result is published against the dataset's own physical URN (a `dagster` one is refused, same as 7g) and recorded against the asset. What *builds* the derived table -- dbt, dlt, a Python asset -- is the deployment's business and this component neither owns nor materializes it. The composition rules live in the pure `dag_tools.warehouse_source` package (7g) and are therefore testable with no Dagster and no catalog. **Composition only ever tightens, and the directions differ**: the hierarchical dimension takes the highest rung of its inputs, a restrictive or exclusionary set unions, and a *permissive* set INTERSECTS, because a wider permissive set admits more readers. Dimension types come off the mounted document (`type: restrictive_set | permissive_set | exclusionary`, defaulting to `restrictive_set`); the library still names no dimension and no value. **A column with no lineage entry publishes the table's ceiling** -- the composition of every labelled column of every source read, deny-by-default columns included -- and the decision records which basis it used (`column_lineage` or `table_max`) and the exact source columns, so a coarse label reads as coarse rather than as wrong; composing *no* labels is refused, because an unlabelled source is not an unrestricted one. **The sources are declared, not inferred from the asset graph**: which upstreams carry labels is a policy fact, and an inferred list would compose a ceiling out of a subset of the inputs and look exactly as correct as the real answer -- so a lineage dep naming an unlisted source is refused. **Nothing is widened except by a declared rule**: a `downgrades` entry is the only thing that can publish a column wider than it derives, so `id`, `owner` and `reason` are required and the id travels on the published decision; two rules reaching one column are refused rather than ordered, a rule that would tighten any dimension is refused as a re-label, a dimension the rule omits keeps what the data derived, and an empty set CLEARS a dimension because an empty set is a value and not an omission. Published as **two patch aspects**, never a replace: `datasetProperties` and `editableSchemaMetadata` with a glossary term per column per label value **plus a remove for every other term in the vocabulary** -- add-only would leave a stricter term behind and void the downgrade, and a full aspect would wipe a crawler's metadata. The sensor is **stopped by default**, re-reads the document **every tick** (a ConfigMap can move between a deploy and a tick), isolates one dataset's failure from the others, and retries a failing dataset on later ticks without re-materializing it, so a corrected rule publishes on the next tick. Source-side lookups read the **observation** log as well as the materialization log, because a 7g source is an observable source asset and never materializes -- a materializations-only lookup refuses every real 4a source with "publishes no label set", a wiring failure wearing a labelling failure's words. Chained propagation (a derived dataset as another's source) is not supported. `examples/warehouse_source` carries it end to end against sqlite, with one derived table whose three columns show both bases and one downgrade.


7i. **Curated slice (`dag_tools.systemlink.measurements` + `.sql` + `dag_tools/dbt_project_packages/mfg_trace_curated`)**: The first thing in this library that ships **SQL** rather than a component. Two *conformed* contract documents are the seam, and the work splits in two: a deployment's own `contract_mapping` YAML maps its raw tables onto them (the one place anything from the source system is named), and a shipped dbt package derives three curated models from them (`test_result`, `test_measurement`, `test_catalog`) naming nothing from below. `measurements.py` is **pure** -- no Dagster, dbt, dlt, duckdb, sqlalchemy or jinja2 import -- and holds one rule table that both routes read: the Python evaluator, and the generator in `sql.py` that emits the package's SQL. The shipped files are asserted byte-for-byte against the generator **and** asserted to agree with the Python route over duckdb, because either test alone passes vacuously. The package is installed with a `local:` entry in the deployment's `packages.yml` pointing at `sql.PACKAGE_DIR`, and it declares a **default for none of its four required variables** -- two relations, the warehouse's own exact numeric type for the tolerance arithmetic, and the deployment's **comparator table** -- so one left unset fails `dbt parse` rather than resolving to something. The comparator table is the deployment's, as the normalizers are: the library ships no comparison codes, only the two words `low` and `high` named after the curated contract's own limit columns; matching is on the **whole** operator and never a prefix, and an operator the table does not cover is **kept as text and counted** at warning severity, never dropped and never read as a value. `is_latest` is terminal-only, because an in-flight attempt read as the latest result serves a reader a row whose result is not in yet. Stage 1 ships too, in `examples/mfg_trace/conform/`: one `contract_mapping` instance per raw table, mapping the SystemLink kind's landing tables onto the two conformed documents. It needed three transforms `contract_mapping` did not have -- `normalize` reading a **normalizer document**, `in_set` for the terminal-status flag, and a `coalesce` accepting one source plus a declared `default` -- and the example states its two limits rather than papering over them: the flattened spelling of the nested status column is dlt's own decision and is unverified against a real run, and six of the result columns are the example's own declaration of a shape this repo has never observed. `examples/mfg_trace` carries the two conformed documents, a worked dbt project with a sample comparator table that the library's own tests execute on both routes, and a README covering both stages.
7j. **Documents to tables (`dag_tools.documents` + `DocumentTablesComponent`)**: Bundles of documents become Lance tables, one dynamic partition per bundle.
  - **Input:** a bundle is a zip or a directory tree, local or on S3.
  - **The mapping:** a YAML file each deployment supplies privately. It holds the expressions (XPath for `format: xml`, JMESPath for `format: json`), the column types, the value maps, the lookups and the file-column resolution.
  - **No format in code:** nothing in code, tests or docs names a real document format. The only format anywhere is the invented one in `examples/document_tables`, and a vocabulary guard test enforces this.
  - **The engine is pure:** no Dagster import. The sources, the coercion (which never raises: a failure becomes a counted null), the reader (safe XML parsing, `max_bytes`) and the Lance writer all run without Dagster.
  - **The writer:** one dataset per table. It is idempotent per bundle (delete by `source_bundle`, then append), and the schema comes from the mapping, so an empty bundle still gets its tables. Blob columns carry `lance-encoding:blob`.
  - **The component:** a multi-asset with one asset per table. It also defines a stopped discovery sensor, four warning-severity checks (`reject_rate`, `file_resolution_rate`, `unknown_paths`, `non_empty`) and a maintenance job.
  - **Concurrency:** writes go through a Dagster pool sized by `write_concurrency`, default 1. Two writers on the same bundle were measured duplicating it.
  - **Mapping semantics:** `vars` are evaluated once per document, against the root, not per row. A scoped index files entries under (scope, key), so a key unique only within a parcel cannot cross-link parcels; a lookup into one must give `scope`. `prefer` picks one value out of a list by precedence; `order: keys` keeps the order the keys name. `document.match` globs are path globs: `*` never crosses `/`.
  - **JSON documents:** `document.format: json` keeps every XML guarantee. Values arrive typed (`3` fills an int, `3.5` into an int is a counted failure); non-identifier keys are quoted (`Depot."Dock door"`); structural paths read `$.key.list[].leaf`. A zero-byte file, `{}`, `[]` or a bare scalar gives no rows and is not a reject; `NaN` / `Infinity` are rejects. No `vars`.
  - **Rows chains:** `rows: [{as, each}, ...]` names each level; `from: <level>` (and `from: root`, always available) evaluates a column at another level, `index_of: <level>` is a 0-based position that restarts per parent. Works for XML too.
  - **Value features:** `split` (literal separator, a `list<T>` column, `keep_empty`), `extract` (regex; a miss is null and counted in `unmapped_values`), and the `basename_in` file resolution strategy (one folder, never recursive).
  - **Member tables:** `members: [globs]` instead of `rows` gives one row per bundle member, with `member: path|name|stem|ext|dir|size|modified|self` columns. `only_unreferenced: true` keeps only members no file column resolved to, decided after every document; a rejected document references nothing; `members_kept` / `members_skipped` are counted.
  - **`nulls`, `const`, `into`:** `nulls` (per column, default `document.nulls`) are strings meaning absent, matched whole after trimming, before split/extract/map/coercion. `const` is one value typed by the column's `type` at load, refusing every source step. Tables sharing an `into` write one dataset and one asset; their columns and types must be identical, a `row_id` must be unique across them (not checked), and metadata carries `rows_by_table`.
  - **Trust and spelling:** an `extract` pattern is trusted deployer config with no guard against catastrophic backtracking. `expected_paths` must use the engine's path spelling (a non-identifier JSON key quoted as a JSON string); the profiler writes it, and a list in another spelling is reported once per bundle.
  - **Parser limits:** libxml2's built-in limits (depth, huge attribute values, names, CDATA) are told apart from malformed XML by a probe re-parse; the reject names `document.huge_tree: true`. `max_bytes` still applies.
  - **Cost:** opening a bundle lists only that bundle's prefix, and maintenance keeps a scalar index on `source_bundle` so the per-bundle delete does not scan the table.
  - **Profiling:** `dagtools documents profile` surveys a source before a mapping is written. It can redact values, anonymise bundle names and scrub. Documents are never logged at INFO or above.
  - Docs are in `docs/DOCUMENT_TABLES.md`.

8.  **Control Plane vs. Data Plane Architecture**: The project is split into a Control Plane (Dagster orchestrator, Central Gateway, Domain Broker) and a Data Plane (Restate workers, Cortex Data Client). Restate workers run a single shared image (`Dockerfile.restate-worker`, published by CI). Its env-driven entrypoint `dag_tools.restate_handlers.serve` selects which handlers to host via `RESTATE_SERVICES` and self-registers with Restate on startup — consumers deploy the image and configure it purely through environment variables rather than writing bespoke entrypoints.
9.  **Federated Zero-Trust Data Mesh**: We implement a unified data mesh using DataHub URNs. The **Central Gateway** verifies Keycloak JWTs via Topaz AuthZ. The **Domain Broker** maps URNs to physical storage and mints temporary STS tickets. The **Cortex Data Client** uses Polars to fetch data natively. The **Cortex Polars IO Manager** forces Dagster to use this same client via M2M OAuth2, achieving 100% code portability between Jupyter and production.
10. **The "Holy Trinity" Pattern**: Our standard for complex integrations involves **dlt** (Extraction), **dbt** (Transformation into a stateful Outbox), and **Restate** (Durable Triggering).

**Full spec for the qualification system**: `docs/RECIPE.md` contains the recipe, the ADRs (why share code not service; why schema discipline replaces package split; FQN+MRO over substring), the regression-test guard rail table, and the implementation-status matrix.
## Component API (Dagster 1.12 GA)
All custom components inherit from `dagster.components.Component`, `dagster.components.resolved.base.Resolvable`, and `dagster.components.resolved.model.Model`. Key rules:
- **No `ComponentSchema`** — schemas are plain `pydantic.BaseModel` or use `Model` directly on the component class.
- **No manual `load()` overrides** — the base class handles YAML attribute resolution automatically via `Resolvable`.
- **`build_defs(self, context)` remains** the primary definition factory method.
- **Normalized Configuration** — components MUST use the Dagster configuration framework to wrap native tool configurations (dlt, dbt, restate), exposing a standardized Dagster-centric schema while handling internal translation to the tool's requirements.
- **Factory pattern for @asset closures** — Dagster 1.12 introspects function parameters as asset inputs; use factory functions to capture closure variables.

## Local Development
Other projects will typically install this repository as a dependency. When developing `dag-tools` locally:
```bash
uv run dagster dev
```
All new common tools should be accompanied by a small "example" usage asset to ensure they load properly in the local UI.
