# Orchestrated two-way pipelines round: design

Written and committed before any break was run and before any outcome was computed. The frozen protocol is
evals/orchestrated-protocol.json; it pins the hash of this file, of the code, of the lock file, of my declared breaks and
of the bundle the independent author receives. No model is called anywhere in this round, and nothing costs money.

## Where this round lives (the overlap test)

Two published families were candidates.

- The outbound syncs round of this study (outbound-sync.html, DESIGN-outbound.md) already measures the write-back half:
  a warehouse pushing computed fields into a CRM-style store, change-only syncs against a ledger, read-back and
  reconciliation, idempotency keys, late and duplicated writes. It has no orchestrator, no inbound pipeline, no dbt
  models, no asset checks, no freshness policies and no declared break schedule.
- Event contracts (portfolio/event-contracts) asks which check stops which break, and how many days of wrong numbers
  follow, with breaks written blind from a change grammar. Its data are a product's analytics events and its damage is a
  wrong dashboard metric; its checks sit before and after a release.

This round's data are CRM, billing and product records, and its damage is a wrong action taken in an operational tool
(an email or a task fired on a value the sync wrote). That is the outbound round's data and failure surface; the method
borrowed from event contracts (a fault grammar and an independent author) is a method, not a question family. So the
round is the next part of this study, beside outbound-sync, and reuses its conventions: a fake CRM built from documented
behaviour categories, change-only writes against a ledger, idempotency keys per request, results per seed never pooled
across designs or breaks. Every earlier round's files stay byte-identical.

## Question

A subscription business lands its CRM, billing system and product database in a warehouse every hour, models them in dbt,
and writes two computed fields back into the CRM, where automations act on them. When one of six common breaks hits
this loop (a late billing load, a duplicated webhook, a CRM field renamed, a timezone shift, a partial sync that
half-applies, a backfill that re-sends old values), how many wrong values reach the CRM, how many accounts get an action
they should not have, how many simulated hours pass before a check stops the sync, and what does each guard cost in
stops on clean runs? The same questions are asked of breaks an independent author writes without seeing the guards.

## The orchestrator: Dagster

Dagster, not Airflow. The round needs checks attached to the data they test, freshness policies declared on the data,
and a run that stops the steps downstream of a failed check. Dagster models these directly: assets, asset checks with a
blocking flag, freshness policies on asset specs, hourly partitions, and dbt tests mapped to asset checks by dagster-dbt.
In Airflow the same design needs sensors, custom operators and a separate data-quality tool wired in by hand. Dagster also
renders its asset graph from code, which is what the page shows. Airflow remains the more common scheduler; nothing here
measures one tool against the other.

Everything runs in process: no daemon, no web server. A simulated-clock driver (orchestrated/run.py) evaluates the job's
hourly schedule at each simulated tick and executes the run it requests; every asset reads its hour from the partition
key, never from the wall clock. Dagster evaluates declared freshness policies against wall-clock time in its daemon, so
the freshness check evaluates each declared policy's window against the simulated clock instead.

## The business (orchestrated/world.py, explicitly synthetic, from a seed)

A company sells booking software to service businesses (studios, clinics, repair shops) on monthly subscriptions. 2,400
customer accounts and 300 prospects. It stands in for any vertical software company whose CRM, billing and product
systems describe the same customers; no company's data or schema is used.

- CRM: accounts (name, lifecycle stage, owner, segment, the billing customer id), 1 to 3 contacts each, 0 to 2 open
  opportunities per customer. People edit 0.3% of accounts an hour (owner or name), contacts and opportunities less.
- Billing: one customer and one subscription per customer account (starter, growth or pro, US$49, US$99 or US$149 a
  location a month), a monthly invoice on each subscription's anniversary, paid by card a few minutes after it is issued.
  The first attempt succeeds 90% of the time; a failed charge is retried a day later (60%) and two days after that (50%);
  three failures cancel the subscription. 0.2% of subscriptions cancel each day; 2% of paid invoices get a refund within
  ten days. Payment and refund outcomes arrive by webhook within two minutes.
- Product: 1 to 5 locations per customer (70% have one), 2 to 6 staff each, and bookings: about 7 a location a day
  (lognormal across locations), open 08:00 to 20:00 local time (UTC-7) Monday to Saturday; 90% completed, 4% no-shows,
  6% canceled. 15% of accounts decline over ten days to between 10% and 50% of their usual bookings, 5% grow by 30%.
- History: 35 days before hour 0, so every 28-day window is full. The run window is hours 0 to 59.

Benign noise shared by every run of a seed, broken or clean (drawn from its own stream):
- extract outages: each source has a 0.4% chance an hour of an outage of 1, 2, 3 or 4 hours (its extracts do not run);
- unrelated custom fields: each source has a 0.15% chance an hour that an administrator adds a column to one table;
- webhook redelivery: 1% of payment and refund webhooks arrive a second time with the same event id.

All rates are assumptions, not measurements of any business.

## The warehouse and the models

DuckDB, one file per run. The loader (orchestrated/sources.py) lands each source table append-only every hour with
`_loaded_at` and `_batch`, adds a column it has not seen (older rows hold NULL there) and never removes one, the way
managed extract tools document their behaviour.

dbt (dbt-duckdb), orchestrated/dbt_project:
- staging, one model per source table: the latest version of each record (payment and refund events deduplicated by
  event id; bookings merged incrementally);
- int_account_billing: per CRM customer account, the linked subscription, invoices past due and failed payments in the
  last 30 days, and billing_status: no_billing_record (no linked customer or subscription), canceled, past_due (an invoice
  due more than an hour ago with no successful payment, within 30 days), else current;
- int_account_usage: completed bookings in the last 7 days and in the 21 days before;
- mart_account_scores: health_score = round(100 x (0.7 x usage ratio + 0.3 x payment score)), where the usage ratio is
  the last 7 days' completed bookings over the weekly mean of the 21 days before (capped at 1) and the payment score is 1
  with no failed payment in 30 days, 0.5 with one, 0 with two or more;
- mart_account_sync_hourly: one row per account and hour (incremental), what the sync sends, kept so any hour can be re-sent;
- mart_account_pipeline: open opportunities and opted-in billing contacts per account (modelled, not written back).

On Snowflake the models would change little (dbt-snowflake; `qualify` works; interval arithmetic would use dateadd).
What would differ: the loader would be a managed extract tool or Snowpipe; timestamps need an explicit type choice
(TIMESTAMP_NTZ against TIMESTAMP_TZ), which is where the timezone break lives; each hourly run spends warehouse credits,
so a team would weigh hourly against less frequent runs; DuckDB is single-writer, so this round runs one run per file.

## The sync (orchestrated/sync.py)

Two fields go back to the CRM: health_score and billing_status. The sync follows the outbound round's convention: it
sends only rows whose values differ from what it last confirmed writing (a ledger in the warehouse), in requests of 200
rows with an idempotency key that hashes the rows and their as-of time, so a retried or repeated run applies nothing
twice. A row error is not recorded in the ledger, so the row is planned again next hour.

## The CRM and what "acted on" means (orchestrated/crm.py)

A fake built from behaviour categories CRM products document: bulk update with a result per row, idempotency keys,
read by id, field history. The two synced fields are integration-owned: people cannot edit them unless a break says so.
Three automations run on every applied change; a field's first value fires nothing:

- at_risk_task: health_score moves from 50 or more to under 50 (a task for the account owner to call the customer);
- collections_email: billing_status moves to past_due;
- win_back_email: billing_status moves to canceled or no_billing_record from current or past_due.

**An account is acted on when one of these automations fires for it.** It is wrongly acted on when the automation fired
while the true value at that hour (below) was not in the state that fires it: true health_score 50 or more for an
at_risk_task, true billing_status other than past_due for a collections_email, true billing_status other than canceled
or no_billing_record for a win_back_email.

## The Dagster job (orchestrated/definitions.py)

Assets, every one partitioned by the hour: ops/sim_clock; one landing step per source materialising raw/<source>/<table>
(11 tables), each with a declared freshness policy (fail window 3 hours); the dbt models as one dagster-dbt multi-asset;
sync/plan (rows whose values differ from the ledger); sync/crm_sync (the writes). One job runs them all; an hourly
schedule built from the partitioned job requests each hour's run at the end of the hour. A second job runs only the two
sync assets, for a backfill.

## Guards (orchestrated/guards.py, the dbt tests, and the sync)

Every guard below is an asset check except the last.

1. **Freshness policy** on each raw table: fails when the table's last extract is more than 3 hours older than the
   simulated now.
2. **Schema contract** on each raw table: fails when the landed columns differ from the source contract (a column added,
   renamed, or a required column empty in the newest batch).
3. **dbt data tests** (models/schema.yml, each mapped to an asset check): unique and not-null keys in staging; payment
   events unique on (invoice, attempt); bookings dated in the future while marked completed; customer accounts without a
   billing customer id above 1%; billing_status within its four values; health_score present and within 0 to 100.
4. **Change-volume breaker** on sync/plan: fails when more accounts would change band this hour (billing_status changes,
   health_score crosses 50, or the account is new to the ledger) than max(20, 3 x the most seen in any of the previous 24
   regular runs that wrote, the first run excluded); it passes until 6 such runs exist.
5. **Read-back reconciliation** on sync/plan, before each write: reads every account the sync has written and fails when
   any CRM value differs from what the sync last confirmed writing.
6. **As-of guard**, inside the sync: never send a value computed as of an earlier time than the one already sent for
   that account. It is not a check and stops nothing: it drops those rows and lets the rest through.

A check that fails stops what is downstream of it for that hour; the next hour evaluates it again. So a guard whose
condition persists (a renamed column stays in the raw table; a CRM left out of step by a stopped sync stays out of step)
keeps the sync stopped until a person intervenes, and no person intervenes in this simulation.

## Arms

- **Guarded:** every check blocking (a failed check stops the steps below it, so the CRM is not written that hour), dbt
  tests at error severity under `dbt build`, the as-of guard on.
- **Unguarded:** the same checks run and are recorded but stop nothing (dbt tests at warn severity), and the as-of guard
  is off. The sync's own idempotency and ledger stay in both arms.

## Breaks

The fault grammar (orchestrated/grammar.md) states what the injector (orchestrated/faults.py) can express: 11 operations
on a source extract, 3 on the orchestrator and 7 on the CRM, each with its parameters. A break starts between hours 24 and
35 and is followed for 24 hours.

My declared schedule (orchestrated/breaks/declared.json), all starting at hour 30 except the backfill:
1. late_billing_load: the payment and refund webhook tables do not land for hours 30 to 39; invoices land on time.
2. duplicated_webhook: from hour 30 every payment webhook lands twice, the copy with a new event id.
3. crm_field_renamed: from hour 30 the CRM sends the account's billing customer id under a new column name.
4. timezone_shift: from hour 30 booking times arrive 7 hours late.
5. partial_sync: hours 30 to 53, the CRM applies the first half of each write request's rows and reports success for all.
6. backfill_resend: at hour 34 the sync is run again for hours 24 to 29.

**Held-out breaks.** An independent author who never saw the guards, their thresholds, the freshness policies, my
schedule or my predictions writes 12 breaks in the same grammar, as a team might meet them, each with a description and its
own expectation. It receives only the author bundle: the business description, the source schemas, the dbt model list,
the sync's target fields, the simulated clock's range and the fault grammar (hashed in the protocol). It runs once, read
only, from a clean folder holding only those files; its output file is hashed into the slot the protocol reserves for it
before any break is run. Its breaks are scored by the same code as mine and reported apart from mine, never pooled. A
break the grammar cannot express is reported with the reason, not dropped; a break that starts outside hours 24 to 35 is
reported and run from the nearest allowed hour only if the author's text gives a start that maps to one, else reported
as not run.

## Runs

- Clean guarded runs, seeds 1 to 30, hours 0 to 59: the false stops.
- Clean unguarded runs, seeds 1 to 3, hours 0 to 59: the truth for the break runs (every hour's dbt output with no break
  and nothing stopped).
- Break runs, seeds 1 to 3, both arms, for my six breaks and every held-out break: each starts from its clean twin's
  state at the end of hour 23 (same seed and arm) and runs from hour 24 to 23 hours after the break's start.

A seed fixes the business and the benign noise, so a break run and its clean twins share every event but the break.

## Measures (orchestrated/measure.py), per break, arm and seed, over the 24 hours from the break's start

The truth at hour h is mart_account_sync_hourly of the clean unguarded run of the same seed, as of hour h. A health_score
differs from the truth when the two are 5 or more points apart or on opposite sides of 50; a billing_status differs when
it is another value.

1. **Wrong values written:** field changes the sync applied to the CRM (including late copies; a write that leaves a
   value unchanged is not a change) whose new value differs from the truth at the hour it was applied.
2. **Accounts wrongly acted on:** distinct accounts with at least one automation fired while the truth at that hour was
   not in the state that fires it (defined above). Also reported: all accounts acted on.
3. **Missed actions:** accounts for which the clean unguarded twin fired an automation in the window and the break run
   fired none of that kind for that account in the window.
4. **CRM values left wrong:** account-field-hours at which the CRM's value (at the end of the hour) differs from the
   truth; and the share of accounts with a wrong field at the window's end.
5. **Hours until a check stopped the sync** (guarded arm): the first hour at or after the break's start at which a
   regular run did not write because a blocking check failed that did not fail at that hour in the clean guarded twin,
   minus the start hour; "not stopped" when there is none. The checks that failed are named.
6. **First hour each check fails** (unguarded arm, same attribution against the clean unguarded twin): which checks would
   have seen the break, and when, had they been blocking.
7. **Rows held back by the as-of guard** (guarded arm).

**False stops**, on the 30 clean guarded runs, hours 24 to 59 (1,080 run-hours): per guard family (freshness, schema
contract, dbt tests, change-volume breaker, read-back), the runs with at least one regular run stopped by it (with a
Clopper-Pearson 95% interval over the 30 runs) and the hours it stopped (with a 95% percentile interval from 10,000
bootstrap resamples of whole runs). The as-of guard's held-back rows on clean runs are reported too.

## Analysis

Each break and arm is reported per seed and as the range over the three seeds, never pooled across breaks, and the
declared and held-out sets are never pooled. A difference between arms is called clear for a break when it has the same
sign in all three seeds. The worked example on the page follows one account through one break, hour by hour, in both
arms: the break and account are chosen by a rule fixed here, the first account (by id) wrongly acted on in the
unguarded run of late_billing_load, seed 1; if there is none, the first such account in the next break of the declared
list.

## Predictions (declared before any break was run)

Rates behind them, from the two clean development runs (below): 0 to 10 band changes an hour, roughly one at_risk_task an
hour, collections and win-back emails a few times a day, 56 to 62 accounts under 50, and a stop of the
rest of the run when a benign custom field arrived (dev seed 101). "Guarded" and "unguarded" are the arms; each band
holds for every one of the three seeds unless it says otherwise.

| Break | Guarded: hours until stopped, first check | Guarded: accounts wrongly acted on | Unguarded: accounts wrongly acted on | Unguarded: wrong values written |
|---|---|---|---|---|
| late_billing_load | 3, freshness on the payment events (safe bet: the 3-hour window) | 2 to 12 | 15 to 40 | 15 to 60 |
| duplicated_webhook | 0 or 1, the dbt test on (invoice, attempt) | 0 | 0 to 6 | 5 to 25 |
| crm_field_renamed | 0, schema contract on CRM accounts (safe bet) | 0 | 110 to 200 | 120 to 260 |
| timezone_shift | 9 or 10, the dbt test on future-dated completed bookings (the first completed bookings arrive when the businesses open) | 0 | 10 to 60 | 100 to 1,500 |
| partial_sync | 1 to 3, read-back reconciliation | 0 | 0 to 5 | 0 to 5 |
| backfill_resend | not stopped; the as-of guard holds back every re-sent row (safe bet) | 0 | 2 to 15 | 10 to 150 |

Further predictions:
- In the guarded arm, every stop caused by duplicated_webhook, crm_field_renamed, timezone_shift and partial_sync lasts
  to the end of its window (the condition persists and nobody intervenes), so missed actions there are at least 15
  accounts for each of those breaks, more than the unguarded arm misses.
- late_billing_load's guarded stop ends when the backlog lands (hour 40), and the change-volume breaker then stops the
  catch-up hour or the one after it in at least one seed.
- partial_sync, unguarded: the accounts missed are at least a third of the clean twin's acted-on accounts in the window.
- backfill_resend, unguarded: the change-volume breaker fails on at least one re-sent hour in at least one seed.
- False stops on the 30 clean guarded runs, hours 24 to 59: schema contract in 3 to 12 runs (an unrelated custom field
  stops the rest of the run); freshness in 0 to 7 runs (only a 4-hour outage trips the 3-hour window); change-volume
  breaker in 0 to 3 runs; dbt tests and read-back in 0 runs (safe bets: the clean data satisfy every test, and nothing
  but a break edits the synced fields); the as-of guard holds back 0 rows (safe bet).
- Held-out breaks: the guarded arm stops a smaller share of the held-out breaks that write wrong values than of mine, and
  at least one held-out break writes wrong values in the guarded arm that no check stops within its 24 hours.

## Known before running, or true by construction

- Truth is the clean unguarded run of the same seed, so every measure is zero on a clean run by construction; the
  measured part is how far a break moves a run from its clean twin.
- The as-of guard removes every re-sent older value by construction; backfill_resend in the guarded arm can only show
  that the mechanism is wired, not that it is hard to build.
- A schema contract fails on any renamed or added column by construction, so it catches crm_field_renamed at the first
  extract after the rename, and it fails on every unrelated custom field too.
- The freshness window fixes how long a stalled load runs unchecked: 3 hours, by construction.
- The read-back reconciliation and the dbt tests cannot fail on a clean run (no break edits the synced fields; the clean
  data satisfy every test), so their zero false stops are true by construction, not a measurement of their precision.
  Only the freshness policy, the schema contract (through the custom fields) and the breaker face benign noise here.
- I wrote the business, the breaks I declared, the guards and their thresholds: the declared schedule is a self-test.
  The held-out breaks are the test of guards written without sight of the breaks.

## Development runs (disclosed)

Before freezing: two clean runs on seeds not in the study (seed 101, guarded, hours 0 to 59; seed 102, unguarded, hours
0 to 40), short clean smoke runs of the same seeds, and the mechanics tests in orchestrated/tests on small fixtures,
which include applying each inbound grammar operation to a four-row table (no pipeline run, no check evaluated on a
break). No break was run through the pipeline. Changes made after those runs, each before the freeze:
- after seed 101's first hour: the change-volume breaker passes until 6 earlier runs exist (the initial load of 2,400
  accounts tripped it);
- after seed 101 hours 0 to 7: the bookings staging model became incremental, dbt runs in process with the parsed
  manifest reused, the CRM keeps its state in files, and the plan is built in SQL (speed only; no value
  changed);
- after seed 102: the unguarded arm parses dbt with tests at warn severity instead of running `dbt run` then `dbt test`
  (same tests, one invocation), and the driver undoes and stops on any step failure that is not a check (a method
  failure is never scored; one interrupted hour in seed 102 led to this);
- seed 101 showed an unrelated custom field stopping the guarded sync for the last 32 hours; the schema contract was
  kept as declared, and the prediction above reflects it.

The one-command demo (Reproducing, below) was then run once end to end; it is clean seed 101 again and gave the same
28 hours written and 32 stopped. After it, the CRM's segment column was made to follow each customer's location
count (it had been the same value for every account; no model reads it, and no other generated value changed), and
the generated data are now cached under a hash of the generator so a changed generator never reuses old data.

## Limits known before running

- One synthetic business of 2,400 customer accounts, 60 simulated hours, three seeds per break; all rates assumed.
- One break per run, scored against its clean twin; real incidents overlap.
- Nobody repairs anything: a stop lasts until its condition clears by itself. With an on-call person the stops would be
  shorter and the missed actions fewer; the hours until a check stops the sync are the measured part.
- The CRM, its automations and the source systems are fakes; no product was tested and none is imitated field by field.
- The automations are three declared rules; "acted on" counts their firings, not what a person did next.

## What would change the conclusion

If the held-out breaks were mostly caught at 0 hours by the schema contract and the dbt tests, the guards' value would
rest on those two and on whether their false stops are acceptable. If the breaker or the freshness policy stopped clean
runs as often as the schema contract, a team would need a person in the loop for every stop, and the case for blocking
checks over alerting ones would weaken.

## Reproducing

One command from a clean clone, with a folder outside the repo for the venv, the caches and the runs:

    bash portfolio/ai-answers-over-company-data/orchestrated/demo.sh <scratch folder>

It builds a venv from orchestrated/requirements.lock (Python 3.12) once, then runs clean seed 101 in the guarded arm for
hours 0 to 59 and prints how many hourly runs wrote to the CRM and how many a check stopped. The study's runs use the same driver: `python -B -m orchestrated.run make-plan <runs.json> [held-out file]`, then
`python -B -m orchestrated.run plan <runs.json> --worker K --of N --budget SECONDS` from the study folder with
ORCH_SCRATCH set, repeated until every run reports done; scoring is orchestrated/measure.py. Mechanics tests:
`python -B -m pytest orchestrated/tests -q -p no:cacheprovider`.

## Changes to the protocol (appended; the text above is unchanged apart from Change 3)

- Change 1 to the protocol, made after the held-out breaks arrived and before any break was run: the injector's extract
  hook considered every operation, so an operation without a source (the orchestrator and CRM operations) or without a
  from_hour (rerun) would have crashed it; it now considers only extract operations. A mechanics test applies every break
  of both files to a three-row world for every hour. No measure, threshold, guard or break changed.
- Change 2 to the protocol, made before any break was run: H12 carries its author's own "not expressible" note; it is
  reported as not expressible, and its closest operations, as written, are run and scored apart.
- Change 3 to the protocol, made before any result was computed: run-time phrases removed from this file, the demo
  script and a docstring. Wording only.
- Change 4 to the protocol, made after the results. The first scoring of all 108 break runs was invalid, and I saw its
  results before the fault was found and fixed. Fault: the driver copied each clean twin's state at the end of hour 23
  without DuckDB's write-ahead log, so every break run started from a warehouse as of hour 19 beside a CRM as of hour
  23; the read-back check then stopped every guarded break run from its first hour. Fix (orchestrated/run.py): checkpoint
  the warehouse before copying it and copy any write-ahead log left. The six hour-23 snapshots were made again by
  rerunning hours 0 to 23 of each clean twin; their checks and CRM history matched the original clean runs exactly. All
  108 break runs were run again from them and scored by the same code. The clean runs were unaffected (no read-back
  failure in any of the 33). The first scoring and its run folders are kept privately, outside every score. No
  prediction band, guard, threshold, measure or break changed.
- Change 5 to the protocol, made after the results: the run driver no longer opens a snapshot that has no write-ahead
  log (it is already checkpointed), because two runs starting from one shared snapshot at once could not both take its
  write lock, and those runs stopped before their first hour. Runs that were cut off part-way (85 after a machine
  crash, 23 after a stalled session, and 3 whose last hour was interrupted when a chunk of runs was stopped) were
  discarded whole and run again from the start; no partial run is scored. No value of a finished run can change: a run
  either fails before its first hour or proceeds exactly as before. No prediction band, guard, threshold, measure or
  break changed.
