backdated is a dbt project on DuckDB plus a small Python package that build a type 2 account dimension from effective-dated change events. When a territory change is entered weeks after it took effect, the dimension re-splits that account's history instead of recording the change from the day it was observed. An incremental build recomputes only the accounts a new batch touched, and after every batch it must equal a full refresh and a brute-force day-by-day as-of oracle. As-was and as-is revenue are tied out by dbt tests, and a restatement bridge explains every territory's difference by the accounts that moved. All data is synthetic and seeded.
A food-service distributor reassigns customer accounts between sales territories and reps several times a year, and sales operations often enters a reassignment with an effective date weeks in the past. A snapshot-style type 2 dimension records when a change was observed, not when it took effect, so the as-was commission report credits the old rep for the backdated weeks. The restated (as-is) view then stops tying to the as-was total, and every quarter-end turns into an argument about whose revenue it was.
The seeded data reproduces that. Territory T-07 is split on 2025-10-15: 40 of its accounts move to the new territory T-26, and the move is recorded 30 days late. A recorded-date snapshot credits the 30 days of invoices in between to the wrong territory; the effective-dated dimension does not.
flowchart LR
B["Change batches<br/>changes/batch_NNN.parquet<br/>(max_batch picks the visible ones)"] --> S1[stg_account_changes]
I["invoices.parquet"] --> S2[stg_invoices]
R["territories, reps"] --> S3[stg_territories / stg_reps]
S1 --> E["int_account_change_events<br/>last recorded entry per date,<br/>no-ops dropped"]
E --> D["dim_account_scd2<br/>full refresh"]
E --> DI["dim_account_scd2_incr<br/>delete+insert per touched account"]
S1 -. "accounts in the new batch" .-> DI
S1 --> N["dim_account_naive_snapshot<br/>validity from recorded_at"]
S2 --> F["fct_invoices<br/>account_sk_as_was"]
D --> F
F --> M1[mart_revenue_as_was]
F --> M2[mart_revenue_as_is]
M1 --> BR[mart_restatement_bridge]
M2 --> BR
F --> MN[mart_naive_misattribution]
N --> MN
D --> T["dbt data tests<br/>and unit tests"]
DI --> T
M1 --> T
M2 --> T
D --> O["Python oracle<br/>(brute force, per account and day)"]
DI --> O
B --> O
Every change event carries the account's full attribute set (territory, rep, segment) from its effective date.
int_account_change_eventskeeps, for each account and effective date, the last recorded entry, and drops an event that is identical to the previous effective state. It also recordslast_batch_id, the newest batch that touched the account, counted over the raw events.dim_account_scd2turns those events into versions withlead():valid_fromis inclusive,valid_tois the next effective date (exclusive), the last version ends at9999-12-31, and the surrogate key ismd5(account_id || valid_from). Anunknownmember row owns invoices dated before an account's first effective date.dim_account_scd2_incris incremental withdelete+insertonaccount_id. For each new batch it rebuilds every version of the accounts in that batch from their full event history and leaves all other accounts alone. Both dimensions share one macro for building versions, so they differ only in which accounts they rebuild.fct_invoicescarriesaccount_sk_as_was(the version valid on the invoice date) andaccount_idfor the as-is join.mart_revenue_as_wasandmart_revenue_as_isaggregate by territory, rep and month;mart_restatement_bridgeexplains the difference per territory by account.backdated simulatereleases the batches one at a time through themax_batchvariable. After each batch it checks incremental == full refresh (EXCEPTin both directions), both against the oracle, that exactly the accounts with events in that batch carry the newlast_batch_id, and that no other account's rows changed.
python3 -m venv .venv && . .venv/bin/activate
pip install -e ".[dev]"
backdated generate --out data # 600 accounts, ~30,000 invoices, 6 batches
backdated build --data data --workdir work # dbt build: models, data tests, unit tests
backdated oracle-check --data data --workdir work # day-by-day expansion vs brute-force oracle
backdated simulate --data data --workdir sim --batches 6
backdated bridge --workdir work --data data --territory T-07 --territory T-26Requirements: Python 3.11+, dbt-core 1.10.5 or later (below 2), dbt-duckdb 1.10 or later (below 2), duckdb 1.1 or later (below 3). The tested set is dbt-core 1.12.7, dbt-duckdb 1.11.1, duckdb 2.0.1 and polars 2.2.
generate --size tests writes the small configuration (150 accounts, 3 batches) that the test-suite uses. Everything dbt writes (profile, DuckDB file, logs, target directory) goes into the work directory, and dbt runs offline with telemetry off.
All numbers below come from the commands above on the seeded data (--seed 42). Amounts are dollars.
Restatement bridge for the split territories:
territory as-was as-is difference accounts moved
--------------------------------------------------------------------------
T-07 2,847,858.24 1,340,856.86 -1,507,001.38 40
T-26 1,891,452.98 3,398,454.36 1,507,001.38 40
The 1,507,001.38 is the revenue the 40 accounts earned before 2025-10-15, which truth.json records as pre_split_revenue_cents = 150700138. Across all territories the differences sum to zero. The 10 early invoices show up as an unknown territory row in the bridge.
Simulation log, one batch at a time (touched = accounts with events in the batch, re-split = touched accounts whose already-loaded history was cut differently, for example by a backdated entry):
batch touched re-split incr == full oracle mismatches others untouched
---------------------------------------------------------------------------
1 160 0 yes 0 yes
2 168 4 yes 0 yes
3 183 9 yes 0 yes
4 257 57 yes 0 yes
5 114 28 yes 0 yes
6 134 58 yes 0 yes
all 6 batches: incremental == full refresh == oracle
Batch 4 carries the late T-07 split, so its 57 re-split accounts include the 40 moved ones. The oracle check on the final state compares both dimensions with the oracle for 600 accounts over every day in range; the 220,224 account-days on which an account has a known state (days before an account's first effective date have none) show 0 mismatches, and the day-by-day expansion of each dimension contains no extra or duplicated day.
Naive snapshot versus the effective-dated dimension:
naive snapshot misattributes 744,396.92 of 37,887,044.25 (646 invoices, 132 accounts)
naive snapshot credits 197,776.22 of T-26 revenue to T-07 between 2025-10-15 and 2025-11-14 (truth: 197,776.22)
The first line counts every invoice whose territory or rep differs between the recorded-date snapshot and the effective-dated dimension. The second is the split alone, and it equals the backdated-window revenue in truth.json exactly.
- Validity comes from effective dates, not load time. A backdated entry re-cuts history that earlier loads had already attributed, so as-was numbers for past periods change when late entries arrive. That is the point (commissions follow the effective date), but it means as-was reports are not append-only; the restatement bridge exists to show exactly what moved. The grain is a calendar day, so two changes on one day collapse into the last recorded one.
- The incremental model rebuilds whole accounts. Patching individual rows would be cheaper per change, but a backdated change shifts the
valid_toof the previous version and theversion_noof every later one, and a revert or correction can erase a version. Recomputing every version of a touched account from its full event history is simple to reason about and bounded by the accounts in a batch. The cost is that an account with a long history is rewritten for one new event. The full and incremental models share a macro, so their equality test checks the account selection and the delete+insert, while the oracle (written separately in Python, no shared logic) checks the version logic itself. - Normalisation rules are explicit. A revert (A to B to A) is a real change and stays three versions; an event identical to the state already in force is dropped; for several entries on the same account and effective date the last recorded one wins, with
change_idas the tie-break.last_batch_idcounts raw events, so a dropped no-op or a superseded entry still marks the account as touched and is recomputed. - Invoices before an account exists go to an
unknownmember instead of being dropped or failing the join. As-was revenue then still ties to the invoice total; the 10 early invoices appear underunknownas-was and under the account's current territory as-is, and the bridge shows them. - Batch visibility is a variable plus a glob. The dbt-duckdb
external_locationtemplate is rendered by the adapter without access to project macros, so the source readschanges/batch_*.parquetandstg_account_changesfilters onbatch_id <= max_batch. Unseen files are still opened; at this size that costs nothing, and at larger sizes the file list would be generated by the caller instead. - The incremental watermark only moves forward.
dim_account_scd2_incrdecides what is new withbatch_id > max(last_batch_id)of its own table. Runningbuildwith a lowermax_batchafterwards does not rewind it: the incremental table keeps the newer batches while the full-refresh dimension shrinks, so the two diverge until the DuckDB file in the work directory is removed (or the model is rebuilt withdbt build --full-refresh).backdated simulatealways starts from an empty warehouse for that reason. - Unit tests sit where each rule lives. dbt unit tests mock the model's direct inputs only, so the two tests about interval cutting (a backdated change between two versions, A to B to A) are on
dim_account_scd2, and the two about normalisation (same-date correction, no-op) are onint_account_change_events, whose input is the raw staged events. The hand-built end-to-end scenarios intests/test_scenarios.pyrun all four cases through both dimensions.
pytest -q57 tests, about a minute, fully offline (DO_NOT_TRACK=1, send_anonymous_usage_stats: false, --no-version-check; dbt's profile, target and log paths are inside pytest's temporary directories). They cover:
dbt buildon the seeded data throughdbtRunner: 14 models, 61 data tests and 4 unit tests, all passing.- Day-by-day expansion of both dimensions equals the oracle (0 mismatched account-days), and the oracle itself is shown to catch a one-day boundary shift.
- Incremental equals full refresh row for row; the three custom generic tests (
no_overlapping_validity,no_gaps_in_validity,one_current_row) fail on deliberately broken dimensions. revenue_ties_out: as-was total = as-is total = invoice total to the cent; the 10 early invoices map to theunknownmember.- The bridge for
T-07andT-26lists exactly the 40 moved accounts, theT-26difference equals the truth's pre-split revenue, and all differences sum to zero. - The naive snapshot credits exactly the truth's backdated-window revenue to
T-07. - Hand-built scenarios with exact expected versions: A to B to A gives 3 versions, a same-date correction gives 1 corrected version, a no-op gives none, and a backdated B between A and C gives
A[d1,d2),B[d2,d3),C[d3,open), with invoices landing on the right side of each boundary. - Simulation on the tests configuration (3 batches) and on the full data (6 batches), and the generator's determinism and injected patterns.
warehouse/ dbt project (dbt-duckdb)
models/staging/ stg_account_changes, stg_invoices, stg_territories, stg_reps
models/intermediate/ int_account_change_events (+ unit tests)
models/marts/ dim_account_scd2, dim_account_scd2_incr, dim_account_naive_snapshot,
fct_invoices, mart_* (+ unit tests)
macros/ account_versions, unknown member, open end date
tests/generic/ no_overlapping_validity, no_gaps_in_validity, one_current_row
tests/ revenue_ties_out, bridge_explains_difference
src/backdated/
synth.py seeded generator and truth.json
dbt_run.py dbtRunner wrapper, profile and paths inside the work directory
oracle.py brute-force as-of oracle and dimension expansion
simulate.py batch-by-batch incremental simulation
bridge.py restatement bridge and naive-snapshot readers
cli.py generate, build, simulate, oracle-check, bridge
tests/ pytest suite and hand-built scenarios
.github/workflows/ci.yml
MIT. See LICENSE.
