---
description: Coding standards and technology stack rules for the dag-tools common resource repository.
---

# `dag-tools` Tech Stack & Rules

This project serves as the central hub for common Dagster utilities, resources, I/O managers, sensors, and asset wrappers used across our external repositories.

## 1. Dependency Management (`uv`)
- **Rule**: NEVER use `pip`, `poetry`, or `conda` directly. 
- **Tool**: Always use `uv` for all environment and dependency management.
- **Commands**: 
  - Install dependencies: `uv add <package>`
  - Run scripts: `uv run <script>`
  - Sync lockfile: `uv sync`
  - Start Dagster: `uv run dagster dev`

## 2. Shared Dagster Resources
- **Rule**: All assets and resources here must be highly generic and reusable. This repo does not execute domain-specific business pipelines.
- **Purpose**: Any IO Manager (e.g., S3, DuckDB), Resource (e.g., dlt wrappers, API clients), or partition definitions used across multiple projects should be housed here.
- **A sensor or a schedule is built by a COMPONENT, from its YAML, not housed as a shared definition.** `dag_tools/sensors/` is an empty package and there is no `dag_tools/schedules/`; every sensor here belongs to `S3SensorComponent`, `RestateDltSyncComponent`, `GristIngestComponent` or `ClassificationPropagationComponent`, and the one schedule belongs to `DltPipelineComponent`. A new sensor goes in the component whose YAML configures it (§2 above, Declarative Component First); do not add a generalized sensor module for one to be imported from.

## 3. Python Style
- **Type Hinting**: All function signatures and classes must include strict Python type hints (e.g., `def create_s3_io_manager(bucket: str) -> IOManagerDefinition:`).
- **Docstrings**: Provide a brief Google-style or standard docstring explaining the configuration kwargs and usage examples for all shared components. This is critical because other repositories will depend on these docstrings.
- **Imports**: Ensure all public-facing common tools are neatly exported in `dag_tools/__init__.py` so they are easily importable by downstream consumers (e.g., `from dag_tools import CommonS3IOManager`).

## 4. Ecosystem & Integrations Stack
- **Dependencies**: The framework explicitly supports `pyarrow`, `pandas`, `s3fs`, `httpx`, `pyodbc`, `oracledb`, and the `restate-sdk`. Do not reinstall duplicative dependencies natively (e.g. `requests` instead of `httpx`).
- **Dagster Version**: This project targets **Dagster 1.12+ (core)** / **0.28+ (libraries)**. The old experimental `dagster-components` library is deprecated — use `dagster.components` (built-in to core).
- **Restate SDK Constrains**: 
  - Never hardcode API Keys or DB passwords into Dagster `kwargs` mapped to Restate. Always pull from `os.environ.get()` inside Restate `ctx.run` blocks for strict Kubernetes injection isolation.
  - When fan-out querying DB sources during Restate extraction syncs, chunk Database executions strictly (e.g. 10,000 max size for HTTP DAG dispatches, 1,000 max size for legacy Oracle `IN` clauses).
  - **HTTP/2 Standard**: All Restate ASGI servers must use `Hypercorn` (or equivalent) to support HTTP/2, as required by modern Restate SDKs (`>=0.14.0`).
  - **HTTP status is data, never an exception**: `ctx.run` retries anything that raises, so a handler that calls `raise_for_status()` turns a branchable 404 into an infinite backoff loop and its fallback never runs. Return `{"status", "body"}` from the closure and classify outside it — 2xx done, declared fallback statuses branch, 5xx/429/408 raise (Restate retries), everything else `restate.TerminalError`.
  - **A `ctx.run` that connects to a database must be bounded AND terminal on a wrong password**: each failed login spends one of the account's `FAILED_LOGIN_ATTEMPTS`, so the retry is itself what locks the account out and takes down every other consumer of it. `dag_tools/restate_handlers/db_retry.py` is the one place this lives -- `terminal_on_damage(...)` plus `**run_options()`, splatted at the call site so both halves read in one pass. The classifier reads `str(exc)` and imports no driver. A `TerminalError` message never quotes a driver's text (it carries the connect identifier and sometimes the account name); our own exceptions' messages do travel, and name only variables and fields.
  - **Validate the payload INSIDE the step, never before it**: a refusal outside `ctx.run` fails the whole invocation, which Restate retries with no attempt bound at all and no journal entry naming what was wrong. Raise `db_retry.MalformedPayload` (a `ValueError` subclass, terminal on the first failure) from inside the step, collect every problem rather than the first, and name the refused fields and no value from any of them. Watch for sequence-shaped strings: a string of ids is truthy, sliceable and iterable, so a presence check accepts it and the chunker binds it one character at a time. When one payload feeds **two** steps, each step refuses for itself -- they are separate journal entries and a replay can execute either without the other. All four payload handlers are converted and `test_every_payload_handler_refuses_inside_its_step` fails on a fifth that is not.
  - **A `ctx.run` that does NOT connect takes `terminal_on_refusal`, never `terminal_on_damage`**: the damage classifier matches a driver's codes as standalone numbers anywhere in the exception text, and an HTTP failure quotes the URL it failed on -- so `404 ... /orders/18456` reads as a failed login and the call is abandoned on the first attempt, which is the retry the step exists for. `terminal_on_refusal` makes only our own refusals (`MissingCredentials`, `MalformedPayload`) terminal and classifies nothing else, so an unbounded step can refuse its payload without borrowing a database's vocabulary.
  - **Keying serializes, it does not deduplicate**: a second dispatch of the same VirtualObject key is a second invocation. Handlers with append-shaped effects must record completed work in object state and short-circuit repeats.
  - **Fallbacks are scoped to failures**: never render a retry/fallback payload over a whole batch. Bulk endpoints frequently have replace semantics, so a group-wide fallback overwrites state for items that already succeeded. Pre-render per-item fragments and splice in only what failed (`dag_tools/otel_api_sync`).
  - **Mapping templates need native types**: mapping YAML renders through `NativeSandboxedEnvironment` (`SandboxedEnvironment` + `NativeEnvironment`). Sandboxing and native typing are separate Jinja classes; using the sandbox alone stringifies every numeric/boolean/array payload field. OTel attributes are `Map(String, String)` — coerce explicitly.
  - **Shared Worker Image**: Do NOT write bespoke Restate worker entrypoints or per-project Dockerfiles. Restate workers run the shared `restate-worker` image (repo-root `Dockerfile.restate-worker`); its env-driven entrypoint `dag_tools.restate_handlers.serve` selects services via `RESTATE_SERVICES` and self-registers via `RESTATE_ADMIN_URL` / `RESTATE_ADVERTISED_URI`. Register every new durable handler in `serve.SERVICE_REGISTRY` so it is selectable. Deployments configure workers purely through environment variables.

## 6. Docker Build Best Practices
- **Layer Caching**: When using `uv` with a local package, use the "metadata trick" (creating dummy `__init__.py` and `README.md`) to cache dependencies.
- **Shadowing Prevention**: ALWAYS `rm -rf` dummy metadata directories/files (created for caching) immediately before the final `uv pip install -e .` step. Failing to do so will cause the empty dummy directory to shadow the real package in the container's working directory, leading to `ModuleNotFoundError`.

## 4l. Classification (invincible-agent ADR-0064 steps 3-5; `warehouse_source` is the first reader -- 4m)
- **Never ship a classification file in dag-tools.** Read the deployment's copy: env `DAGTOOLS_CLASSIFICATION_LEVELS`, default path `/etc/dagtools/classification/levels.yaml` (the mount is unchanged by the dimensions amendment), top-level key `classification_dimensions`.
- **Exactly one dimension is `hierarchical`, and the file says which.** Discover it from the flag; never name it in code. Zero or two must fail the load.
- **Within a dimension, order is list position, least restrictive first. A clearance is a CEILING on the hierarchical dimension** — never an exact match. Every other dimension declares `type:` — `permissive_set` (holds >=1), `restrictive_set` (holds all), `exclusionary` (holds none); an undeclared one is a restrictive set, which is what every unordered dimension already meant. Access is the conjunction across dimensions.
- **An absent or empty file means most restrictive in every dimension** — deny by default, which with nothing declared means nothing is served. A missing mount must never read as "unclassified, therefore readable". Most restrictive is the ladder's last row, EVERY value of a restrictive or exclusionary dimension and NO value of a permissive one: empty releases to nobody there and to everybody elsewhere, so never read an empty set as "no restriction" without asking the dimension.
- **Never write a dimension id or a value string in code, as a default, or in a comment.** Validate every configured label against the mounted file and fail the load on anything it does not declare.
- **A column label is `{dimension: values}` with the hierarchical dimension required** — not a bare `level`. Hierarchical takes exactly one value; a label that omits it fails the load, while a column with no label at all is most restrictive.
- **Propagate per dimension: `max` on the hierarchical one, UNION on a restrictive or exclusionary set, INTERSECTION on a permissive one.** Never union a permissive set — a wider one admits more readers, so that would publish a derived column to people who could read neither source. All four come off one order (`at_most_as_restrictive_as`); extend that, never a branch at a call site.
- **A derived label is total, a declared one is partial, and the two are never compared directly.** `values_for` answers `()` for both an absent dimension and an empty one, which mean opposite things on a permissive set, so ask `declares`. Overlay a downgrade rule on the derived label; a dimension the rule omits keeps what it derived.
- **No downgrade is automatic.** A standing one is a declared rule with a named owner and a reason, each application records the rule, the owner, the reason and BOTH labels, and a rule that tightens any dimension or changes nothing is refused rather than recorded. An unlabelled source column fails propagation — it does not fall to deny-by-default, which belongs where the source is declared.
- **Use the physical platform's dataset URN as the asset of record, never a `dagster` platform URN.** The catalog registers under the physical platform; the Dagster asset is lineage.

## 4m. Warehouse source (`dag_tools.warehouse_source` + `WarehouseSourceComponent`)
- **The engine stays pure.** `dag_tools/warehouse_source/` imports no `dagster`, `datahub`, `sqlalchemy` or `dlt` — documents and rows in, plans and payloads out. The component next door does every read, every emit and every file load. Regression: `test_the_engine_imports_no_dagster_no_datahub_no_warehouse` (which also restores `sys.modules`, since a re-import mints a second copy of every exception class).
- **Refuse a `dagster` platform dataset URN at the load.** The asset of record is the physical platform's URN; the Dagster asset is attached as lineage in the fabric read off that URN. Never derive a platform or a fabric from anything in this library.
- **Read the dimensions document at MATERIALIZATION, not only at load.** The mounted document is the authority at the moment of the read. An absent document must fail the **run** (deny by default) and must not fail the code-location load — one missing ConfigMap must not take the location's other assets down. A label the document contradicts does fail the load.
- **A schema observation uses `fetch_columns`, never `fetch_rows`.** An empty table yields no rows, so names read off a row report a source with zero columns — which then publishes an empty table and fails every declared label as stale. Keep the two seams separate; both still refuse an untagged read.
- **No run config on an observable source asset.** Dagster calls `observe_fn(context, **resource_kwargs)`, so a pythonic `config:` parameter raises `TypeError` at run time, not definition time (1.10.19 and 1.13.1 alike), and there is no `owners` parameter. Every knob is a YAML attribute.
- **Name the keys when selecting this asset.** `AssetSelection.all()` excludes source assets; a job built that way runs zero steps and reports success. Use `AssetSelection.assets(*keys)` in tests, jobs and schedules.
- **A catalog failure FAILS the materialization** — the opposite of the dbt publisher (4i), because here the publish is the deliverable. Never swallow an emit error; use `dry_run` to inspect a payload without a server. Emit no `token` key when there is none.
- **Emit no `schemaMetadata`** — only column names were read, and that aspect belongs to a crawler. Labels ride on `EditableSchemaMetadata` glossary terms per field.
- **Unlabelled column = most restrictive in every dimension, reported as `defaulted_columns`. A labelled column the source no longer has RAISES.** Keep the two distinguishable; never default a stale label.
- **Count rows exactly and positionally** (no float path), refuse a grouped count, refuse an absent as-of, and send an operator's statement verbatim. A relation carrying a statement separator fails the load.
- **A column with no declared lineage carries the TABLE MAX, never nothing.** `TableColumnLineage` is what narrows it; composing no labels at all is refused outright, because the least restrictive label must never be arrived at.

## 4n. Classification propagation (`ClassificationPropagationComponent`; steps 4b/4c over 4m's engine)
- **Look a source's label set up in BOTH event logs; look the derived asset up in the materialization log only.** A 4a source is an observable source asset, so it only ever emits an `AssetObservation` — a materializations-only lookup refuses every real source with "publishes no label set". The derived side must stay materializations-only, because this sensor writes its own observation against the derived asset and counting it would republish on every tick forever.
- **Declare the sources per dataset; never infer them from the asset graph.** Which upstreams publish labels is a policy fact. Refuse a lineage dep naming an undeclared source, and fail the dataset when a declared source has published nothing — never compose a ceiling from a subset of the inputs.
- **Publish two PATCH aspects, never a replace:** `datasetProperties` then `editableSchemaMetadata`, the latter *removing* every vocabulary term it does not set. Add-only leaves a stricter term behind and voids a downgrade; a full aspect wipes a crawler's metadata.
- **Validate a downgrade rule's label against the mounted document at the LOAD**, and require `id`, `owner` and `reason`. Two rules for one column are refused rather than ordered; a rule that tightens any dimension is refused; an empty set clears a dimension, an omitted one keeps what the data derived.
- **The sensor ships STOPPED, re-reads the document every tick, isolates one dataset's failure and retries it without re-materializing.** An absent document fails the tick, not the load (4m's split). Never start publishing classifications because a code location loaded.
- **Build no assets here.** What materializes a derived table is the deployment's business; this component reads the `dagster/column_lineage` Dagster already carries. A derived dataset cannot be another's source — chaining is not supported, and must not be half-built.

## 4k. Contract mapping (`dag_tools.contract_mapping` + `ContractMappingComponent`)
- **The engine is pure.** No Dagster, no dbt, no dlt imports and no IO in `dag_tools/contract_mapping/`: documents in as dicts, a `MappingPlan` out. The component, the row route and the tests all share it, which is what makes the mapping semantics testable with no warehouse and no dbt project.
- **Refuse what would be WRONG; note what is merely unproven.** A mapping that reads a column the source does not have, drops a column a governed read selects, or disagrees with the contract about write cadence fails the code-location load. A test that could not be written (the contract names its period calendar instead of listing it; no `warehouse_types`; no `non_finite_predicate`) is a `note` — the model is correct, there is just less proof of it. Do not promote a note to a refusal or demote a refusal to a note without the test that says which it is.
- **Guess nothing to fill a gap.** No default warehouse type, no default cast template, no default non-finite predicate, no inferred calendar. Each wrong guess emits SQL that fails at the warehouse for a reason unrelated to the data, and a guessed predicate silently matches nothing. `config.contract.enforced` is emitted only when EVERY column has a declared type — a half-typed contract is not a contract.
- **A file contract is reconciled at load; a served contract is fetched at materialization.** A code location must not fail to load because a service is down. The served route therefore says so in its notes rather than implying the load-time check ran, and `expect_contract_id` is mandatory there: what arrives is not under the operator's control, and a service that starts serving a different document would otherwise silently re-point the mapping.
- **Render everything into memory, then write.** A dry run shows the exact bytes, and a render that fails leaves the target directory untouched. `prune` is off by default and only ever considers files named `<model>__...`: this component writes into a directory it does not own, and deleting a test an operator wrote by hand is worse than leaving a stale one.
- **Type fidelity is the hard edge.** Integer text parses exactly past 2**53 (never through `float()`); a `numeric` column keeps the source's written form, so a whole amount does not widen to `1.2e6`; a non-finite value is refused by field path rather than rendered, because JSON cannot carry it and neither can a contract. `factor` on `scale` is read as a `Decimal` — a unit conversion of money through a binary float is how a total stops reconciling.
- **Hazard: a SQL cast ROUNDS where the row route REFUSES.** The row route rejects a scaled value that is not whole; `cast(... as <integer type>)` rounds in most dialects. The cast is the operator's own SQL from `cast_templates` and this library owns no dialect, so this is documented (example README) rather than papered over. Do not "fix" it by rounding the row route to match.
- **Every emitted test fails under a rule the contract declares.** A failure naming an id outside the contract's `rules:` cannot be acted on by anyone reading the contract. `tests_under_undeclared_rules` is on every materialization, and the key-uniqueness id is derived structurally from the contract's grain rather than written down here.
- **The asset of record is the PHYSICAL platform's dataset URN**, from the contract — never a `dagster` platform URN. The mapped model is what a governed read is served from, so that is what the catalog registers and what a broker authorizes; the raw table's URN and the Dagster asset attach as lineage.
- **Stay inside `type:` + `attributes:` with plain dict/scalar fields validated against sibling pydantic models.** Same floor discipline as 4j: no nested `Resolvable`, `{{ env('X') }}` never `{{ env.X }}`, and no `from __future__ import annotations` in the component module. Verified on the 1.10.19 floor venv, by running it, not by reading it.
- **The example is the proof.** `dag_tools_tests/test_contract_mapping_proof.py` runs the shipped mapping over rows derived from the shipped fixture and asserts it reproduces the fixture exactly, types included, by **inverting every transform the plan declares** — so it names no column and it fails if the plan's description of a transform stops matching what the row renderer does, the one disagreement that would make a dry run a lie. The vendored contract is byte-identical to upstream and the drift canary skips rather than guessing when the upstream copy is absent.

## 4j. Read audit and the tagged warehouse (`dag_tools.audit` + `ReadAuditComponent` + `TaggedWarehouseComponent`)
- **Component first, CLI second.** The YAML surface is primary; `dagtools audit` is a thin wrapper over the same pure engine for operators with an export and no deployment. Never add behaviour the component cannot express.
- **No name, not even a default.** No relation, column, level or identity literal in `dag_tools.audit` — `HistoryColumns` has five required fields and no fallbacks. A wrong default would audit the wrong column and report an empty window as a clean audit.
- **Build the statement; let a resource run it.** `build_history_statement` returns SQL + bound `:named` params. Identifiers cannot be bound, so `validate_relation` whitelists 1–3 unquoted dotted parts (columns go through the same grammar) and refuses anything else rather than escaping. Nothing in the package opens a connection; `fetch_rows(statement, parameters)` is the whole resource seam.
- **Only the tag's principal is tested for `pipeline:<name>`.** Testing the history row's identity made every untagged read `not_a_pipeline` and left the correlation branch dead. A warehouse username is in the warehouse's namespace; narrowing to the service identity is the operator's `principal_filter`.
- **Publish the gap decomposed, and never fake coverage.** Unattributed / ambiguous / non-pipeline reads stay in the headline gap *and* are broken out (different owners). `coverage` is `None` — and omitted from metadata — when nothing was read; 0/0 is not 100%. Malformed rows are reported in `row_failures`, never dropped.
- **Stay inside `type:` + `attributes:` with plain dict/scalar fields.** That is what keeps the component loadable on the 1.10.19 compat floor, which rejects an unknown top-level key in a component file and fails the whole code-location load. Blocks are `Dict[str, Any]` validated in `schema.py`.
- **No `from __future__ import annotations` in a component module declaring a `config:` parameter** — the annotation becomes a string and Dagster cannot resolve the pythonic Config type.
- **Tagged or not sent.** `TaggedWarehouseResource` refuses a query it cannot attribute: `plan_tagged_query` refuses an empty tag and `execute_plan` re-checks `plan.carries_tag` at the chokepoint. Refuse *before* resolving the connection, so a bad connection cannot mask a missing principal. Keep `pipeline_name` optional -- on-behalf-of resources bind per request.
- **A resource cannot know the asset key.** `InitResourceContext` exposes `run` / `dagster_run` / `run_id` only -- no `asset_key`, `op_def` or `step_context` (measured). So `fetch_rows` tags the run; `for_asset(context)` is how an asset gets asset-key attribution, `for_user(authz_id)` how a brokered read gets a person.
- **Escape the colons inside a comment-placed tag.** `sa.text()` parses `:1` in `"schema_version":1` as a bind parameter and every comment-placed read fails at submission. `escape_tag_comment` escapes only inside the generated leading comment; compile strips the backslashes, so the warehouse gets the tag verbatim.
- **No env fallback for the connection, and resolve it at load.** `connection:` names a `dsn` or `drivername` + parts, or it is refused; a magic variable name would belong to whichever pipeline set it last. `warehouse_url` resolves a URL and builds no engine, so validating at load imports no driver.
- **Spell env references as `{{ env('X') }}`, not `{{ env.X }}`, in anything claiming the 1.10.19 floor.** On that version `env` is a function in the template scope; the attribute form raises `UndefinedError` and fails the whole code-location load. Current Dagster takes either.
- **Resolve the warehouse URL with SQLAlchemy, never through `config_to_credentials`.** That helper imports `dlt`, which is an `orchestrator` extra — a base install then cannot resolve a connection at all. `URL.create` percent-encodes the user info just the same.
- **Ship no tag dialect.** `comment` needs nothing; `session` runs the operator's statement, which must bind `:tag`, be one statement and carry no comment marker. One `TagTransport` validates at load and at query time.

## 4i. Verdict (`dag_tools.qual.verdict`)
- **Metadata parity is KEY-set only, never value comparison.** The recipe explicitly says "metadata values may differ" — a baseline timestamp metadata value will never equal the candidate's, and gating on that would NO_GO every qualification. Test `test_diff_compares_metadata_KEY_set_not_values` enforces this; don't relax it.
- **Duration deltas are reported but never gating.** Same recipe rule. A candidate that's 10x slower is fine for behavior preservation; it's the operator's call whether to GO. Do not add a "gates on duration" knob.
- **Strict by default.** Unknown gaps block GO. `GapAcceptance` exists so operators can explicitly accept "yes, I know orchestration isn't implemented and I'm OK going without it" — the verdict layer does NOT decide that on the operator's behalf. New gaps follow the same pattern: add a `GapAcceptance` field defaulting to False, surface a blocking issue when False, document the override flag in the CLI.
- **Candidate-preflight failure is a hard gate, period.** No GapAcceptance bypass exists or should be added — the operator should fix the deployment, not paper over it.

## 4h-1. Probe deploy-state status (`dag_tools.qual.probes.status`)
- **Location name is HARD-CODED to `dag-tools-probes`** — same constant the runner uses. If a future deployment needs configurability, surface it through the manifest, not a per-call override.
- **`ABSENT` is distinct from `LOADED` empty.** The workspace returning no `dag-tools-probes` entry is its own diagnostic state (operator forgot to register the location); don't collapse it into "no probes."
- **Partial loads are visible, not silenced.** Upstream-loaded-downstream-missing (or vice versa) usually means an `_IO_MANAGER_ERROR` fallback path is masking a class-import problem. Surface it; the operator needs the asymmetry to triage.
- **Unexpected probe-shaped assets are INFORMATIONAL.** Stale files in `DAGTOOLS_PROBES_DIR` get flagged but don't fail `all_loaded` — forcing operators to wipe the probe dir every iteration would be hostile.

## 4h0. Probe runner (`dag_tools.qual.probes`) + Q6 synthetic coverage
- **Probe state is in its OWN slot — never mixed with runnable-rep state.** `qualifications/<qual_id>/<side>/probes/state.json` for probes; `<side>/state.json` for runnable reps. Run records mirror: `<side>/probes/runs/.../` vs `<side>/runs/.../`. The two paths must not collide because a class can legitimately be both RUNNABLE (covered by a rep) and SYNTHETIC_REQUIRED (covered by a probe), and Q6 reads both.
- **The probe state schemas are SEPARATE TYPES** (`ProbeRepState` / `ProbeRepStatus`) from the rep state types (`RepState` / `RepStatus`). They have the same status values but distinct types — accidental cross-wiring fails type checks at the call site instead of silently working.
- **Launch BOTH the upstream AND downstream asset in ONE run.** Selecting only the downstream does NOT auto-materialize the upstream — Dagster treats it as a loaded input whose output must already exist, so downstream-only dies with `DagsterExecutionLoadInputError`. Both must run together: upstream writes via the real IO manager, downstream reads it back and asserts identity (the write→read round-trip is the probe's whole purpose). Live-tested against `dagster dev`; regression `test_run_probes_side_launches_against_dag_tools_probes_location` asserts both keys. Do NOT "optimize" back to downstream-only.
- **Location name is hard-coded to `dag-tools-probes`.** That's the contract with `dag_tools.probes_location`. If a future deployment needs configurability, surface it through the manifest's deployment config — not through a per-call override.
- **Reuse the Q2 `RunRecord` schema.** Probe runs use the same persisted shape so Q6 can diff them the same way runnable-rep runs are diffed.
- **`synthetic_classes_with_probe_coverage`** counts classes where probes PASSED on BOTH sides AND (when records exist) diff cleanly. One-sided wins don't count.
- **`synthetic_classes_red`** lists classes whose probes ran-and-FAILED OR ran-and-DIVERGED (both PASSED but records differ — exactly the regression Q6 exists to catch). Blocks GO **regardless** of `--accept-synthetic-coverage-missing` (which only excuses *missing* coverage). No opt-out exists for synthetic_classes_red. Regressions: `test_verdict_no_go_when_probe_failed_even_with_synthetic_accept`, `test_verdict_diverged_probes_blocks_go_even_with_passing_status`.
- **Graceful degradation.** PASSED state with no readable run record still counts as covered. The diff augments; it doesn't supplant.
- **`ClassVerdict.probe_diff`** is attached for SYNTHETIC_REQUIRED classes only. `UPGRADE_VERDICT.md` shows it in a dedicated probe-failure section for operators.

## 4h1. Synthetic probes (`dag_tools.qual.synthetic` + `dag_tools.probes_location`)
- **Generated source must always parse and the code location must always load.** The `dag-tools-probes` user-code location holds modules for every `SYNTHETIC_REQUIRED` class; one broken import blocks the whole location. The generator imports the real IO manager FQN inside a `try/except` with an `InMemoryIOManager` fallback and stamps the import error on `_IO_MANAGER_ERROR`; the probe asset raises that error at materialization, where operators can triage one probe at a time. Regressions: `test_generated_source_parses_as_python`, `test_generated_source_has_inmemory_fallback_for_missing_io_manager`.
- **Each probe binds its IO manager under a CLASS-UNIQUE resource key (`io_manager_<short>`).** `Definitions.merge` raises on conflicting resource keys; using bare `"io_manager"` for every probe would collide on merge and prevent the dag-tools-probes location from assembling more than one class. Regression: `test_each_probe_uses_class_unique_io_manager_resource_key` + `test_loaded_probes_merge_into_one_definitions_without_resource_collision`. Do not "simplify" back to a shared key.
- **Probes must NOT import `dag_tools.qual.*`.** They live in a separate code location with its own deploy cadence. If a probe imports the qual package, every `dag-tools` release becomes a probe redeploy. Regression: `test_generate_probe_source_is_self_contained`.
- **`probe_manifest.json` is written LAST.** `publish_bundle` writes every `<class_hash>.py` first and only then the manifest — same "pointer-written-last" invariant as `latest.json`. Don't reorder.
- **The dag-tools-probes location soft-fails per probe.** `load_probes_from_dir` captures failures on `ProbeLoadReport.failures` and continues — one syntax-broken `<class_hash>.py` MUST NOT block the whole location. The operator triages from the report. Regression: `test_loader_soft_fails_a_malformed_probe`.
- **The dag-tools-probes location loads cleanly with NO probes deployed.** `DAGTOOLS_PROBES_DIR` unset or pointing at a missing dir yields an empty `Definitions` — operators deploy the location once and add bundles over time. Regression: `test_loader_returns_empty_report_when_env_unset`.
- **Run + Q6-coverage integration is pending.** `qual synthetic` produces + the location deploys, but the Q2 runner doesn't yet launch probe assets per class and Q6 still requires `--accept-synthetic-coverage-missing` for synthetic classes. Until that integration ships, don't fake the coverage signal in `build_verdict`.
- **v1 deferrals surface as `ProbeModule.notes`**, not silent gaps. Partitions defs, partition mappings, and custom dbt translators that the generator can't synthesize are captured in notes and printed in the bundle output. When extending the generator, expand the synthesis; do not drop the notes path.

## 4h. Preflight (`dag_tools.qual.preflight`)
- **All checks become entries in `PreflightReport.checks`, never raise.** A `DagsterGraphQLError` from version lookup or workspace query becomes a failed `CheckResult` with the message in `detail`. Operators read the report; the runner should not crash because the deployment is misbehaving — that's WHY they're running preflight.
- **The candidate-side run-rendering check uses the baseline state, NOT the registry's `latest.json` or the class matrix.** Sampling reads `state.json` for the baseline side, deterministically sorts PASSED run_ids, and probes the top N. This is the event-log back-compat spot check — its whole point is reusing the runs that actually executed during Q2.
- **The baseline side skips the run-rendering check vacuously.** No priors exist yet. Don't add inference like "check baseline runs against the baseline deployment" — that's tautological and breaks the test `test_baseline_preflight_does_not_sample_baseline_runs`.
- **Version wildcards use `.x` suffix only.** `1.12.x` matches `1.12.0` through `1.12.999`; do NOT try to add SemVer-style range parsing — operators want to write what the manifest already shows them.

## 4g. Run execution (`dag_tools.qual.runs` + `dag_tools.qual.graphql`)
- **Resumability is the load-bearing invariant.** After every state transition (`pending` → `launched` → `passed`/`failed`), the runner saves `QualRunState` to both `~/.dagtools/quals/<id>/<side>-state.json` AND the registry's `qualifications/<id>/<side>/state.json`. If you add a new state transition, save state after it — tests in `test_runs_runner.py` enforce this.
- **Re-invocation MUST skip PASSED.** And it MUST reconcile LAUNCHED via GraphQL poll, not re-launch. A naive "just relaunch everything pending-or-not-passed" would burn duplicate compute and confuse downstream Q6 by writing two run records. The regression tests `test_run_side_skips_passed_reps_on_re_invocation` and `test_run_side_reconciles_launched_via_poll_not_relaunch` enforce both.
- **GraphQL queries use public fields only.** No `dagster._core.*` access. Add a fallback path for any field that's seen drift across the version range; soft-fail per-field rather than raise. New queries go in `graphql/client.py`; the launcher + runner consume them.
- **Only select GraphQL fields that EXIST on the target type — a nonexistent field 400s the WHOLE request.** `... on InvalidStepError { message }` broke every launch because `InvalidStepError` has only `invalidStepKey`. When editing a mutation/query, introspect the live schema first (`__type(name){ possibleTypes { name fields { name } } }`) and select only present fields. Mocked-transport unit tests can't catch this — it needs live testing or introspection. Regression: `test_launch_mutation_does_not_select_message_on_fieldless_error_types`.
- **The launch location/job come from the manifest, not a hardcoded default.** `run_side` passes `manifest.deployment.location_name` / `job_name` to `launch_representative`. The `"default"` fallback is degenerate — real deployments name their location after the user-deployment; `dagtools qual init --location-name` sets it. Regression: `test_run_side_threads_manifest_location_and_job_into_launch`.
- **No GraphQL library dependency.** httpx + raw query strings is the discipline. Tests mock httpx, not a GraphQL schema — keeps CI fast and portable.

## 4f. Equivalence-class matrix (`dag_tools.qual.classes`)
- **Read the manifest, not the registry.** Q1 (and every later Q-phase) walks `manifest.inventory_pins[]` and fetches each pinned `(repo, git_sha)` from the registry. Do **not** call `read_latest_pointer` to discover repos — that would let mid-qualification CI publishes shift the qualification target silently. The regression `test_classes_builder.py::test_q1_reads_pinned_sha_not_latest` enforces this.
- **The class key is THE contract**, not the asset key. Two assets with identical key components land in the same class; they're then treated as interchangeable for qualification purposes. Adding new key components is fine (they go in `ClassKeyComponents`) but they're effectively additive — old class hashes won't match new ones, so prefer doing this only at qual_id boundaries.
- **Custom dbt translators always force own classes.** The "is_custom_translator" signal comes from `dbt_projects.json`. When extending the dbt detection (e.g. multiple dbt projects in one repo), keep it conservative — over-segregation costs operator time, but missing a custom translator costs upgrade-day surprises.
- **Runnability is tag-driven**, not inference-driven. `synthetic_required: "true"` / `observe_only: "true"` are the contract; do not add FQN-based heuristics ("snowflake means synthetic_required") without a manifest knob to disable them — different orgs have different staging realities.

## 4e. Qualification manifest (`dag_tools.qual.qualify`)
- **One qual_id is immutable.** The manifest at `qualifications/<qual_id>/manifest.yaml` is written via `InventoryRegistry.put_qualification_manifest` which defaults to immutable. `--allow-overwrite` exists for the explicit "I really do want to redo this qualification" path; do NOT silently bypass.
- **Inventory pinning is point-in-time.** `create_qualification` reads `latest.json` for every repo once at init time and freezes those `(repo, git_sha)` pairs in `inventory_pins[]`. Later phases MUST read the manifest's pins, not call `read_latest_pointer` again — that would let mid-qualification CI publishes shift the qualification target.
- **`co_upgrade_risks` filters the Dagster family.** `compute_co_upgrade_risks` excludes anything matching `dagster*` from the diff because those are the explicit upgrade target. When extending the diff (e.g. to allowlist additional libraries), keep this filter in `dag_tools/qual/qualify/risks.py`, not scattered through callers.
- **YAML aliases match the recipe sample.** `CoUpgradeRisk` uses `from`/`to` aliases (not `from_version`/`to_version`) so the on-disk YAML matches what operators read in `docs/RECIPE.md`. Always serialize with `by_alias=True`.

## 4d. Read the Recipe before changing the qualification system
- The full spec for `dag_tools/qual/` (and the shared `dag_tools/inventory/` contract it depends on) lives in [`docs/RECIPE.md`](docs/RECIPE.md). It contains the ADRs (why the registry is separate from the gateway; why schema discipline replaces a package split; why FQN+MRO classification beats substring matching; etc.) and a table of regression tests that guard recipe invariants. Read it before changing publisher control flow, layout helpers, or schema fields.

## 4c. Survey (`dag_tools.qual.survey`)
- **Load failure means publish nothing.** `run_survey` refuses to write to the registry if any code location fails to load. This is THE recipe invariant for Phase 1 — the registry must never contain an inventory for code that doesn't load. The test `test_run_survey_refuses_to_publish_when_load_fails` enforces it; if you change publisher control flow, that test will tell you.
- **Capture every warning during load.** Use `_capture_warnings` (equivalent to `-W all`) around every `importlib` call. Warnings are part of the load-validation payload — they're how operators see Dagster deprecations and experimental APIs drifting across the fleet.
- **Soft-fail per item in introspection**, same discipline as `dag_tools.inventory.extractors`. One malformed sensor or dbt resource must never abort a whole introspection pass.
- **Schema versions live in `survey/schemas.py`** (one per artifact). Same additive-only evolution rules as `AssetRecord`.
- When adding a new artifact: define a pydantic model in `schemas.py` with its own `SCHEMA_VERSION_*` constant, add a filename constant to `registry/layout.py`, plumb it through `publisher.run_survey`'s artifact dict, and bump the schema version in any new commit that adds fields.

## 4b. Qualification Registry (`dag_tools.qual.registry`)
- **Layout is canonical**: every S3 key is constructed via helpers in `dag_tools/qual/registry/layout.py`. **Never** write a literal key string anywhere else — writers and readers must agree on the layout via the module, not by convention.
- **Immutability is enforced**: every per-build artifact and every per-qualification artifact is written via `S3Storage.put_immutable`, which refuses to overwrite (HEAD-then-PUT). The only mutable keys are `inventory/<repo>/latest.json` and the equivalent qualification pointers; those use `put_mutable`.
- **`latest.json` is written LAST**: `InventoryRegistry.publish_build` writes all per-SHA artifacts first, then updates the pointer. **Do not reorder.** This is the invariant that prevents readers from observing partial builds — keep all pointer writes at the end of their respective publish paths.
- **Machine-readable by default**: every `dagtools` CLI command emits JSON unless `--format table` is set. New sub-commands MUST follow this — operators pipe `dagtools` output into other tools.

## 4a. Inventory Contract (`dag_tools.inventory`)
- The shared `AssetRecord` schema in `dag_tools/inventory/schema.py` is consumed by **both** the runtime Domain Broker and the CI qualification survey. Cross-process compatibility is the whole point.
- **Evolution is strictly additive**: never rename or remove a field; only add `Optional[...]` fields with defaults. Bump `SCHEMA_VERSION` in the same commit. Readers use `extra="ignore"` to tolerate unknown fields from newer writers.
- For new IO manager classes, add an explicit entry to `dag_tools/inventory/classifier.py::FAMILY_REGISTRY` (FQN -> family). Do **not** rely on substring matching — it's a logged-at-WARNING last-resort fallback, never the intended path.
- For introspection that may not exist in older Dagster versions, version-gate it and **fail soft per-field** (record `None` + log WARNING). The extractor must never abort an entire `Definitions` walk because one asset is malformed — per-asset try/except is mandatory.

## 4r. Shipped SQL: the curated slice (`dag_tools.systemlink.measurements` + `.sql`)
- **The grammar stays pure.** `dag_tools/systemlink/measurements.py` imports no `dagster`, `dbt`, `dlt`, `duckdb`, `sqlalchemy` or `jinja2`. One rule table, read by the Python evaluator and by the SQL generator next door; a rule written in only one of the two is a route that silently disagrees with itself.
- **Never hand-edit the shipped `.sql`.** Change `sql.py` and regenerate with `write_models()`. Byte identity against `render_models()` is a test, *and so is cross-route agreement over duckdb* — keep both, because byte identity alone passes on a wrong generator and agreement alone passes on a stale file.
- **Ship package data under `dag_tools/dbt_project_packages/`, never `dbt_packages/`.** The latter is gitignored and hatchling honours VCS ignore files, so the package would be absent from the wheel. Regression: `test_the_shipped_package_is_on_a_path_no_vcs_ignore_rule_matches`.
- **Declare a default for no dbt variable.** The package requires four (two relations, the adapter's exact numeric type, the deployment's comparator table) and a default for any of them would either name something from below or guess a type. Unset must fail `dbt parse`.
- **Never cast possibly-non-numeric text with `cast(x as double)`.** `cast('1e999' as double)` is `inf` on duckdb while the Python route answers `None`. Guard with `x * 0 = 0`, which is true of every finite double and false of both infinities and of nan. The exact-decimal path raises instead and that is the stated limit, not something to paper over.
- **Keep the comparator vocabulary out of the library.** No comparison codes, no operator strings beyond the two words `low` and `high` (named after the curated contract's own limit columns). Match the **whole** operator, never a prefix. An operator the deployment's table omits is kept as text and counted at warning severity — never dropped, never read as a value, and never reported as a parse failure.
- **Compute a tolerance in the configured exact numeric type, not in doubles**, and keep `is_latest` terminal-only.

## 5. Dagster Component API Pattern (1.12 GA)
- **Rule**: All custom components MUST use the triple-inheritance pattern: `class MyComponent(Component, Resolvable, Model)`.
- **Imports**: `from dagster.components import Component, ComponentLoadContext` and `from dagster.components.resolved.base import Resolvable` and `from dagster.components.resolved.model import Model`.
- **No `ComponentSchema`**: Schemas are plain `pydantic.BaseModel` or declared directly on the component class as typed fields.
- **No manual `load()` overrides**: The `Resolvable` base handles YAML attribute parsing automatically.
- **`build_defs(self, context: ComponentLoadContext) -> Definitions`**: This is the only method you must implement.
- **Factory pattern for `@asset` closures**: Dagster 1.12 treats all function parameters (except `context`) as asset inputs. When creating `@asset` functions inside `build_defs()`, use a factory function to capture closure variables:
  ```python
  # WRONG: Dagster treats 'pk' and 'table' as asset inputs
  @asset(name=name)
  def my_asset(context, pk=pk_value, table=table_name): ...
  
  # CORRECT: Factory captures values via closure
  def _make_asset(_name, _pk, _table):
      @asset(name=_name)
      def my_asset(context): ...  # use _pk, _table from closure
      return my_asset
  ```
