Chapter 2 — Import (Core)¶
2.1 — What the import does: import.* staging → core tables¶
⚙ Process: the import engine — the pipeline's import scenario drives it. How to run it: the Import process card → Configure → ▶ Run Import (scenario) (the standard, guarded run) or Run all (ad-hoc) (the legacy, unguarded path), or a workflow that carries an
importstep. Partial runs and per-run mode overrides are scripts/add-on territory only (2.D).
The import copies the staged rows from the tenant's import.* tables into the
core tables — it is the only sanctioned writer of core business data. The input is staging
(read-only for the run — the import never modifies what it reads). Along the way it resolves the customer's
*_xuid string keys to numeric ids, runs the objects in the fixed FK dependency order, applies the
configured load mode per object, rejects rows whose keys resolve to nothing (counted, never
guessed), and counts everything it does (2.2). One engine, one code path, identical for every
customer:
import. staging (input — read-only) → import engine xuid → id resolution FK dependency order per-object load mode → unresolvable rows REJECTED (counted + sampled) → core tables (the list below) →* counts: import_run + import_table_result (+ rejection samples)
The core tables the import fills — one per staging object (39 distinct tables for 40 objects:
site and zone both land in master.site). Object-level detail with load
modes: the map in 1.1. Two dimensions make the list readable at a glance:
| Dimension | How to read it |
|---|---|
| Pipeline scope | Shared across pipelines. Master/business data and staging have no pipeline dimension; the import writes shared tenant data, not pipeline output. Remark: the pipeline-scoped family is PIPE_* (forecast/MEIO/supply outputs), written by engine steps and never by the import. The only nuance is master.capacity: rows can carry scenario_id (NULL = all scenarios), giving row-level scoping inside an otherwise shared table. |
| Destination | 37 PostgreSQL tables plus ClickHouse-native history tables. PostgreSQL holds the shared master.* schema and {schema}.* tenant-schema tables in the same tenant database.Remark: the two ClickHouse-native history tables have no PostgreSQL master copy. Their import steps write ClickHouse directly; their only PostgreSQL home is staging because those histories grow unbounded and are not mirrored back. |
| Family | Core tables and destination |
|---|---|
| Registers & master data | PostgreSQL: master.item_type · master.site_type · master.demand_type · master.route_type · master.item · master.site (zones are site_class='zone' rows) · master.customer · {schema}.master_channel · master.item_location · {schema}.item_supersession. |
| Demand & forecast | PostgreSQL: master.demand_orders (the order level) · master.forecast_external · {schema}.master_feature_values. |
| Supply & order flow | PostgreSQL: master.route · master.route_resource · master.route_quota_override · master.bill_of_material · master.on_hand · {schema}.master_supply_orders_firm · {schema}.master_sales_return.ClickHouse-native: MASTER_supply_movement (movement history) and MASTER_supply_orders_hist (receipt history). |
| Capacity & calendars | PostgreSQL: master.capacity (scenario-scoped rows possible) · master.capacity_day_off · master.calendar · master.calendar_entry · {schema}.master_currency_conversion. |
| Causal & maintenance | PostgreSQL: master.causal_usage_type · master.causal_asset_type · master.causal_bom · master.causal_fleet_plan · master.causal_asset_coverage · master.causal_asset_deployment · master.causal_asset_usage · master.maintenance_event · master.maintenance_bom · {schema}.master_causal_asset · {schema}.master_causal_failure_rate. |
Mechanics that matter for testing: one set-based INSERT…SELECT per object (xuid→id
FK resolution inside SQL — no Python row iteration; the only sanctioned exceptions are the two CH history-table steps
whose rows transit through Python), always in STEPS dependency order (types → entities
→ structures — never JSON key order), a per-object SAVEPOINT (one failing object rolls back
alone → run status completed_with_warnings), one final commit, and a session-scoped
advisory lock so concurrent imports queue instead of overlapping.
2.2 — Where the counts land — and what the import never touches¶
Every import run writes what it counted into the audit tables — this is where the results live:
| Table | What the row means |
|---|---|
import.import_run |
One row per run. The run header: total_rows_loaded, total_rows_rejected, status (completed / completed_with_warnings / failed), scenario_id, triggered_by, and error_message.Remark: run_kind reads 'import' for imports versus 'stage' for Point 1. |
import.import_table_result |
One row per object per run. The per-core-table counts: rows_staged, rows_loaded, rows_rejected, load_mode, target_table, error_sample, and duration_ms.Remark: rows_rejected counts orphan-xuid rows; the other fields explain what was staged, what landed, and how long it took. |
import.import_rejection_sample |
One row per rejected row when capture_rejections is ON. The offending staged row as JSONB plus the rejection reason, feeding the run detail's “View rejected rows”. |
pipe_process_log |
One row per run. Entries under import:<run_id> put import jobs in the Process Log UI next to pipeline runs. |
The import never writes: the import.* staging tables themselves (input only —
staging is the customer's to manage), any PIPE_* engine output, the customer source DB, any core
object not selected by the run ("objects listed = objects loaded; absent objects are untouched"), and nothing
outside the tenant (account-context isolation).
2.3 — The user's options: full vs partial¶
| Run shape | How to read it |
|---|---|
| Full — scenario-driven (the standard path) | How invoked: “▶ Run Import (scenario)” button or a workflow import step.What loads: every object the scenario lists, in STEPS dependency order, with its per-object modes. Fitness guard: ON — the run is refused before any core write if staging is unfit. |
| Partial — scenario subset | How invoked: scripts and add-ons only — there is no UI button (2.D). What loads: only the listed objects; tables must be a subset of the scenario's objects or the request fails loudly.Fitness guard: ON for the selected subset only. |
| Ad-hoc — no scenario | How invoked: “Run all (ad-hoc)”. What loads: all steps at their step-default modes; empty staging silently no-ops under legacy semantics. Fitness guard: OFF — this is the legacy silent-skip path. |
Per-run mode overrides are also scripts/add-on territory (2.D); their precedence chain is
documented there. The in-repo consumer of the partial+override path is the customer add-on
(files/addons/customer/stage.py::run_import(tables, extra_modes)).
Load modes — what each means for the core table¶
| Mode | Meaning for the core table |
|---|---|
truncate_replace |
Semantics: TRUNCATE + INSERT…SELECT; staging is the sole source of truth, so rows removed from the extract disappear from the core on the next import.Use when: full-snapshot extracts such as demand actuals, on-hand, external forecasts, calendars, and CH history. |
upsert |
Semantics: INSERT…SELECT ON CONFLICT DO UPDATE on the natural key; merge, never delete.Use when: incrementally maintained master registers such as item, site, route, customer, and bill of material. |
append |
Semantics: add-only with natural-key dedupe (ON CONFLICT DO NOTHING).Use when: accumulating feeds such as the feature store ( feature_values). |
Supported modes are derived per object from its SQL (step_supported_modes) — the editor dropdown
offers only those; the two CH steps are always truncate_replace, and zone has no
truncate (upsert-only). An unsupported mode in a scenario fails validation at save AND run time.
Staging-fitness guard (scenario-driven runs; runs before any core write)¶
| Staging state | Meaning |
|---|---|
| Table absent, non-optional object | Hard error — “Stage the customer data first”. |
Empty + truncate_replace + not allow_empty |
Hard error — an empty replace snapshot would silently keep stale data because the step skips on zero staged rows; the API maps it to 409. |
| Empty + upsert/append | WARNING — proceeds as a no-op load. |
allow_empty: true |
INFO — empty cycles are legitimate for seasonal flows; this is the only way to allow an empty replace snapshot by design. |
The Import modal shows a client-side mirror of the guard (per-object badges: "no staging table" / "EMPTY + replace → fails" / "empty (allowed)" / "empty (no-op)") — the server guard remains the enforcement point.
What 'Empty OK' (allow_empty) is for.
It answers ONE question per replace-mode object: is an empty staging table legitimate this cycle? OFF (default): an empty staging snapshot fails the run BEFORE any core write — without the guard, the zero-row skip would report "success" while loading nothing, silently keeping the previous core snapshot (a missing nightly extract would go unnoticed). ON: the empty cycle is expected (seasonal flows — e.g. an extract with no closed POs this month, an empty promo calendar); the run proceeds, loads 0 rows, logs INFO. Either way the core table is never wiped: zero staged rows always skip the truncate. Upsert/append objects don't need the toggle (empty staging there is a harmless warning no-op) — that's why "Empty OK" only appears on replace-mode rows in the editor.
2.4 — Where the configuration is made¶
Three surfaces, one field: the pipeline's import_scenario_id (pipeline editor dropdown), and the
scenario definitions themselves live on the Pipelines → "📥 Import" tab
(ImportScenarios.jsx):

Fig. 5 — Where the import configuration is made: Pipelines → "📥 Import"
(the customer). The scenario the customer snapshot — 14 objects, each with its load-mode dropdown
(offering only the object's supported modes), the Empty OK (allow_empty)
toggle for replace-mode objects, and the staged-rows-now column. Auto-saves ~800 ms after each change;
"Objects listed = objects loaded; absent objects are untouched by the step." Scenario create starts from the
starter pair (item upsert + demand_actuals truncate_replace); clone and delete per scenario. Captured 2026-11-09.
The Import process card (ProcessRunner → Processes tab) carries the pipeline-side chip, and
its Configure button opens the run surface (ImportTab):

Fig. 6 — The Import process card on the customer: the chip shows the active pipeline's linked import scenario (the customer snapshot) or "None — no import scenario on this pipeline" (the process is then dormant). Captured 2026-11-09.

Fig. 7 — The Import config modal (Import card → Configure) on the customer: the admin
scenario picker (writes the same import_scenario_id as the pipeline editor —
"— None (no import step) —" makes the import process dormant), the staging-fitness preview
for the scenario's 14 objects, the two run buttons — ▶ Run Import (scenario) (full,
guarded) and Run all (ad-hoc) (legacy, unguarded) — both admin-only, and the recent import
runs with per-object results and "View rejected rows". Captured 2026-11-09.
API surface (files/api/import_scenario_router.py +
import_router.py): scenario CRUD + clone + link, the object catalog, the run and
verification endpoints — the full list lives in 2.D. Validation is ONE implementation —
resolve_scenario_config runs at save (400) and run time (ValueError): unknown objects, unsupported
modes, unknown keys, non-bool allow_empty all fail loud.
2.5 — Reviewing a run: where issues show up, and what to work on¶
The whole review loop lives in one place: the Import card → Configure →
the recent-runs table at the bottom of the modal (titled "Recent import runs" in the UI itself). Each row carries the run's status and totals
(import.import_run); clicking a row opens the run detail — the per-object results from
import.import_table_result: staged / loaded / rejected counts, the load mode actually used, the
error sample of a failing object, duration — plus the "View rejected rows" samples when
capture_rejections is enabled. The same runs also appear in the Process Log tab of the
Processes page (rows import:<run_id>) alongside pipeline runs, with the full log tail per
entry.

Fig. 8 — Reviewing a run (the customer): clicking a run row in the runs table opens the detail — the run header (scenario, status, totals) and the per-object results: load mode used, staged / loaded / rejected, duration. All green here — a healthy 1.65 M-row scenario import. Captured 2026-11-09.

Fig. 9 — Where an issue shows up (another demo tenant): the 2026-09-22 run ended
completed_with_warnings — the supply_movement object carries
82,636 rejected rows (the flux2 extract's xuids resolve to nothing in this tenant's site
universe). The run did its job: orphans are counted and shown, never loaded. Captured 2026-11-09.

Fig. 10 — The Process Log (Processes page → Process Log tab), "Search process"
filter set to import: the import:<run_id> entries sit alongside pipeline runs —
the same import runs, with the full log tail expandable per entry. Captured 2026-11-09 on another demo tenant.
Symptom → where you see it → what to work on¶
| Symptom | Where you see it | What to do |
|---|---|---|
Run failed |
Red status in the runs list; import_run.error_message; the failing object's error_sample in the run detail (first error + its staged row) |
Fix the staged data (or the extract that produced it), then re-import just that object — a partial run (scripts/add-ons, 2.D): {"scenario_id": N, "tables": ["<object>"]} — no need to re-run everything |
Run completed_with_warnings |
Amber status; the per-object rows with rows_rejected > 0 or an error sample |
Same as failed, for the affected object only — the others committed fine (per-object SAVEPOINT) |
| Rows rejected (orphan xuids) | The Rejected column in the runs list + the object's row in the detail; rejection samples ("View rejected rows") show the offending rows + the reason | Fix the keys in the source extract so they resolve in this tenant; re-stage the object; re-import it. Live example: Fig. 9's 82,636-rejected run |
| Run refused before starting (fitness guard) | The modal's fitness preview shows it before you click; the server error names the unfit objects; the run never appears as started | Re-stage the missing/empty objects (run the Stage process or an upload) — or mark the object Empty OK when the empty cycle is legitimate (the callout in 2.3) |
| Core table still shows old data after a replace import | rows_staged = 0 for the object in the run detail — the zero-row rule skipped the load |
The extract never arrived in staging — same fix as the fitness refusal |
| Import slow | duration_ms per object in the run detail |
Check the staged counts (the Stage card's staging-state section); re-run the Stage process so ANALYZE refreshes statistics — the single biggest import-side performance lever |
The same answers straight from the database (for scripts / the ):
SELECT id, status, scenario_id, total_rows_loaded, total_rows_rejected, error_message FROM import.import_run WHERE run_kind='import' ORDER BY id DESC LIMIT 10;
SELECT table_name, load_mode, rows_staged, rows_loaded, rows_rejected, error_sample
FROM import.import_table_result WHERE run_id =
SELECT * FROM import.import_rejection_sample WHERE run_id =
Live rejection example (another demo tenant, 2026-09-22)
the last ad-hoc import on another demo tenant ended completed_with_warnings with 82,636 rejected rows — the flux2 supply_movement extract whose xuids do not exist in another demo tenant's site universe (the tenant needs its own CSV; the movement-history import step rejected them instead of guessing). Exactly the loud, counted behavior the import promises: orphans never land in the core.
2.D — For developers — the import API surface¶
The screens above cover the planner's loop; the equivalent API calls, for scripts and add-ons (the staging-side endpoints are in 1.D):
| Call | Purpose |
|---|---|
POST /api/import/run |
The run itself: {"scenario_id": N} full · {"scenario_id": N, "tables": [...]} partial (subset of the scenario's objects) · {"scenario_id": N, "modes": {...}} per-run mode overrides · {} / {"tables": [...]} ad-hoc. Admin. |
GET /api/import/runs · GET /api/import/runs/{id} (+ /log, /rejections) |
The run list and per-run detail with per-object results and rejection samples. |
GET /api/import/tables |
Per-object staging counts (the fitness preview's source). |
GET /api/import-scenarios (+ /objects) · POST /api/import-scenarios · PUT /api/import-scenarios/{id} · POST /api/import-scenarios/{id}/clone · PUT /api/import-scenarios/link · DELETE /api/import-scenarios/{id} |
The scenario CRUD + the pipeline link (the same import_scenario_id the pipeline editor and the Import card's picker write). |
Per-run mode-override precedence: per-request modes > scenario object mode >
(deprecated) import_settings.demand_actuals_load_mode — consulted only without a scenario — >
step default.
2.T — Step-by-step test walkthrough¶
Import verification — the guarded promotion from staging into the core tables.
| # | Where to look / what to click | You should see |
|---|---|---|
| 1 | Import card → Configure | the modal shows the linked import scenario (or None) — the object list and load modes |
| 2 | ▶ Run Import (scenario) | the staging-fitness guard runs FIRST; then per-object staged → loaded → rejected counts |
| 3 | Open the run in the history → rejected drill-down | rejected samples list the reason per row (unresolvable xuid, bad key) — counted, never guessed |
| 4 | Empty-staging guard test: point a truncate_replace object at empty staging → Run | the run REFUSES with the empty-staging error — stale state is never silently imported |
| 5 | Master Data grids (Items, Sites, Demand Order) | the promoted rows are present; demand lines landed at order grain with order_id/line_id |
| 6 | Run all (ad-hoc) (with no import scenario picked) | every step loads at its step-default mode; the fitness guard is OFF — the legacy path (partial runs are scripts-only, 2.D) |
| 7 | Audit (/audit + run history) |
the run recorded with run_kind='import', per-object counts, duration |

The Import process card with its linked import scenario chip.

Per-object counts and the rejected-rows drill-down of a real run.