👻 wraith-modelgen
Sovereign dbt Scaffolding for the Ghost Stack
wraith-modelgen is a dbt scaffolder. Feed it a YAML data contract (Open Data Contract Standard, ODCS) and it writes dbt models for BigQuery or DuckDB: a raw layer that passes everything through, and a staging layer that holds a stable interface for downstream models. It also writes the schema and sources yml for the tables your project produces and reads.
Source schemas change. Columns get renamed, types get tightened, and new fields appear without warning. In most analytics codebases that change lands downstream: dashboards break, models fail, and the analytics team finds out from a support ticket.
wraith-modelgen makes the data contract the change-management mechanism. The source team updates it as part of their release. wraith-modelgen regenerates the models. Downstream sees what it sees. By default the contract's declarations are the source of truth and modelgen never reads the warehouse, so it cannot tell when a source table moves away from its contract. With --introspect, BigQuery is the source of truth for the columns of BigQuery event contracts: a column the contract names but the source no longer has fails generation with the column name, and modelgen check --introspect in CI is the gate for drift between contract and warehouse.
🚀 Installation
uv tool install wraith-modelgen
BigQuery introspection needs Application Default Credentials:
gcloud auth application-default login
Everything except new runs without them. gen, run and check use contract-only introspection by default: columns come from the contract's declarations and no BigQuery connection is made, so the same contract gives the same files on every machine. Pass --introspect to query BigQuery instead. That happens only when the contract's selected server uses the BigQuery dialect and Application Default Credentials exist; a DuckDB or local contract never queries it. new stays BigQuery-only.
⚙️ Workflow
modelgen init # scaffold .modelgen.yml + dirs (once)
modelgen new my-project.landing.user_signups # draft a contract from a live table
modelgen validate contracts/user_signups.yml # offline semantic lint, all findings at once
modelgen run # regenerate every layer and mode the config names
modelgen schema contracts/marts.odcs.yaml -o models/marts # models yml for tables this project produces
modelgen sources contracts/extract.odcs.yaml -o models/staging # sources yml for tables this project reads
modelgen check --diff # CI: fail if committed models drifted
run renders all three modes. With schema_contracts and schema_output, and/or sources_contracts and sources_output, set in .modelgen.yml, it also writes the produced and extract yml and their singular tests (honouring tests_output), so run then check is a clean round trip. The separate schema and sources commands stay valid for one-off use and for --strict CI gating.
Single layers when you need them. --raw and --staging are mutually exclusive:
modelgen gen contract.yml --raw -o ./models/raw
modelgen gen contract.yml --staging -o ./models/staging
modelgen gen contract.yml --raw --dry-run # preview without writing
| Command | What it does |
|---|---|
init |
Scaffold project layout: .modelgen.yml, contracts/, models/ |
new |
Bootstrap a draft contract from a live BigQuery table, keys guessed and marked TODO |
validate |
Offline structural + semantic lint over every schema object; --strict promotes warnings to failures. A rule that's wrong for one contract can be exempted with modelgenExempt; a reason is mandatory, and exempted findings still print |
gen |
Generate one layer (--raw or --staging), or one mode's yml (--layer schema / --layer sources), from one contract |
run |
Regenerate raw and staging for every event contract under .modelgen.yml, plus the produced and extract yml and tests when their config keys are set |
schema |
Write _<contract-name>__models.yml for tables the project produces |
sources |
Write _<contract-name>__sources.yml for tables the project reads (extract contracts) |
check |
Render in memory, diff against disk, exit non-zero on drift. Writes nothing. |
Full flags and exit codes are in the CLI reference section.
⌨️ CLI reference
Every command takes --help:
modelgen --help
modelgen check --help
Exit codes
Each failure class has its own exit code, so a script can tell an invalid contract from a lint failure, drift or a missing credential. The codes and their precedence are in the Exit codes table.
What modelgen keeps stable between releases is in the Compatibility policy.
gen
Generates one layer, or one mode's yml, from one contract. Specify exactly one of --raw, --staging or --layer.
modelgen gen contracts/bus-positions.odcs.yaml --staging -o models/staging
The command prints a panel per event with its target model, then a File and Status table with written, or dry-run with --dry-run. Exit 0. With --staging, quality rules that staging does not map print on stderr as modelgen: N quality rule(s) not mapped: <model>.<rule>.
Generating the yml for produced or read tables uses --layer:
modelgen gen contracts/bus-marts.odcs.yaml --layer schema -o models/marts --dry-run
It prints one <path> dry-run line per file and exits 0.
| Flag | Meaning |
|---|---|
--raw |
Raw layer. Everything in, nothing filtered. |
--staging |
Staging layer. |
--layer schema |
Models yml for produced tables. Same output as modelgen schema. |
--layer sources |
Sources yml for extract contracts. Same output as modelgen sources. |
-o, --output DIR |
Output directory. Default ./models. |
--dry-run |
Preview without writing. |
--introspect |
Query BigQuery for the source table's columns. Off by default. Ignored under --layer. |
--from-contract |
The default: use the contract's staging declarations. Kept so existing scripts keep working. |
-t, --table NAME |
Generate only the named schema object. Repeatable. Default: every object. |
-s, --server ID |
Pick the server by its server: id. Not accepted with --layer sources. |
-v, --verbose |
Debug logging. |
--layer takes exactly schema or sources. It cannot be combined with --raw or --staging.
Gotchas:
genhas no--strict. Usemodelgen schema --strictormodelgen sources --strictfor that.--from-contractdoes nothing under--layer.
run
Reads .modelgen.yml and regenerates every contract it names: raw and staging layers for event contracts, plus the produced and extract yml and their singular tests when the schema and sources keys are set (see Configuration).
modelgen run
Flags: -c, --config FILE, -s, --server ID, --dry-run, --introspect, --from-contract, -v, --verbose. There is no --strict.
Unmapped quality rules print on stderr as modelgen: N quality rule(s) not mapped: <model>.<rule> and do not change the exit code.
Gotchas:
- A
*_contractskey without its*_outputkey is skipped with a warning naming both keys. The exit code does not change. - To fail CI on unmapped quality rules, use
modelgen schema --strictormodelgen sources --strict.
schema
Writes one _<contract-name>__models.yml for tables the project produces. Quality rules that map to dbt tests land under tests/generated/ inside the output directory. A validValues rule, in either form, becomes an accepted_values test in the yml instead.
modelgen schema contracts/bus-marts.odcs.yaml -o models/marts --strict
Exit 0 when every quality rule maps to a dbt test. Unmapped rules are reported on stderr as modelgen: N quality rule(s) not mapped: <model>.<rule>.
| Flag | Meaning |
|---|---|
-o, --output DIR |
Output directory. Default ./models. |
--dry-run |
Preview without writing. |
-t, --table NAME |
Repeatable. Unknown names exit 1. |
-s, --server ID |
Pick the server by its server: id. |
--strict |
Exit 3 when any quality rule cannot be mapped. |
A contract with no schema objects, or an unknown --table or --server, is invalid.
Gotchas:
- With
--strict, files are still written before the exit3. With--dry-run, nothing is written but the exit3still applies.
sources
Writes one _<contract-name>__sources.yml for tables the project reads (extract contracts). See the Sources layer section.
modelgen sources contracts/bus-positions-extract.odcs.yaml -o models/staging
Exit 0 on success. The flags match schema, with two differences: there is no --server, and --strict behaves the same way.
check
Renders every contract that .modelgen.yml knows about and compares the result to the files on disk. It writes nothing. Run it in CI next to the linter.
modelgen check --diff
Clean repo, last line:
Everything in sync. 12 file(s) match their contracts.
Drifted repo: a --- <path> header and a unified diff for each drifted file, then Drift detected: N file(s) out of sync, M error(s). Run modelgen run and commit the result. and exit 4. The count is illustrative. Run the command to see your own numbers.
check takes no contract path and no --layer, --table or --strict. It reads .modelgen.yml, found by walking up from the current directory, or the file named by --config.
| Flag | Meaning |
|---|---|
-c, --config FILE |
Path to .modelgen.yml. Default: discovered upward from cwd. |
--diff |
Print a unified diff for every drifted file. |
--ignore-version |
Treat a file that differs only in the modelgen version of its GENERATED header as in sync. |
--introspect |
Query BigQuery for source columns. Off by default. |
--from-contract |
The default. Kept so existing scripts keep working. |
-s, --server ID |
Pick the server by its server: id. Applies to schema and event contracts. Extract contracts ignore it. |
-v, --verbose |
Debug logging. |
By default check compares the committed files with what the contracts render, and never reads the warehouse. For BigQuery event contracts, modelgen check --introspect with Application Default Credentials is the CI gate for drift between contract and warehouse. A contract column missing from the source table fails generation with the column name (exit 1). A new source column changes the raw model's column list and shows as drift (exit 4). Without credentials it falls back to contract-only introspection and prints No GCP credentials found. Checking against contracts only. DuckDB event contracts and all produced and extract contracts are never compared with a live table. The CI steps are in modelgen check.
When no contracts match the contracts glob and no schema_contracts or sources_contracts pattern is set, check prints No contracts found. and succeeds. A schema_contracts or sources_contracts pattern that matches no files fails even when other contracts exist.
Gotcha: schema_contracts and sources_contracts are only checked when their schema_output and sources_output keys are set. Without them, matched contracts are skipped by the drift comparison and do not fail the run. check prints a warning naming both keys.
Python API
modelgen.generator exposes generate(), render_raw() and render_staging(). Each takes a contract_path argument. It is accepted for compatibility with 0.14.1, ignored, and deprecated. Passing a non-None value emits a DeprecationWarning ("contract_path is ignored and will be removed"). The generated header no longer embeds the contract path, so drop the argument.
Gotchas:
contract_pathsits betweenlayeranddry_runingenerate(). Passdry_runby keyword, or a positionalTruelands incontract_path.render_schema()inmodelgen.schema_modehas nocontract_pathparameter.
⚙️ Configuration: .modelgen.yml
Put the file at the repo root. Every path in it is relative to the directory that holds the file. run and check find it by walking up from the current directory, or take --config PATH (-c). With no file found, the defaults apply and the root is the current directory. An empty file means defaults. A file whose top level is not a mapping is a config error (exit 1). Every key takes a string. Any other value, such as contracts: false, is a config error (exit 1) that names the key and the type it got: 'contracts' must be a string, got bool. An empty string for contracts, schema_contracts or sources_contracts is a config error too. A key set to null counts as absent, so its default applies. Unknown keys are ignored with a warning that names the key and the nearest valid key, such as unknown key 'staging_ouput' is ignored; did you mean 'staging_output'?. Warnings go to stderr and, with --format json, into issues with severity: warning. They do not change the exit code.
| Key | Default | Read by | What it does |
|---|---|---|---|
contracts |
contracts/*.yml |
run, check |
Glob of event contracts. Each one yields a raw model and, when it declares staging columns, a staging model. |
raw_output |
models/raw |
run, check |
Directory for raw models. |
staging_output |
models/staging |
run, check |
Directory for staging models. |
schema_contracts |
unset | run, check |
Glob of produced contracts for tables this project builds. Rendered as modelgen schema would. |
schema_output |
unset | run, check |
Directory run writes the produced yml to and check compares against. |
sources_contracts |
unset | run, check |
Glob of extract contracts for tables this project reads. Rendered as modelgen sources would. |
sources_output |
unset | run, check |
Directory run writes the extract yml to and check compares against. |
tests_output |
unset | run, check |
Directory that replaces the leading tests of generated singular-test paths, so tests/generated/x.sql is written and compared at <tests_output>/generated/x.sql instead of under schema_output/sources_output. Pair it with --tests-output on schema/sources. Use it when the yml lives under models/ but dbt must find the tests in its tests/ directory. |
Complete example:
# .modelgen.yml at the repo root. Paths are relative to this file.
contracts: contracts/events/*.yml
raw_output: models/raw
staging_output: models/staging
schema_contracts: contracts/produced/*.odcs.yaml
schema_output: models/marts
sources_contracts: contracts/extract/*.odcs.yaml
sources_output: models/staging
Gotchas, all from the code:
runwrites the produced and extract yml and their singular tests when the*_contractsand*_outputkeys are set, sorunthencheckis a clean round trip.schema_contractsorsources_contractsset to a glob that matches nothing makesrunandcheckexit 1 and name the key.- A
schema_contractsorsources_contractsglob without its*_outputkey, or an*_outputkey without its glob, is skipped byrunandcheckwith a warning. Set both or neither. runhas no--strict. It prints unmapped quality rules on stderr and exits 0. Useschema --strictorsources --strictas a CI gate.- The default
contractsglob is*.yml. ODCS files named*.odcs.yamlneed their own glob. - Keep extract contracts out of the
contractsglob. Event contracts requiremodelgenLoadedAtFieldon each schema object.runandcheckreport its absence as aparseerror. Extract contracts do not carry that property. gen,schema,sourcesandvalidatenever read this file. Pass their paths and flags explicitly.
📄 Contract anatomy
Contracts are Open Data Contract Standard (ODCS) documents, validated against the bundled ODCS JSON schema for their apiVersion. modelgen's BigQuery/dbt specifics ride in customProperties.
version: "1.0.0"
kind: DataContract
apiVersion: v3.0.2
id: 8b1f6c2e-5a3d-4e7a-9f21-3c4d5e6f7a8b
status: active
name: user_signed_up
servers:
- server: landing # source project + dataset
type: bigquery
project: my-gcp-project
dataset: landing
schema:
- name: user_signed_up # the entity → dbt model stem
physicalName: user_signups_raw # source table
physicalType: table
customProperties:
- property: modelgenLoadedAtField # SOURCE column for incremental loads
value: RECEIVED_AT
- property: modelgenRaw
value:
dataset: raw
incrementalStrategy: merge
dedup: true # row_number() partition by primaryKey
partitionBy: { field: RECEIVED_AT, dataType: timestamp, granularity: day }
clusterBy: [USER_ID]
freshness: # -> dbt source freshness
warnAfter: { count: 12, period: hour }
errorAfter: { count: 24, period: hour }
- property: modelgenStaging
value:
dataset: staging
materialization: snapshot # ds snapshot; derives partitionBy: ds
clusterBy: [user_id]
properties:
- name: event_id # staging (consumer-facing) name
physicalName: EVENT_ID # source column name
logicalType: string
physicalType: STRING # cast target
description: "..." # >= 50 chars, and not just the name
primaryKey: true # contributes to dbt unique_key
primaryKeyPosition: 1
required: true # → not_null test
unique: true # → unique test
# accepted_values → quality: [{ type: library, rule: validValues, validValues: [...] }]
| dbt test | ODCS field |
|---|---|
not_null |
property required: true |
unique |
property unique: true |
accepted_values |
property quality with rule: validValues + validValues: [...] (property form), or type: library, metric: invalidValues, arguments.validValues and mustBe: 0 (library form). Every mode. |
Write the list once, in either form: gen --staging, modelgen schema and modelgen sources all map both forms to accepted_values, and both forms on one column yield one test. The property form is valid ODCS only under apiVersion: v3.0.2, which also needs a rule key on a library-form rule. v3.1.0 and later accept only the library form.
Staging renders accepted_values with no where, while schema and sources add where: <column> is not null on a column that is neither required nor a primary key. The difference is deliberate.
Supported ODCS versions
The top-level kind must be DataContract. The apiVersion picks the bundled JSON Schema in src/modelgen/schema/.
apiVersion |
Result |
|---|---|
v3.2.0 |
Supported. Validated against the v3.2.0 schema. |
v3.1.0 |
Supported. Validated against the v3.1.0 schema. |
v3.0.2 |
Supported. Validated against the v3.0.2 schema. This is also the default. |
v3.0.1, v3.0.0, v2.2.2, v2.2.1, v2.2.0 |
Deprecated: still accepted and validated against the v3.0.2 schema; prints a warning; will be removed in a later minor release. |
| missing, or not a string | Validated against v3.0.2, which reports the problem. |
anything else (for example v2.3.0 or v9.9.9) |
Rejected: unsupported apiVersion, followed by the list of supported versions (v3.0.2, v3.1.0, v3.2.0). |
Gotcha: modelgen new writes apiVersion: v3.0.2. Edit it if the contract should be newer.
🧭 Targets and dialects
A contract picks its dialect from the type of each servers[] entry. The dialect decides which keys locate the source and how SQL is rendered.
servers[].type |
Dialect | Where the source lives |
|---|---|---|
bigquery |
BigQuery | project and dataset keys on the server. |
duckdb |
DuckDB | First set of database, path, location, server. Schema is the schema key, default main. |
local |
DuckDB | Same keys as duckdb. With format: parquet, the location is a Parquet landing file that dbt-duckdb reads through the source's external_location meta. |
Any other type, such as custom, has no dialect. It is skipped when auto-selecting a server and rejected when named with --server.
servers:
- server: prod
type: bigquery
project: my-gcp-project
dataset: landing
- server: build-warehouse
type: duckdb
database: ./dbt/build.duckdb
schema: main
- server: extract-local
type: local
format: parquet
path: dbt/data/bus_positions_*.parquet
DuckDB limits, enforced by lint or generation:
- Models are views unless the contract says
materialization: table. Stagingincrementalpasses lint but renders as a view. - No partitions or clustering. Declaring
partitionByorclusterByis a lint error. The deriveddspartition of a snapshot is the one exception, and DuckDB never adds adscolumn. - No encryption. Classified columns are pseudonymised instead: the
modelgenSubjectFieldcolumn is staged assha256(cast(<col> as VARCHAR)), a stable hash, so joins, counts and aggregates still work; every other classified column is omitted from staging and stays in the raw layer only. A classified column in the unique key is a lint error (classified-column-omitted), since staging would not select it.
Choosing a server
--server ID (short form -s ID) matches the server: value exactly. It works on gen, schema, validate, run and check. sources has no such flag, and gen --layer sources exits 2 when given one.
- Unknown ID: error that lists the server IDs in the contract.
- Known ID with an unsupported type: error that lists the supported types.
- No
--server: the firsttype: bigqueryserver wins, even when it comes after a DuckDB one. If there is none, the first server whose type a dialect supports is used, in contract order. If there is none at all, the error lists the supported types:bigquery, duckdb, local.
Introspection is opt-in and follows the dialect. With --introspect, gen, run and check query BigQuery only when the contract's selected server uses the BigQuery dialect and Application Default Credentials exist. A DuckDB or local contract always uses contract-only introspection, even on a machine with GCP credentials, and prints no "No GCP credentials" notice. new stays BigQuery-only.
modelgen gen contracts/events/build_summary.yml --staging --from-contract -o models/staging
On success, gen prints a File and Status table of written files. The status column reads written, or dry-run with --dry-run.
📦 Sources layer
modelgen sources renders one _<contract-name>__sources.yml per extract contract. The filename uses the contract's name, not dbtSourceName. The file holds one sources: entry with loaded_at_field, freshness, a tables: list, and a column-set test (dbt_expectations.expect_table_columns_to_match_set). The consuming dbt project therefore needs the dbt_expectations package. Quality rules that map to singular tests go under tests/generated/ of the output directory, or of tests_output when that is set (see Configuration).
Read the customProperties below from the contract's top level unless the table says otherwise.
| Property | Level | Effect |
|---|---|---|
dbtSourceName |
contract | Name of the dbt source. Default: the contract name. Must be a single value, not a list. |
dbtColumnSetTest |
contract | Name of the column-set test, replacing dbt_expectations.expect_table_columns_to_match_set. For projects whose sources are bare table functions (for example DuckDB read_parquet(...)), where the dbt_expectations test errors. The macro must take the same column_list argument. Single value. |
loadedAtField |
contract | Written as loaded_at_field. Optional. Passed through as written. |
freshnessWarnAfter |
contract | freshness.warn_after. Format N minutes, N hours or N days. |
freshnessErrorAfter |
contract | freshness.error_after. Same format. |
externalLocation |
schema object | meta.external_location on that table. Wins over the contract-level value. |
externalLocation |
contract | Used for the table when the contract has exactly one object. With more objects it is a contract error, even when --table narrows the output, so set it on each object instead. |
The freshness format is one whole number, at least one space, then a unit. Accepted units are minute, minutes, hour, hours, day and days, in any case. The count must be above zero. 2 days is valid, 2days and 0 days are errors that name the property. A freshness block is written only when at least one bound is set.
Example extract contract, adapted from tests/fixtures/real_contracts/bus-positions-extract.odcs.yaml and trimmed. dbtSourceName: bods is added here so the source has a short name. The fixture omits it, and the source then takes the contract name.
apiVersion: v3.2.0
kind: DataContract
id: 7c3f9a52-1e84-4b6d-a0c7-5d2e8f419b63
name: wraith_bus_extract_positions
version: 1.0.0
status: active
servers:
- server: extract-local
type: local
format: parquet
path: dbt/data/bus_positions_*.parquet
customProperties:
- property: dbtSourceName
value: bods
- property: externalLocation
value: "read_parquet('data/bus_positions_*.parquet', union_by_name=true)"
- property: loadedAtField
value: '"timestamp"'
- property: freshnessWarnAfter
value: 2 days
- property: freshnessErrorAfter
value: 5 days
schema:
- id: bus_positions_extract_obj
name: bus_positions
physicalName: bus_positions_*.parquet
logicalType: object
physicalType: table
description: Downsampled bus positions, one row per (timestamp, bus_id, operator, line).
properties:
- id: ex_timestamp
name: timestamp
logicalType: date
physicalType: TIMESTAMP WITH TIME ZONE
required: true
description: End of the 3-minute bucket, UTC.
- id: ex_bus_id
name: bus_id
logicalType: string
physicalType: VARCHAR
required: true
description: Vehicle identifier.
Two things the example shows. The format: parquet line is the server's format key, which selects the DuckDB Parquet path. It is not the freshness format. The loadedAtField value includes its double quotes, because the code writes the string out unchanged.
modelgen sources contracts/extract/bus-positions-extract.odcs.yaml -o models/staging
Expected output, with the file name the code derives from the contract name:
models/staging/_wraith_bus_extract_positions__sources.yml written
Add --dry-run to see the same line with dry-run in place of written. Add --strict to exit 3 when a quality rule cannot be mapped to a dbt test.
🔐 Classification and erasure
A property marked classification: pii or psi is encrypted on the way
into staging and never materialised in plaintext. Same seam as
required: true → not_null: the contract says it, the generator does it,
no human in the loop.
- property: modelgenSubjectField
value: USER_ID # who the row is about
- name: user_id
physicalName: USER_ID
classification: pii # subject → DETERMINISTIC_ENCRYPT
- name: email
physicalName: EMAIL
classification: psi # payload → AEAD.ENCRYPT
The subject column is encrypted deterministically, so its ciphertext is stable per keyset and joins, row counts and aggregates all survive erasure. Everything else is randomised. Both resolve their keyset from a keystore holding one wrapped key pair per subject.
Encryption is BigQuery only. DuckDB has no AEAD, so staging there pseudonymises the subject column as a stable sha256 hash and omits every other classified column (they exist in the raw layer only). A hash is not erasure: there is no keystore to delete from, so the raw layer is where the personal data remains.
Right to erasure is one DELETE. Destroy the subject's keystore row and every ciphertext written under those keys becomes unrecoverable, across every table, without rewriting a single partition. A historical regulatory position still reconstructs in aggregate; the individual does not.
Full design, key hierarchy (CMEK vs KEK vs DEK), erasure timeline and citations: Keystore & Erasure.
🔄 Schema evolution
The outcomes below need --introspect on a BigQuery event contract. Under contract-only introspection, the default, modelgen never reads the source and reports none of these changes. A renamed or dropped column then surfaces only when dbt runs the models.
| Source change | What wraith-modelgen does | What you do |
|---|---|---|
| Adds a column | Does not appear until you regenerate (modelgen run --introspect). Invisible in staging until declared in the contract. |
Regenerate, then add to staging when consumers need it. |
| Renames a column | Validation fails: column not found in source. | Update the property's physicalName. The modelgenLoadedAtField too, if applicable. |
| Retypes a column | Existing CAST in staging absorbs it (or fails loudly at query time if values are incompatible). | Update the property's physicalType if the canonical type should change too. |
| Drops a column staging uses | Validation fails: column not found. | Either restore upstream or remove from staging contract. |
Validation runs as part of modelgen gen --staging --introspect. If it passes, the generated staging model still presents the same contract to downstream consumers.
✅ Contract standards
modelgen validate --strict is the gate. Beyond the structural checks, it
holds contracts to a few standards that only matter once more than one team
reads them:
| Standard | Rule |
|---|---|
| Every column is documented | description of at least 50 characters that says something the column name does not |
| Every source declares staleness | modelgenRaw.freshness with warnAfter / errorAfter, which becomes the dbt freshness: block |
| Every key is tested | primaryKey properties carry required and unique |
| Exceptions are written down | modelgenExempt opts out of one rule, and a reason is mandatory |
An exemption is scoped either to the whole contract or to a single column, and the two never cross:
- name: internal_note
customProperties:
- property: modelgenExempt
value:
- rule: low-quality-column-description
reason: "deprecated in TJP-00042, drops next quarter"
Exempted findings still print on every validate run, labelled exempt with
their reason, and the summary counts them. They stop blocking, they do not
stop being visible. Full rule list: Lint Rules.
🏗️ What gets generated
For --raw:
raw__event.sql: dbt incremental model with{{ source(...) }}, optional dedup window, partition and cluster config.raw__event.yml: dbt sources entry plus model definition. Columns mirror the introspected source schema.
For --staging:
stg__event.sql: dbt model reading{{ ref('raw__event') }}. Casts and renames applied.stg__event.yml: model definition with column tests from the contract.
For --layer schema and --layer sources: the yml described in the CLI reference section. Neither writes SQL.
The layouts above are for BigQuery. DuckDB models are views unless the contract says materialization: table, and they have no partitions. See the Targets and dialects section.
Staging defaults to a datestamped daily snapshot: insert_overwrite
partitioned on a generated ds column, one full copy of the dimension per
day. History is where ds = '<date>', and any date backfills in parallel
with the same SQL. The orchestrator injects it:
dbt run --select stg__event --vars '{ds: 2026-07-27}'
The grain is (key, ds), so the generated unique test is scoped to the
partition the run writes. materialization: incremental on
modelgenStaging opts back into a high-water-mark load, and then
incrementalStrategy and partitionBy are yours to declare.
On BigQuery, both layers load incrementally. Raw merges on the unique key,
staging replaces one ds partition per run. Neither rebuilds the whole table,
and no generated BigQuery model emits CREATE OR REPLACE TABLE ... AS SELECT.
Full rebuild is available as a documented exception rather than a default,
which is covered in Tooling Decisions. DuckDB
models follow materialization instead: views by default, tables when the
contract says materialization: table (see Targets and dialects).
⬆️ Upgrading from 0.14.1
Read this before you bump the modelgen pin. The first modelgen check after the upgrade fails on every committed generated file until you regenerate them.
What you will see
modelgen check reports drift on each file whose bytes changed. The final line has this shape (counts depend on your project):
Drift detected: <n> file(s) out of sync, <m> error(s). Run modelgen run and commit the result.
That advice is right once the schema and sources keys are set in .modelgen.yml: modelgen run regenerates the raw and staging layers and, with schema_contracts/schema_output and sources_contracts/sources_output set, the produced and extract yml and their singular tests too.
Why every file drifts
The generated header changed.
- 0.14.1: the header carried a
Contract: <path>line. - Now: the first line of every generated file is
-- GENERATED by modelgen <version> from <name> <ver>. Do not edit.in.sqlfiles, and# GENERATED by modelgen <version> from <name> <ver>. Do not edit.in.ymlfiles.
<name> is the contract name and <ver> is the contract version. When the contract declares no version, the <ver> part is dropped. The contract path is gone, so moving a contract no longer changes its output. The header line cannot be turned off.
The header embeds the modelgen version, and modelgen check compares bytes. Each release that changes the version string makes every committed file drift again. Run modelgen check --ignore-version in CI so an upgrade alone is not drift: it masks the version in the header line on both sides and still compares everything else byte for byte. Without the flag, plan a regeneration in every upgrade PR.
The version comes from installed package metadata. If the distribution is not installed, for example when you run from an uninstalled source checkout, the version falls back to 0.0.0. Files generated that way carry modelgen 0.0.0 and will drift against a released install. There is no override flag. Do not commit output generated from an uninstalled tree.
Regenerate
Step 1: raw and staging.
modelgen run
run uses contract-only introspection by default and builds columns from the contract's staging declarations. modelgen run --introspect queries BigQuery when the contract's selected server uses the BigQuery dialect and Application Default Credentials resolve. Use the same introspection that produced the committed files. The raw layer differs between the two because BigQuery returns every source column and the contract declares only some of them. Regenerating with the other one commits a different raw file.
Step 2: schema and sources. With the schema_* and sources_* keys set, step 1 already wrote them and you can skip this step. Without the keys, regenerate them per contract:
modelgen schema contracts/bus-marts.odcs.yaml -o models/marts
modelgen sources contracts/extract.odcs.yaml -o models/staging
Equivalent forms: modelgen gen <contract> --layer schema -o <dir> and modelgen gen <contract> --layer sources -o <dir>.
Set schema_contracts and schema_output together, and sources_contracts and sources_output together, so run writes them. See the Configuration section.
Step 3: verify.
modelgen check --diff
Clean output ends with Everything in sync. <n> file(s) match their contracts. and exits 0. Drift or missing files exit 4; contract errors exit with their own code (see Exit codes).
Upgrade notes
- Output is byte-identical for the same inputs. No timestamps, no paths. That is tested for
gen --rawandgen --stagingwith--from-contract. The BigQuery path is not covered by that test. - ODCS quality rules are mapped per mode.
schemaandsources(andgen --layer schema|sources) map them throughsrc/modelgen/quality.py:validValues, in either form, becomesaccepted_values, zeronullValuesandduplicateValuesbecomenot_nullandunique, androwCountwith a bound becomes a row-count test. Other thresholds andtype: sqlrules become singular tests undertests/generated/. Anything unmapped is reported, never dropped.gen --stagingmaps onlyvalidValues, in either form, toaccepted_values(src/modelgen/contract.py) and now reports every other rule as unmapped, where it used to drop them silently.gen --rawemits no quality tests. Review the generated tests after regeneration. - Both
validValuesforms now map toaccepted_valuesin every mode. Contracts that used the form a mode used to ignore (the library form undergen --staging, the property form underschemaandsources) now gainaccepted_valuestests, which may fail on existing data.schema --strictandsources --strictno longer exit 3 on the property form. An empty property-formvalidValues: []on event staging used to emitaccepted_valueswithvalues: []; it is now reported as unmapped. modelgen checkalso checks the schema and sources layers when their config keys are set.- Several schema objects per contract:
genwrites one model per object, in contract order. Check model names if a contract has several objects. - Pin
--serverif a contract lists several servers. Without it, the firsttype: bigqueryserver wins, then the first server of a supported type. contract_pathonrender_raw,render_stagingandgenerateis ignored and warns. Stop passing it.- Generated descriptions changed. Raw and staging SQL headers and yml descriptions now say "Raw layer" and "Staging layer", call staging a stable interface and name downstream models, in place of an organisation-specific taxonomy.
modelgen checkreports drift on every committed raw and staging file until you regenerate, andmodelgen runclears it. This ships as a patch only because the version header already makes every committed file drift on each release.
Limitations
- The version falls back to
0.0.0when the package is not installed. - Generated quality tests call
dbt_expectations.*macros. The consuming dbt project must install the dbt-expectations package.runandcheckwarn once when it is missing, but only for adbt_project.ymlat or below the directory holding.modelgen.yml, and they count any mention ofdbt_expectationsinpackages.ymlordependencies.yml, or adbt_packages/dbt_expectationsdirectory, as installed.gen,schemaandsourcesdo not check.
🧪 Developer Quality Gate
# Clone and set up
git clone https://git.thomaspeoples.com/thomaspeoples/wraith-modelgen
cd wraith-modelgen
uv run poe setup # creates .env if missing, syncs deps, installs pre-commit hooks
# The quality gate
uv run poe test # pytest (interactive)
uv run poe test-ci # pytest with coverage enforcement (≥80%)
uv run poe lint # ruff check
uv run poe format # ruff format
poe setup runs tasks.py. It writes a placeholder .env (APP_NAME=ghost-template, DEBUG=true) only when none exists, runs uv sync --all-extras, and installs pre-commit hooks only when a .git directory is present.
The test suite uses FakeIntrospector and runs without BigQuery credentials. Covers contract parsing, semantic linting, both layers, schema evolution scenarios, composite keys, REPEATED/RECORD types, determinism, drift detection, contract scaffolding, and error surfaces.
Golden files in tests/golden embed the package version as a literal. A version bump in this repo fails the golden tests until they are regenerated.
Committing
All commits go through commitizen with the Ghost Stack convention:
👻 <type>/<ticket>: <message>
uv run cz commit
📜 Sovereign Principles
- One layer per invocation. Layers have different lifecycles; conflating them makes things harder to reason about.
- The contract is the source of truth by default. Under contract-only introspection, the default, column names and types come from the contract's declarations.
--introspectmakes BigQuery the source of truth for the columns of BigQuery event contracts, andmodelgen check --introspectis the CI gate for drift between contract and warehouse. - Deterministic output. Same contract + same source schema = byte-identical files.
modelgen checkturns this into a CI gate. - Strict failure on missing columns. With
--introspect, if the contract references a column the source no longer has, generation fails with the column name. Contract-only introspection never sees the source, so it cannot fail this way. - Standards are enforced, exceptions are written down. A rule that is wrong for one contract is exempted in the contract itself, with a reason, and the exemption stays visible on every run.
- Dialects are explicit. BigQuery and DuckDB ship in the box. A contract names its warehouse through
servers[].type, and a new warehouse is a new dialect behindget_dialect.
Part of the Ghost Stack. Sovereign. Self-hosted. No nonsense.
Metadata
Release files for wraith-modelgen 0.20.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| wraith_modelgen-0.20.0.tar.gz | 1.4 MB | Without provenance | Details for wraith_modelgen-0.20.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| wraith_modelgen-0.20.0-py3-none-any.whl | Python 3 | none | any | Details for wraith_modelgen-0.20.0-py3-none-any.whl |
Total release size: 1.5 MB
Release files / wraith_modelgen-0.20.0.tar.gz
| Download URL | wraith_modelgen-0.20.0.tar.gz |
|---|---|
| Size | 1.4 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
5b389fead9021d7513400c935c373ec7e2da9cf3d67a86e4746031ed1973ac2a
|
|
BLAKE2b-256 checksum How to use checksums |
7549c484ce4896d09ae5ad5f08969659f9279affa34503ee3d6e132e42f6a818
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.10.12 {"installer":{"name":"uv","version":"0.10.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / wraith_modelgen-0.20.0-py3-none-any.whl
| Download URL | wraith_modelgen-0.20.0-py3-none-any.whl |
|---|---|
| Size | 117.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
d0df2a7468d59b8c432e937d0ada0c90be608dae56d09d6c4e63c4a4d6701932
|
|
BLAKE2b-256 checksum How to use checksums |
8313a11ec9187addc92135bec3a1724ec8c575fed8d6737046de5c13f184467a
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.10.12 {"installer":{"name":"uv","version":"0.10.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for wraith-modelgen 0.20.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.