Chapter 1 — ETL (Stage)¶
1.1 — The boundary: custom data in, staging out¶
⚙ Process: a registered Stage process — the per-customer adapter that lands the customer's data into the staging tables. This is the FLEXIBLE side: it connects to custom inputs and will evolve as new customers are onboarded. Its output is the
import.*staging tables — that is its ONLY job.Customer source (CSV, the customer DB, Flow History…) → STAGE process per-customer adapter (evolves per customer) → import.* staging tables THE BOUNDARY (known schema)
The architectural contract: Stage is per-customer and open-ended (a new customer = a new adapter, zero changes anywhere else). Import (Point 2) is global and stable — it reads the known staging schema and promotes it into the core tables, identically for every customer. The staging schema is the single interface between them: left of it, anything goes; right of it, one standard engine.
Everything about the promotion — the load modes, the fitness guard, the counts, the run review — is documented in Point 2. This point covers only the extraction into staging.
→ STAGE process per-customer ETL etl.customer_processes → import. staging (PG, tenant-isolated) → IMPORT standard engine (Point 2) → master. core
Stage is an independent process card, not a hidden pipeline phase: it is registered in
PIPELINE_STEPS (runnable standalone and as a workflow step) but removed from
PIPELINE_STEP_ORDER — the run-all chain and the Processes tab chain carry no trace of it.
Workflows include it opt-in (new workflows default to ["stage","import"] at the head; stored
step lists own their presence). The Stage card in the ProcessRunner "Processes" tab shows a
"Tenant-wide" chip plus the configured process name, and its Configure button
opens the former ETL tab content in a modal (ImportStageTab).
What the stage process achieves¶
In one sentence: land the customer's data — extracted in whatever shape the customer's systems
produce — into this tenant's import.* staging tables, in the ONE standard shape the import engine
expects, with a complete audit trail — and touch nothing else.
| Goal | Meaning |
|---|---|
| Standard shape | Every object lands in import.<object> with the exact columns the import step expects; headers are validated against information_schema, never hand-mapped or guessed. |
| Per-customer freedom | The extraction side is customer-specific and open-ended; the import side is identical for every customer, so a new customer never changes it. |
| Auditability | Every run writes import.import_run (run_kind='stage') plus one import.import_table_result per object; failures are recorded with their error, never swallowed. |
| Safety | Core tables are never touched; a failed or partial stage cannot corrupt master.*. The import's staging-fitness guard re-checks staging before any core write. |
Tables a stage run WRITES — and nothing else¶
1. The staging objects — import.<object>, one table per object (40 today).
The map also shows what each object becomes after the import — that core write is the import's job
(Point 2), never the stage's. Read the target column with two rules: every target is shared across
pipelines (never pipeline-scoped — the pipeline-scoped family is PIPE_*, written by the
engines), and every target is PostgreSQL except the two ClickHouse-native history tables in
bold (no PG master copy — their staging table is their only PG home):
| Family | Staging object (import.*) | Core target — filled by the IMPORT (Point 2) | Default import mode |
|---|---|---|---|
| Types & master data | item_type · site_type · demand_type · route_type |
master.item_type · master.site_type · master.demand_type · master.route_type (condition pair resolved here) | upsert |
item · site · zone |
master.item · master.site (zones are site_class='zone' rows of the same table) | upsert | |
customer · channel | master.customer · {schema}.master_channel | upsert | |
item_location | master.item_location | upsert | |
item_supersession | {schema}.item_supersession | upsert | |
| Demand & forecast | demand_actuals | master.demand_orders — the order level, one row per order line; weekly master.demand_actuals is derived later by the pipeline etl step | truncate_replace |
forecast_external | master.forecast_external — customer forecast as master data | truncate_replace | |
feature_values | {schema}.master_feature_values — the feature store | append | |
| Supply & order flow | route · route_resource · route_quota_override |
master.route · master.route_resource · master.route_quota_override | upsert |
bill_of_material · on_hand | master.bill_of_material · master.on_hand | truncate_replace | |
firm_supply_orders · sales_return |
{schema}.master_supply_orders_firm · {schema}.master_sales_return | upsert | |
purchase_receipt |
ClickHouse MASTER_supply_orders_hist — the receipt history table, no PG master copy | truncate_replace | |
supply_movement |
ClickHouse MASTER_supply_movement — the movement history table, no PG master copy | truncate_replace | |
| Capacity & calendars | capacity | master.capacity — dated resource ranges | upsert |
capacity_day_off | master.capacity_day_off | truncate_replace | |
calendar · calendar_entry | master.calendar · master.calendar_entry | upsert | |
currency_conversion | {schema}.master_currency_conversion | upsert | |
| Causal & maintenance | causal_usage_type · causal_asset_type |
master.causal_usage_type · master.causal_asset_type | upsert |
causal_asset · causal_failure_rate |
{schema}.master_causal_asset · {schema}.master_causal_failure_rate | upsert | |
causal_bom · causal_fleet_plan |
master.causal_bom · master.causal_fleet_plan | upsert | |
causal_asset_coverage · causal_asset_deployment · causal_asset_usage |
master.causal_asset_coverage · master.causal_asset_deployment · master.causal_asset_usage | upsert | |
maintenance_event · maintenance_bom |
master.maintenance_event · master.maintenance_bom | upsert |
2. The audit trail — import.import_run + import.import_table_result
(run_kind='stage'), and the process-log entry when the run comes from a workflow step.
Per-process staging coverage¶
| Process | Objects it stages |
|---|---|
customer_db_source |
12: item_type, site_type, item, site, customer, item_location, route, bill_of_material, on_hand, demand_actuals; optional forecast_external and purchase_receipt. |
customer_erp_source |
The customer's model over the same contract (harvest resources as capacity, shelf life, lost sales) — 16 stage runs to date. |
flow_history_source |
15 objects: item_type, site_type, demand_type, route_type, item, site, customer, item_location, route, demand_actuals, on_hand, feature_values, firm_supply_orders, sales_return, and supply_movement. |
csv_directory |
Any subset of the 40 — one <object>.csv per object in the configured directory |
| Interactive upload | Any single object, on demand |
Tables a stage run NEVER writes¶
| Never written | Ownership |
|---|---|
Every master.* / {schema}.master_* core table — all 40 targets in the map above |
Owner: the import process (Point 2), only after the staging-fitness guard passes. |
Every ClickHouse PIPE_* result table |
Owner: the engine steps (forecast, MEIO, supply, allocation — Points 5–7). Stage never touches ClickHouse. |
The CH-native history tables MASTER_supply_movement / MASTER_supply_orders_hist |
Owner: the import's CH-writing steps, from import.supply_movement / import.purchase_receipt; Stage fills the staging side only. |
| The customer source database | Owner: nobody — customer_db_source / customer_erp_source connect read-only. |
master.condition |
Owner: runtime DDL seeds it; the customer on-hand derivation only reads it to validate condition codes. |
{schema}.config_parameters (stage_settings) |
Owner: the configuration surface only (the Stage card's Configure modal); a stage run only reads it. |
1.2 — The integration library¶
The integration library is the catalog of available connectors — one entry per customer data source.
Each entry is a module that knows how to extract that customer's data into the staging tables.
get_process(name) fails loudly on an unregistered name — never a silent skip.
Adding a new customer's connector = one new module + registration; it then appears in every settings
dropdown with no changes anywhere else.
| Registered process | What it does and current linkage |
|---|---|
csv_directory |
What it does: every <object>.csv in a configured directory COPYs into import.<object>; unknown file names fail loudly. Optional objects subset and per-object modes.Tenants linked today: none. |
flow_history_source |
What it does: explicit FILE→OBJECT map (15 objects from item_type.csv through supply_movement.csv), all replace full snapshots; auxiliary artifacts are skipped, unknown CSVs warn, and on_hand is derived fresh from Stock Plant.csv on every run (see 1.7).Tenants linked today: the demo tenant, another demo tenant, and the demo tenant (dormant — no workflow carries stage). |
customer_db_source |
What it does: the customer scenario DB (plan/dp_plan/dpm_stat/custom) feeds staging through a read-only remote connection from stage_settings.params; optional objects include external forecasts, purchase receipts, order-book rows, and planning-date pinning.Tenants linked today: the customer tenant. |
customer_erp_source |
What it does: the customer's instance feeds staging with its own harvest-capacity, shelf-life, and lost-sales model; the SQL is customer-specific but follows the same standard contract. Tenants linked today: the customer (the customer tenant). |
Per-connector behaviors & edge cases¶
| Process | Specific behavior |
|---|---|
csv_directory |
Missing directory → loud error; missing directory or CSV → loud error; unknown staging-table name → loud error listing valid objects; a missing CSV in a replace run leaves the current staging content untouched (missing ≠ “wipe to empty”); objects filters skip with INFO. |
flow_history_source |
on_hand is derived, not copied: it is built fresh from Stock Plant.csv on every run. The STORAGE_LOC condition translation (1AVL→good, 2DIR/3REP/REPR→bad_lvl1; 5SCR, 7EMP, 8FUL, 0001, and blank are excluded and counted) lives in exactly one place and is validated against the live master.condition table before a single row is written.Why the guard exists: when bad was renamed to bad_lvl1, an old hard-coded map could have silently counted repair/wash stock as good on the next re-import. A stale map now fails the stage run loudly. A pre-built on_hand.csv is used only when Stock Plant.csv is absent; this documented dual-mode is logged. |
customer_db_source / customer_erp_source |
The remote customer DB is opened read-only with credentials from stage_settings.params; the source is never written. Objects use full-snapshot replace, optional flags select extra objects, and customer exclusions are counted loudly in the stage audit. |
1.3 — Stage settings & workflow wiring¶
⚙ Process: the Stage process card's Configure button opens the settings modal. The workflow
stagestep reads the tenant's linkage.
| Situation | Meaning |
|---|---|
| A process is configured | The workflow stage step runs it and extracts the customer's data into staging. |
| No process configured | The step is a logged no-op; staging is fed manually or through upload. |
| Configured name not registered | The run fails loudly with the registry hint. |
| Workflow override | The workflow editor's stage-row dropdown can override which process runs for one workflow; parameters still come from tenant-wide settings. |
Stage and Import appear as two paired process cards in the ProcessRunner — but they are independent processes with separate configuration surfaces. The Import card's configuration is documented in Point 2.
1.4 — Configuring the stage process (walkthrough)¶
Where: ProcessRunner → Processes tab → the independent ETL — Stage card
(showing the "Tenant-wide" chip + the configured process name) → Configure. The modal hosts the former
Stage tab (ImportStageTab.jsx) and is the ONE tenant-wide configuration surface. The workflow editor's
stage-row dropdown can override which process runs for that one workflow — parameters always come from here.

Fig. 1 — ProcessRunner Processes tab (the customer tenant): the two independent process cards above the
pipeline chain. The ETL — Stage card carries the Tenant-wide chip + the configured
process (customer_db_source); the Import card shows the pipeline's linked import scenario.
Captured 2026-11-09.
How it saves: the editor auto-saves ~800 ms after the last change (app-wide no-Save-button convention; the status shows Saving… / Saved / Save failed). Reading the settings is open to any authenticated user (secrets redacted); writing requires admin; an unregistered process name is rejected at save time with the registry list.
Modal anatomy¶
| Section | Meaning |
|---|---|
| Per-customer ETL process | Configure: the Process dropdown contains None (manual/add-on staging) and every registered process with a description tooltip. None makes the workflow stage step a logged no-op. |
Directory-based form (csv_directory, flow_history_source) |
Configure: the directory containing <object>.csv files and an optional comma-separated object subset; an empty subset means all objects. |
The customer form (customer_db_source) |
Configure: source host, port, database, SSL mode, user, password, and the four staging toggles. |
| Interactive staging (any process) | Configure: pick the object and the replace/append mode, then upload the CSV right here. The template button generates the exact expected header; start hand-built CSVs from the template. |
| Staging state & history | Read: per-object staging counts and the last 20 stage runs with status and row counts. |

Fig. 2 — The Stage config modal with csv_directory selected: the Directory
(CSV source of the process) + Objects (optional subset) fields, and the per-process helper text;
the interactive upload section and the run history render below. Captured 2026-11-09 on the customer tenant with the
auto-save intercepted — no tenant configuration was changed for this capture.
1.5 — Bulk primitives & data conventions¶
All staging goes through the shared primitives in files/etl/customer_processes/base.py —
never per-row INSERTs, never hand-maintained column lists:
| Primitive | Contract |
|---|---|
| Streaming COPY | COPY import.<table> FROM STDIN WITH (FORMAT csv, HEADER false, NULL '\N'). Files are consumed directly by PostgreSQL; Python-side tuples stream in 20,000-row chunks (COPY_CHUNK). |
| NULL convention | Only a literal unquoted \N is NULL; an empty field is DATA. This project-wide convention means import.supply_movement.source_site_xuid = '' is “external supplier”, never NULL. |
| Header validation | Strict against information_schema; unknown columns or empty headers fail loudly. There is no guessing or subset loading. |
| replace mode | TRUNCATE + COPY for full-snapshot ERP loads. A failed run leaves touched objects empty; the import fitness guard refuses stale/empty state rather than silently importing it. |
| append mode | COPY into a temporary twin plus set-based INSERT…SELECT ON CONFLICT DO NOTHING; natural-key duplicates are counted as rejected with no Python row iteration. |
| ANALYZE | Runs after every load so large import joins do not plan against stale statistics. |
1.6 — The ETL audit trail (import.import_run)¶
This is the ETL/import-specific portion of the application-wide audit infrastructure — see section 0.3 for the full picture.
Every stage run writes an import.import_run row with
run_kind='stage' — the two processes share one audited history (the Import writes
run_kind='import'). One import.import_table_result row is written per object.
| Column | Meaning |
|---|---|
import_run.run_kind |
'stage' (this point) — the customer-data extraction into staging |
import_run.source |
The process name or the uploaded filename |
import_table_result.load_mode |
replace or append, with row counts and error samples |
1.D — For developers — the stage API surface¶
Everything above is doable from the app's screens; the equivalent API calls, for scripts and add-ons:
| Call | Purpose |
|---|---|
GET /api/import/stage/settings · PUT /api/import/stage/settings |
Read (any authenticated user, secrets redacted) / write (admin) the tenant-wide stage linkage — the same field the Configure modal edits. |
POST /api/import/stage/{object} |
Interactive staging upload (admin; multipart CSV → COPY, mode=replace\|append with temp-twin dedupe). |
GET /api/import/stage/templates/{object} |
The template header for an object's CSV (the catalog's exact columns + the NULL convention note). |
GET /api/import/tables |
Per-object staging row counts (the staging-state section's source). |
GET /api/import/stage/runs · GET /api/import/runs?run_kind=stage |
The stage run history (status + per-object counts). |
1.T — Step-by-step test walkthrough¶
Stage verification — land the customer's data into staging without touching core tables.
| # | Where to look / what to click | You should see |
|---|---|---|
| 1 | Left menu → Processes (route /processes) |
the two INDEPENDENT cards above the chain: ETL — Stage (Tenant-wide chip) and Import (scenario chip) |
| 2 | Stage card → Configure | the settings modal: process dropdown + per-process form |
| 3 | Process dropdown → pick a process | the form swaps to that process's fields (Directory + Objects for a directory flow) |
| 4 | Fill Directory (folder of <object>.csv files), leave Objects empty |
auto-save confirms Saved; empty Objects = stage every object found |
| 5 | Interactive staging → pick an object → template download | the CSV template's headers match the staging schema exactly — always start hand-built CSVs from it |
| 6 | Interactive staging → mode append → upload a CSV | the object's staging row count grows (Staging state section) |
| 7 | Stage card → Run | job log streams; on completion the run history shows status + per-object counts |
| 8 | Run history entry → expand | per-object staged/rejected counts; the audit row carries run_kind='stage' |

The Stage and Import process cards — independent processes above the pipeline chain.

The Stage configuration modal: process dropdown, directory form, interactive staging.