Load with COPY into the raw layer, and write the core by whole days of an account
Superseded in part by ADR-0046: "in on-run-start" and "the newest for each account" of "Pinning", as a task before the tasks of dbt now pins and L1 takes the newest load for each account and day, and "a table that a cleanup has emptied gets a TRUNCATE", which now comes under a lock. The rest of this record stays accepted.
Superseded in part by ADR-0051: the sentence of the light DAG with its own table in L0 and the pool of one slot for dbt of "The current day", as the short cycle is a load of the kind intraday that the one transform takes like any load, and, with its bullet "The day before, after midnight", "only the current day of an account" of the same item. The rest of this record stays accepted.
Context and Problem Statement
ADR-0004 merges rows on natural keys into raw tables that stay for good, and calls data final up to yesterday. In the code, the keys are not set, so a delete of a window walks a table by a chain of OR; the load goes by INSERT ... VALUES, whose backends the kernel killed 29 times in one morning of October 2026 on a test stack, under the limit of 384 MiB of warehouse-db, until files of 5,000 rows and two workers stopped it; and nothing connects a load to the run of dbt that reads it.
ADR-0035 makes the raw layer temporary and the core permanent, and dbt-postgres has no partitions: --full-refresh recreates a table without them. The maintainer asked for incremental work from the first day, and for data with a daily grain to reach today.
How does a load enter the raw layer, how does a run of dbt take it without a race, who creates the tables of the core, how does a window behave after a stop, and how does the first load go?
Decision Drivers
- A failure at any moment leaves the data correct, with no manual repair.
- A load that runs during a transform does not change what the transform reads, and a partial day cannot replace a whole one.
- A stop of any length closes by itself.
- Each day of a window is replaced whole: a row that the platform dropped from its report does not stay.
- A new deployment shows a dashboard in minutes, and the first history stays inside the daily quota of a platform.
- A standard incremental strategy of dbt, with no custom materialization, as long as one is enough.
Considered Options
For the format:
csv, which dlt loads throughCOPYinsert_values, as today
For the write into L0:
append, each load under its_dlt_load_id, and a transform that pins the finished loadsreplace, with a lock between the load and the transformmergeon keys
For the tables of the core:
- SQL migrations with a table of versions, and dbt writing into them with
full_refresh: false - A custom materialization of dbt with partitions
- dbt-timescaledb and another image of PostgreSQL
For the write into a fact:
delete+insertby account and day, withincremental_predicatesand a pre-hookmergemicrobatch
For the first load:
- The usual window first, and the history later, in the background, by quarters from new to old
- All the history in one pass, as today
For the current day:
- A short cycle at the level of campaigns, with a flag on the row
- Nothing before the daily load
- A second table of today's data
Decision Outcome
Chosen options: "csv", "append", "SQL migrations", "delete+insert by account and day", "The usual window first" and "A short cycle at the level of campaigns", because append removes the race by construction rather than by a lock, migrations cost no dependency and no custom code, and the standard delete+insert does what a whole day needs once a pre-hook covers its one gap. The writes into L0 and into a fact were run on real dlt and dbt; what was not run is listed under More Information.
In practice this means:
- Into L0.
loader_file_format = csv:COPY ... FROM STDIN. An empty string becomes NULL, and L1 allows for it. The normalizer stays, so the contract of the schema works.write_disposition = append: each load lies under its_dlt_load_id, with no keys and noscd2.staging-optimizedis not allowed, as DROP and a new table would take the dependent objects with them.schema_contract = {"tables": "evolve", "columns": "evolve", "data_type": "freeze"}on each source: a new field reaches L0 and a report, and a change of type stops the load until the connector is updated.loaderneeds no rightTEMPORARY, and a table that a cleanup has emptied gets aTRUNCATE.- Money in L0 is text or whole micros, never
decimal: the type of dlt isnumeric(38,9), which silently loses the tenth place, so a check of six places would not see it. L1 casts tonumeric(18,6). - The answers of an API are read as a stream into files, not by
response.json()over a whole month. - Sources load their entities as full lists of the account, in the same load.
- The working folder of dlt stays temporary. A repeat extracts the window anew, and L1 does not see the rows of an unfinished load, which the cleanup removes after a day.
- Pinning. A run of the transform pins the finished loads in
on-run-start, and until its end L1 sees only those, the newest for each account. A load that runs at the same time lies beside them under its own_dlt_load_id. A whole load is_dlt_loadswithstatus = 0, with one_dlt_load_idacross the tables of a source. - The tables of the core. Numbered SQL files, applied once by
db-initand tracked incore.schema_migrations, create all the tables of the core, dimensions and registries too, with their descriptions:persist_docsneeds ownership, so it is off oncore. dbt only writes into them, withfull_refresh: false, and a singular test checks that each fact hasrelkind = 'p'. Snapshots of versions and aggregates stay models of dbt. The views can then be built at./agoranomos upbefore the first load, as all that they read exists. - Into a fact. The standard
delete+insertwithunique_key = ['account_sk', 'report_date'],full_refresh: falseandon_schema_change: fail. The key need not be unique, so a whole day of an account is deleted.incremental_predicateswith the lower bound of the window is required, to keep the delete inside the partitions of the window. A pre-hook, in the same transaction, copies the changed rows to the journal and deletes the days of the window for which the platform returned nothing, skipping accounts in quarantine, as the standard strategy leaves those days alone. A model casts to the exact types of the table. - Into a dimension. Incremental
mergemodels withfull_refresh: falseandmerge_exclude_columnson the surrogate. A registry takes its key ascoalesce(existing key, nextval(...)), because dbt writes every column of a table, which rules outgenerated always as identity. An account in quarantine does not enter a dimension: a cast tochar(3)cuts a value silently, so the check comes first. - Tests. Contracts of dbt on the models of L1 and on the views. On the tables of the core the constraints are in the migrations, and dbt tests them by the window of the load, with a
wherethat prunes partitions, and not over the whole table: at 48 million rows each test would otherwise be a full pass. A tagcriticalmarks the tests that block. - The window. For a daily load of an account,
[min(yesterday + 1 − W, last accepted day + 1), yesterday], whereWis the window of restatements of the platform: 90 days for Google and Microsoft, 28 for Meta, 14 for GA4, 7 for TikTok, VK and Yandex, and 30 for LinkedIn. The second term widens the window after a stop to the last accepted day, fromcore.loads, with the watermark inasset_state_storeof Airflow 3.3 as a cache. To save quota, as Fivetran does, each run may take a short window of 3 days, and the full window comes once a day. A full rebuild of the core is never needed: each day of a window is replaced whole, so nothing can drift. - The first load. The usual window of the platform first, so that a dashboard fills in minutes. History follows in the background, in portions from new quarters to old ones, one quarter across all the new accounts of a source, each going from L0 to L2 whole.
core.ensure_partitionruns before a portion, as there is no DEFAULT partition. A parameterized run of the DAG of a load takes an account, a start and an end, as asset-triggered runs have nological_dateand backfills of Airflow need a schedule by time. - The current day. The daily cycle ends yesterday, as it does today. A short cycle takes only the level of campaigns, only the current day of an account, and only cost, clicks and impressions, every 3 hours by default. A setting in
.envchanges or turns it off; less than an hour makes no sense, as that is how often Google updates. Conversions of the current day are not shown as a result: Google dates them by click and adds them later.is_partial_dayis a column of the fact of campaigns. The short cycle writes it, and the daily cycle replaces the row and clears it. It cannot be computed from a time zone: after midnight in the account, yesterday with data up to 21:00 would look closed until the daily load.- The watermark counts daily loads only. Weeks, months, comparisons of periods, the journal of restatements, anomalies and the test of missing days take closed days only.
- A separate light DAG has its own table in L0 and runs
dbt build --select tag:intraday. Both cycles write one fact, so both go through an Airflow pool of one slot, where they queue and do not collide. - A dashboard gets a card "Today, as of the load", with its time, and the default period of the others ends yesterday.
The other options were not chosen for these reasons:
insert_valuestook 27 s and 28 MiB in the largest process of PostgreSQL for 1 million rows, against 22 s and 10 MiB. The first reason to move is not memory, as today's limits hold it, but that those limits on files and workers stop being needed.replacewith a lock would hold the lock for the whole load, or split a task into extract and write.replacewithout one truncates a table thatdbt buildis reading, and DAGs of a load and of a transform are different, somax_active_runsdoes not keep them apart.mergeon keys needs the keys, and it does not remove a row that the platform dropped.- A custom materialization is more code for what a migration does; it stays the fallback if migrations prove tight. dbt-timescaledb needs another image of PostgreSQL and a license to review.
mergein a fact andmicrobatchdo not delete vanished rows:microbatchon PostgreSQL is a MERGE byunique_key.- All the history in one pass keeps a person waiting and costs quota. By months it would take about 220 operations of Google Ads for each account with modules, 44,000 for 200 accounts and three daily quotas of Basic. By quarters and the basic set it takes 52 and 10,400, less than one.
- Nothing before the daily load does not meet the requirement. A second table would mean two facts to explain, for what one flag says.
Consequences
- Good, because the design leaves no race between a load and a transform, with no lock to wait on, once its check below has passed.
- Good, because a stop of any length closes by itself, and no operator has to choose a window.
- Good, because a day cannot keep rows that the platform removed.
- Good, because a person sees a dashboard minutes after connecting an account.
- Good, because the tables of the core do not depend on dbt, and a view can rely on them from the first
up. - Bad, because L1 filters by load, and a cleanup deletes rows instead of a simple overwrite.
- Bad, because a change of a table of the core needs a migration and a model in step.
- Bad, because the discipline "the core is never rebuilt by dbt" rests on
full_refresh: falseand on the rights of ADR-0035. - Bad, because the history of a new deployment takes hours, in the background, and the report of an old period stays empty until it arrives.
- Bad, because the numbers of today are approximate, and the reporting amount of today almost always uses a carried rate.
More Information
- Implementation status, as of November 2026: the part for v0.4.x, without a break, is in place: the reading of the answers of Google Ads as a stream into files, an error of an account that does not stop the load,
csvof dlt, a transform that starts on any asset,include_in_conversions_metricas the default primary for Google, and the tagcritical. For v0.5, the load into L0 is in place: every source appends the facts of each load under its own_dlt_load_id, with no keys, and the journal_agoranomos_loadsof each account and window in the same run, under the contract of the schema with the types frozen and with no index on_dlt_id, a task before the tasks of dbt pins the whole loads, those of_dlt_loadswithstatus = 0, intocore.loads, and L1 reads, for each account and day, the newest pinned load that covers the day (ADR-0046), asdbt/macros/pin_loads.sqlanddbt/macros/newest_load.sqldo. The entities append too: each load writes the full list of each account that it took, and L1 reads, for each account, the list of its newest pinned load (newest_list), so that an account whose load failed keeps the list before; no table goes through a staging schema, and the schemasraw_<source>_stagingstay, empty, aspostgres/warehouse.sqlstill creates them. "Into a dimension" is in place: incrementalmergemodels withfull_refresh: falsewrite the dimensions and the registries into the tables of the migrations, a registry withmerge_exclude_columnson its surrogate and its key ascoalesce(existing key, nextval(...)), and an account that is to stay out of the core is left out of the one view that every dimension takes its accounts from,int_accounts__current, which leaves out the accounts that the checks of G1 and G1a put in quarantine (ADR-0035,dbt/models/core/,dbt/macros/quarantine.sql). "Into a fact" is in place: the standarddelete+insertwithunique_key = ['account_sk', 'report_date'],full_refresh: falseandon_schema_change: failwrites the five facts of the core from the days of the pinned windows,staging.int_window_days, with the lower bound of the windows as a subquery oncore.loadsinincremental_predicates, and pre-hooks in the transaction of the model, with no hookbefore_begin, that write the journal of restatements and delete the empty days, skipping the accounts in quarantine; each model casts to the exact types of its table, and the tests by window carry awherewith the same subquery (dbt/models/core/core_*.sql,dbt/macros/facts.sql). The models write into the partitions that the task of the pin creates, and a stack test checks that a changed day reaches the fact and the journal, and that a statement of the write that fails leaves both as they were (tests/stack/test_core_facts.py). The acceptance and the cleanup of L0 are in place for v0.5 too (ADR-0046): once a run has accepted its loads, their days leavestaging.int_window_days, so the next run writes the days of the loads pinned since, and not every pinned day again. For v0.6, the short cycle of ADR-0051: the core takes a load of the kindintradayand writes its day intocore.ad_stats_campaign_dailywithis_partial_day(migration 0009), a whole load takes a day before an intraday one, and the journal of restatements, G1a and the lists of the entities leave intraday loads out; the view of campaigns carries the column, and the dashboard Advertising has the card Today, as of the load, over the partial rows, while its other cards and the metrics take whole days; the DAG of the short cycle of Google Ads,agoranomos_google_ads_intraday, loads the current day everyAGORANOMOS_INTRADAY_HOURShours in the poolgoogle_ads_loadof one slot with the daily load, and the readers of the watermarks in the code of the loads leave intraday loads out; and the DAG of the short cycle of the demo,agoranomos_demo_intraday, loads the current day ofdemo_searchin the pooldemo_loadof the loads of the demo, which a stack test runs whole, from the load to its replacement by the daily load; a run of the transform that reads only a load of the short cycle took 429 s on the demo and 427 s on the core of the agency profile in CI on 19 November 2026 (System requirements). The window of the connector of Google Ads is in place:[min(yesterday + 1 − 90, last accepted day + 1), yesterday], with the last accepted day of each account fromcore.loads, whichloaderreads, and, while the core has accepted no load of the account, as before the first run of the transform that read one, the last day of its newest whole load in its journal (ADR-0032); each load keeps the last day of the window of each account inasset_state_storeof Airflow 3.3.2, as a cache that the window never follows, since after a restore of the warehouse alone it would be newer than the data, and its log says when the two differ (airflow/dags/agoranomos_pipelines/google_ads.py). Its DAG retries withretry_exponential_backoffand ends a run within itsdagrun_timeoutof seven hours. "The first load" is in place for Google Ads: the first load of an account takes its usual window, and the DAGagoranomos_google_ads_history, which runs on an asset that the tasktransformedof each run of the transform that succeeded updates, starts one portion at a time, the newest calendar quarter that some account lacks back to the first day of the month 36 months before yesterday, for every account that lacks days of it, as a parameterized run of the DAG of the load with the accounts, a start and an end, which takes the lists of its accounts, as every load does, and the totals and the facts of those days;core.loadsrecords the kindwindoworhistoryof each load (migration 0008), the pin creates the partitions of the months of a portion, the hook of each fact lifts the freeze in the transaction of its write when the portion comes again, and the viewops.ops_historyof the Ops collection shows the progress (airflow/dags/agoranomos_google_ads_history.py,airflow/dags/agoranomos_pipelines/google_ads.py). An account that the newest load of its history failed for is set aside, so that it holds up no other account of its source, and comes again once the others hold their history and its usual window has loaded since (airflow/dags/agoranomos_pipelines/history.py). The hook lifts the freeze for a write of any kind that replaces a row of a frozen month. The demo keeps its history of 18 months in its first load, of the kindhistory. The windowsWof the platforms are in one place since November 2026, the columnrestatement_window_daysof the seed of the platforms of the base package,dbt/seeds/seed_ad_platforms.csv, whichmarts.ad_platformsshows and which the connectors of Google Ads and Meta, the sources of the rates and the demo read when a load runs (airflow/dags/agoranomos_pipelines/windows.py), with the values of this record: 90 days for Google Ads, 28 for Meta, and 14 for the rates, while the demo keeps its own; a deployment has no setting for them, and no window follows the lookback of the conversion actions of an account. A unit test holds each window to 90 days at most, as the freeze of the triggers stays at 92 days in migration 0005. - The facts behind this record:
- Run on 31 October 2026 with PostgreSQL 18.6, dbt-core 1.12.6, dbt-postgres 1.11.0 and dlt 1.31.0, on a small project with a partitioned fact from a migration and
transformerwithout ownership:- The standard
delete+insertwith a pre-hook put changed and vanished rows in the journal, deleted an empty day and left the neighboring account alone. - A delete of a window of 168 thousand rows, in a table of 2.18 million rows and 24 partitions, took 246 to 252 ms over 24 partitions, and 61 to 70 ms over 13 with
incremental_predicates. csvkept quotes, line breaks and Cyrillic, a new column arrived, and a change of type stopped at normalization with the table untouched.- A type in a model that is wider than that of the table makes dbt run
alter table ... drop column ... cascade, which only the lack of a right stopped.
- The standard
- Run on 1 November 2026 with the same versions on a throwaway stand: dlt with
appendandcsv, a fact from a migration, a table of pinning that L1 reads, and a load of the same account in the middle of adbt build:- Pinning holds within one invocation of dbt, with no lock. A load that ended before the write of the fact, and another that ended during its open transaction, waited for nothing; L1 went on showing the pinned load, the fact, the dimension and a snapshot over the view of L1 equaled that load, and the next run took the newest one. Without pinning, the same run wrote the fact from the new load and the dimension from the old one, so the stand does see the race.
- A load that was unfinished at the pin stayed out of L1. A dlt killed with
kill -9, and a COPY that failed, left committed rows with no row in_dlt_loads: L1 did not see them, and a cleanup by the age of_dlt_load_idremoved them. A repeat of the cleanup of accepted rows deleted nothing and left newer loads alone. A failed run kept its pins, and the next run wrote the same days. on-run-startruns in everydbt build,dbt runanddbt test, so a pin in it lasts one invocation, not one run of a DAG. With one task of dbt for each node (ADR-0028), or with adbt testby hand during a run, a load that ended in between reached the fact and not the dimension. A pin in one step before the tasks of dbt held in the same test.- The newest load must be chosen for each account and day, not for each account: after a failed run, a short window of a newer load dropped the days that only the older load held, and a cleanup then removed them from L0. Among the loads to compare, accepted ones count too: an older load that ended after a newer one was accepted otherwise replaced its days.
- Acceptance must be marked before the rows are deleted. With the order reversed, a failure between the two left a pinned load with no rows, and the next run read its window as empty days and deleted them from the core, unless G1a stopped it. Acceptance must also take only what the run pinned: a load pinned between the end of a run and its acceptance was marked with no run having read it, and the cleanup deleted its rows.
- A
TRUNCATEafter a separate check for an empty table lost committed rows of a load in progress, which still ended withstatus = 0and wrote a partial day to the core with a green run.LOCK TABLE, the check andTRUNCATEin one transaction left the load whole. - A test on a raw table reads past the pin: rows of a killed load failed a
not_nullon the source and stopped the run. - "No lock to wait on" holds for rows, not for a new column:
ALTER TABLEwaits for the open transaction of a model that read the table, and readers queue behind it. Past thelock_timeoutof one minute the load failed and a repeat passed, with the core untouched.
- Measured with hand-written queries, not with dbt, at the density of the limit under a limit of 4 GiB: a window of 28 days, 2.24 million rows, took 21 + 48 s under the load of eight clients, and a window of today at the level of campaigns, 6,000 rows, took 0.2 + 0.07 s.
- Run on 1 and 3 November 2026 with real dbt at the density of the limit, as ADR-0036 describes, in one invocation of dbt that pinned in
on-run-start, withcore.loadsof the brief of B4:- The standard
delete+insertwith the pre-hook replaced whole days in every run: the sums of L1 and the core matched by account and day over the window, and the rows outside the window kept their number and sums. A window of 90 days took 221 to 252 s ofdbt buildunder eight readers on 4 months, and 402 to 736 s on 24 monthly partitions; ADR-0040 has the memory. - dbt renders
incremental_predicatesand thewhereof a test when it parses the project, with no database, and the parser of tests refuses a macro of the project in awhere. A subquery oncore.loadsin the text of the condition works: PostgreSQL prunes the partitions when the statement runs, and the delete took as long as with a constant date. On 24 partitions the delete of a window of 90 days in the fact of ads read 68 to 153 thousand blocks with the predicate and 987 thousand without it. - With the days of the pin in a view over
core.loads, as L1 of the check above had them, the planner counted one row for the join of a raw table with its days and chose nested loops: the journal of the fact of campaigns, 168 thousand rows, did not finish in 10 minutes, nor in 300 s after anANALYZEofcore.loads. The same query took 0.4 s with the days in a table built withANALYZEearly in the run, or withenable_nestloopoff, and 3 to 5 s for the fact of ads. - A hook
before_beginbreaks the transaction of the model in dbt-postgres 1.11: dbt sendscommitbefore the hook, and the pre-hooks and thedelete+insertthat follow then commit one by one. With a post-hook that failed, the run was red, yet the journal kept 4,208 rows and the fact had lost its empty days and taken the new values. Without the hook, or with a hook that ends with its owncommit, the same failure left the journal empty and the fact unchanged. - A delete of the empty days by
not existsover the rows of the load hashed all of them: 107 s on a window of 90 days, and the run took 308 s instead of 221 to 252 s. Finding the empty days first, from the days of the pin and the distinct accounts and days of the load, took 6 to 9 s. - A window of 90 days wrote 9.3 to 12.0 GiB of WAL, of which 1.3 to 3.4 GiB came from tests and temporary tables that only read: the image starts the cluster with data checksums, so the first read of a page after a write logs it. It wrote 8.1 to 9.1 GiB of temporary files, up to 2.6 GiB at once, and left about 1.3 GB of free space in the partitions of the window until the next run.
- The standard
- Read in October 2026:
- The freshness of today: Google has an SLO of 1 hour for clicks, impressions and cost (help), Meta refreshes insights every 15 minutes (best practices), and Microsoft takes up to 2 hours for clicks and 3 for conversions (reports).
- dlt: merge loading, full loading, schema contracts, destination tables.
- dbt: incremental strategy, Postgres configs, #168, closed as wontfix.
- Run on 31 October 2026 with PostgreSQL 18.6, dbt-core 1.12.6, dbt-postgres 1.11.0 and dlt 1.31.0, on a small project with a partitioned fact from a migration and
- Not checked yet, and to be checked before or with the code:
- Pinning in the watcher mode through Airflow: the check above ran dbt by hand. One
dbt buildis one invocation, so the result should carry over. - The initial windows, which come from documentation:
ops.restatementstells within a month. - A real account of Google Ads: no load has reached one yet.
- The quotas of Meta and TikTok for a short cycle, which depend on the level of access, and those of Microsoft, LinkedIn, Yandex and VK.
- Freshness of today on Yandex and VK.
- Pinning in the watcher mode through Airflow: the check above ran dbt by hand. One
- Open at review: SQL migrations are a recommendation of the research, confirmed by a run, with a custom materialization as the fallback.
- Related decisions: at acceptance this record replaces the sentences "Data is final up to yesterday" and "Rows are merged on natural keys" of ADR-0004, whose window, retries and loud failures stay, and the failure of a whole run on one account and the schema
raw_google_ads_stagingof ADR-0032, asappendneeds no such schema, and the first load of "History" of ADR-0034, all 36 months in one pass, whose depth of 36 months stays. The orchestration is in ADR-0039, and the change of the core between releases in ADR-0044. - Revisit this record when migrations prove too tight, or when dbt-postgres gains partitions.