farseer-cli 1.13.0 → 1.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/README.md +23 -8
  2. package/dist/commands/config.js +4 -3
  3. package/dist/commands/config.js.map +2 -2
  4. package/dist/commands/install.js +5 -0
  5. package/dist/commands/install.js.map +2 -2
  6. package/dist/commands/login.js +2 -2
  7. package/dist/commands/login.js.map +2 -2
  8. package/dist/commands/pipeline.js +158 -0
  9. package/dist/commands/pipeline.js.map +7 -0
  10. package/dist/commands/pull.js +2 -1
  11. package/dist/commands/pull.js.map +2 -2
  12. package/dist/commands/run.js +9 -0
  13. package/dist/commands/run.js.map +2 -2
  14. package/dist/commands/variables.js +17 -8
  15. package/dist/commands/variables.js.map +2 -2
  16. package/dist/index.js +45 -46
  17. package/dist/index.js.map +2 -2
  18. package/dist/mcp/prompts/workflows.js +13 -68
  19. package/dist/mcp/prompts/workflows.js.map +2 -2
  20. package/dist/mcp/resources/documentation.js +14 -0
  21. package/dist/mcp/resources/documentation.js.map +2 -2
  22. package/dist/mcp/server.js +14 -2
  23. package/dist/mcp/server.js.map +2 -2
  24. package/dist/mcp/skills.js +59 -0
  25. package/dist/mcp/skills.js.map +7 -0
  26. package/dist/mcp/tools/appTools.js +4 -0
  27. package/dist/mcp/tools/appTools.js.map +2 -2
  28. package/dist/mcp/tools/authTools.js +5 -3
  29. package/dist/mcp/tools/authTools.js.map +2 -2
  30. package/dist/mcp/tools/cellTools.js +3 -2
  31. package/dist/mcp/tools/cellTools.js.map +2 -2
  32. package/dist/mcp/tools/dashboardTools.js +23 -18
  33. package/dist/mcp/tools/dashboardTools.js.map +2 -2
  34. package/dist/mcp/tools/dataTools.js +16 -12
  35. package/dist/mcp/tools/dataTools.js.map +2 -2
  36. package/dist/mcp/tools/folderTools.js +5 -4
  37. package/dist/mcp/tools/folderTools.js.map +2 -2
  38. package/dist/mcp/tools/modelTools.js +33 -58
  39. package/dist/mcp/tools/modelTools.js.map +2 -2
  40. package/dist/mcp/tools/pipelineContract.js +320 -0
  41. package/dist/mcp/tools/pipelineContract.js.map +7 -0
  42. package/dist/mcp/tools/pipelineTools.js +111 -0
  43. package/dist/mcp/tools/pipelineTools.js.map +7 -0
  44. package/dist/mcp/tools/runTools.js +10 -3
  45. package/dist/mcp/tools/runTools.js.map +2 -2
  46. package/dist/mcp/tools/sheetTools.js +21 -17
  47. package/dist/mcp/tools/sheetTools.js.map +2 -2
  48. package/dist/mcp/tools/syncTools.js +15 -5
  49. package/dist/mcp/tools/syncTools.js.map +2 -2
  50. package/dist/mcp/utils/registerTool.js +32 -0
  51. package/dist/mcp/utils/registerTool.js.map +7 -0
  52. package/dist/pipeline/compatibility.js +53 -0
  53. package/dist/pipeline/compatibility.js.map +7 -0
  54. package/dist/pipeline/connect.js +139 -0
  55. package/dist/pipeline/connect.js.map +7 -0
  56. package/dist/pipeline/create.js +158 -0
  57. package/dist/pipeline/create.js.map +7 -0
  58. package/dist/pipeline/errors.js +45 -0
  59. package/dist/pipeline/errors.js.map +7 -0
  60. package/dist/pipeline/generated-reference.json +115 -0
  61. package/dist/pipeline/guide.js +33 -0
  62. package/dist/pipeline/guide.js.map +7 -0
  63. package/dist/pipeline/init.js +204 -0
  64. package/dist/pipeline/init.js.map +7 -0
  65. package/dist/pipeline/operations.js +106 -0
  66. package/dist/pipeline/operations.js.map +7 -0
  67. package/dist/pipeline/query.js +121 -0
  68. package/dist/pipeline/query.js.map +7 -0
  69. package/dist/pipeline/queryDownloads.js +72 -0
  70. package/dist/pipeline/queryDownloads.js.map +7 -0
  71. package/dist/pipeline/queryWorker.js +96 -0
  72. package/dist/pipeline/queryWorker.js.map +7 -0
  73. package/dist/pipeline/readiness.js +62 -0
  74. package/dist/pipeline/readiness.js.map +7 -0
  75. package/dist/pipeline/reference.js +73 -0
  76. package/dist/pipeline/reference.js.map +7 -0
  77. package/dist/pipeline/requests.js +122 -0
  78. package/dist/pipeline/requests.js.map +7 -0
  79. package/dist/pipeline/runArguments.js +68 -0
  80. package/dist/pipeline/runArguments.js.map +7 -0
  81. package/dist/pipeline/runtime.js +106 -0
  82. package/dist/pipeline/runtime.js.map +7 -0
  83. package/dist/pipeline/service.js +1027 -0
  84. package/dist/pipeline/service.js.map +7 -0
  85. package/dist/services/agentApprovalFetch.js +86 -0
  86. package/dist/services/agentApprovalFetch.js.map +7 -0
  87. package/dist/services/appSyncService.js.map +1 -1
  88. package/dist/services/configService.js +40 -4
  89. package/dist/services/configService.js.map +2 -2
  90. package/dist/services/credentials.js +2 -0
  91. package/dist/services/credentials.js.map +2 -2
  92. package/dist/services/farseerService.js +33 -3
  93. package/dist/services/farseerService.js.map +2 -2
  94. package/dist/services/modelExport.js.map +1 -1
  95. package/dist/services/preflight.js +4 -0
  96. package/dist/services/preflight.js.map +2 -2
  97. package/dist/services/syncService.js +6 -0
  98. package/dist/services/syncService.js.map +2 -2
  99. package/dist/skills/pipeline.js +71 -0
  100. package/dist/skills/pipeline.js.map +7 -0
  101. package/dist/utils/agentSandbox.js +35 -0
  102. package/dist/utils/agentSandbox.js.map +7 -0
  103. package/dist/utils/helpers.js +2 -1
  104. package/dist/utils/helpers.js.map +2 -2
  105. package/dist/utils/variableValues.js +78 -0
  106. package/dist/utils/variableValues.js.map +7 -0
  107. package/docs/pipeline-client-guide.md +67 -0
  108. package/docs/pipeline-reference.md +2064 -0
  109. package/package.json +5 -1
  110. package/skills/pipeline-authoring/SKILL.md +95 -0
  111. package/skills/pipeline-authoring/practices.md +325 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "farseer-cli",
3
- "version": "1.13.0",
3
+ "version": "1.14.2",
4
4
  "description": "CLI tool for syncing Farseer App scripts between local folder and Farseer instances",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -9,11 +9,13 @@
9
9
  "files": [
10
10
  "dist",
11
11
  "docs",
12
+ "skills",
12
13
  "README.md",
13
14
  "LICENSE"
14
15
  ],
15
16
  "scripts": {
16
17
  "build": "node build.js",
18
+ "docs:check": "node scripts/check-pipeline-docs.js",
17
19
  "typecheck": "tsc --noEmit",
18
20
  "build:tsc": "tsc",
19
21
  "lint": "eslint src --ext .ts",
@@ -47,12 +49,14 @@
47
49
  "node": ">=20.0.0"
48
50
  },
49
51
  "dependencies": {
52
+ "@duckdb/node-api": "1.5.4-r.1",
50
53
  "@modelcontextprotocol/sdk": "^1.0.0",
51
54
  "chalk": "^4.1.2",
52
55
  "commander": "^11.1.0",
53
56
  "diff": "^5.1.0",
54
57
  "farseer-client": "https://storage.googleapis.com/farseer-remote-jobs-results/farseer-client/release-1.8.12.tar",
55
58
  "inquirer": "^8.2.6",
59
+ "js-yaml": "4.1.1",
56
60
  "zod": "^3.25.0"
57
61
  },
58
62
  "devDependencies": {
@@ -0,0 +1,95 @@
1
+ ---
2
+ name: pipeline-authoring
3
+ description: Author all new repeatable Farseer data pipelines with Simple Pipelines, and maintain existing Simple Pipelines. Preserve existing TypeScript apps through the app tools; migration requires an explicit migration request.
4
+ metadata:
5
+ version: "1"
6
+ minimum-cli: "1.14.2"
7
+ engine-profile: "2.9"
8
+ ---
9
+
10
+ # Pipeline authoring
11
+
12
+ Pipeline authoring for simple-pipelines 2.9, the engine line in the runner image this CLI was released with. Patch releases keep the grammar, so any 2.9 engine runs what this skill describes.
13
+
14
+ ## What this is
15
+
16
+ A pipeline is a folder of YAML dataset definitions plus a `main.py` entrypoint, run as a prepared job on the tenant; it extracts from sources, transforms with inline SQL or Python, and loads cells into the existing model. Use the tenant-bound `farseer_pipeline` MCP tool or the equivalent `farseer pipeline` CLI commands; both expose the same operations (`guide`, `init`, `check`, `pull`, `push`, `run`, `runs`, `inspect`, `inspect-import`, `query`, `versions`, `restore`).
17
+
18
+ All new repeatable pipelines must use Simple Pipelines, even when TypeScript is requested. Before choosing a workflow, inspect the relevant existing apps and source with `farseer_list_apps`, `farseer_get_app` and `farseer_pull`. Preserve existing TypeScript apps: inspect, run, debug and make targeted fixes through the app tools without requiring the user to explicitly say TypeScript. A request to fix or extend an existing import does not authorize replacing its source folder, entrypoint, runner image or schedule, or creating a duplicate pipeline. Migration requires an explicit migration request. An existing TypeScript app is not missing Simple Pipelines setup; do not reconfigure it to make pipeline commands pass. Apply this per app on mixed tenants. Requested one-off direct imports remain supported, but do not authorize new TypeScript pipelines.
19
+
20
+ If a required Simple Pipelines job, profile or source connection is missing, explain the missing setup; do not implement a TypeScript pipeline or direct import as a fallback. Loading this skill does not submit a run or grant tenant permissions; `operation=guide, topic=method` returns these same instructions, so there is no need to fetch the method again once the skill is loaded. Before designing a pipeline, read `topic=practices` (CLI: `farseer pipeline guide --topic practices`): how a Farseer data engineer designs one, from the target cells back to the source, and the import behaviours that turn a plausible pipeline into wrong numbers. Then read `topic=grammar` (CLI: `farseer pipeline guide --topic grammar`) and the named grammar topics it links to. The bundled reference identifies its supported runtime and does not discover a job's engine; if compatibility requires an update, install the matching CLI build and restart the MCP connection.
21
+
22
+ ## First pipeline in six steps
23
+
24
+ 1. `init name=<folder>` (CLI: `farseer pipeline init <org> <tenant> --new <name>`) creates the local folder under files/<name>/ (`main.py`, an empty `Models/` and `Code/`), uploads `main.py` into a new source folder Files/<name>, creates a job named <name> with that folder, `main.py` as entrypoint and the runner-python-simple-pipelines image this CLI was released with, then writes the profile farseer-apps/<tenant>/.pipelines/<name>.json. If files/<name>/ already exists locally with a `main.py`, init adopts it instead: it uploads the folder's source files as they are and writes no starter.
25
+ 2. Write the YAML under `Models/`, one file per dataset, named after its `name:`. The guide topics `FarseerFilesExtractConfig`, `TransformConfig` and `LoadCellsConfig` each end with a complete example the engine accepts; start from those. Discover real source, dataset and model names with the existing tools first.
26
+ 3. Give the job its secrets. A source that needs a key or password (Business Central, a private Drive folder, SharePoint) reads it from a secret-typed job argument and the YAML names it as `{{ pipeline_args.NAME }}`; never write the value into YAML, the engine refuses `farseer_credentials` blocks. init creates the job with no arguments, so add each one with `farseer_configure_app` (`arguments: [{name, dataType: "string", secret: true, defaultValue: "<the value>"}]`) or in the web app before the first real run. The value is the argument's `defaultValue`; reads and run logs show it masked. Setting it through the tool puts the value in this conversation, so when the client prefers, ask the admin to type it into the web app instead. `check` lists every `pipeline_args.NAME` the YAML uses that the job does not define.
27
+ 4. `push` uploads the edited files.
28
+ 5. `run` submits one run and returns a run UUID receipt. To change a job argument for one run, pass it by name: `args: ["MONTH=2026-08"]` (CLI: `--arg MONTH=2026-08`, repeatable). Arguments you do not name keep the job's default; a name the job does not declare, a bare value, an empty value or a fixed argument is refused before anything is sent, and the receipt lists the arguments it used, secrets masked.
29
+ 6. `inspect` reads that run's logs and markers. Then read the output with `query` on the output dataset, and what each load committed with `inspect-import` on the import ID that `loads` reports. Never check a load with a model or variable export: it pulls whole variables out of the tenant's in-memory model.
30
+
31
+ With one profile every operation finds it on its own. With several pipelines on a tenant, select one with `pipeline=<name>` (CLI: `--pipeline <name>`); `profile=<path>` names a profile file explicitly. `init jobId=<id>` (CLI: `farseer pipeline init <org> <tenant> <jobId>`) attaches to a job somebody already prepared: it derives the profile from the job (source folder, entrypoint, image as configured, dataset IDs matched by qualified name), reads only and changes nothing remotely. Either way, the setup record init leaves blank must be filled by the owner, then run `check`.
32
+
33
+ ## The loop
34
+
35
+ Edit, `push`, `run`, `inspect`. `run` requires pushed files: it compares every local source file with the remote one and refuses with the list of unsynced files. Pull and reconcile before editing, and after an interrupted push. The sync scope is `main.py`, declared configuration, and every `.py`, `.yaml`, `.yml`, `.json` or `.md` file under `Models/` and `Code/`, excluding `Data/`. Keep the prepared job fixed. A scheduled job is allowed, but on it a push is a deploy: the source you push runs at the next scheduled start, so verify with `run` before then, or pause the schedule for multi-step edits. init records the schedule, and `check` fails with the restore command if it was removed or changed since; rerun `init jobId=<id> force=true` only when the change was intended. `run` refuses while any run of the job is queued or running, this workspace's, a colleague's or the schedule's, and names it. It reads the run history just before submitting, so two authors starting at the same moment can both get through: nothing on the backend limits runs. A run that stays queued and whose log shows it never started (`inspect uuid=<uuid>`) may be stuck, or may be waiting behind other jobs in the runner's queue, which looks the same. End it yourself with `terminate uuid=<uuid>` (CLI: `farseer pipeline terminate --uuid <uuid>`) only when this workspace started it (`runs` shows `receipt: true`), and tell the user which run you ended and why. Any other run is the schedule's or a colleague's: ask the user before terminating it. `terminate` refuses a running run: stopping work part-way is a person's call, made with Stop in the web app. A tenant can hold several pipelines, one folder each; authors share the same resources, with no per-author folders, ownership sessions, heartbeats, editing leases or waiting queue. Coordinate edits with colleagues and avoid changing shared source files while a run is queued or running; ordinary push and direct API writes keep their existing behavior and can race. This is ordinary tenant access, not a Python sandbox.
36
+
37
+ A refused `run` accepted no new run: read the reason, fix what it names or tell the user; never loop or switch to the ordinary CLI or API to retry.
38
+
39
+ Iterate without runs where you can, because every run reads the sources again. Run the extracts once so they publish, then test each SQL transform with `query`, binding its inputs to those published extract versions, until it returns what you expect; only then push and run. Ask for shapes, not rows: `DESCRIBE <your SELECT>` shows the column types the run will produce, and `COUNT`, `SUM` and `GROUP BY` check totals and duplicates. Query results go to the model provider, so prefer these over reading raw rows. A Python transform cannot be tested this way, so keep its logic small and check its output with `query` after the run. Run `check` after every edit as well, knowing what it covers: the job, its image, the arguments the YAML names and whether this CLI is current. It does not validate the YAML against the grammar, look up model names or check export folders; the run's preflight does that within seconds, before any source is read.
40
+
41
+ Submit once after sync and save the UUID receipt. Inspect that UUID after reconnect; never select the latest run. Each API call, including authentication, sync and reading the response body, has a 30-second deadline. Tool cancellation, connection close or Ctrl-C aborts the network requests but does not undo server writes or cancel an accepted run. A lost response is unconfirmed: the receipt is saved before the request and survives a client restart even when the run finished quickly, and requests with an uncertain outcome are never repeated automatically. Recovery is a terminal step for the author, not an MCP operation: `farseer pipeline recover` clears the receipt when the job's history has no run since the submission (the backend records an admitted run before dispatching it, so none means none was accepted), and otherwise lists the runs in that window and clears nothing; `recover --uuid <uuid>` attaches the run that is this submission. A stale local operation lock needs the direct CLI `unlock` after its process has stopped. A queued acceptance with no runner observation needs operator investigation, not a timeout-based retry.
42
+
43
+ ## Reading results
44
+
45
+ `inspect` pages the raw run logs with `nextOffset`: pass it back to read on, and while the run is queued or running it is where to resume, even when no new lines have arrived yet; it is null only once the run has ended and no lines remain. Its `observations` and `loads` always cover the whole log: `loads` lists every import each load ran (one per `cells` entry, in the order they ran) with its import ID and last outcome (`commit_confirmed`, `not_committed` or `unknown`), so one call answers whether, and how much of, the model changed. Its `skippedOutputs` lists, from the whole log, every load or export the run skipped and why, with an `attention` sentence when any were: an optional source that is missing skips everything that depends on it and the run still finishes successfully, so while building a pipeline a skipped load or export is a defect to fix, not a pass. Its `engine` field compares the engine line (major.minor) the run reported at startup with the one this CLI's grammar describes; on `mismatch` stop and tell the setup owner before trusting the grammar, and on `unobserved` the run has not logged its start marker yet. Markers name what happened: `dataset_candidate` and `dataset_completed` identify the versions a run wrote (a run that fails cancels the ones it did not publish, and `query` refuses a cancelled version), `dataset_published` records the version actually replaced, and `dataset_read_access` records an exact read grant or selected snapshot, not proof that every row was consumed. `import_observation` distinguishes `created`, `commit_attempted`, `commit_confirmed`, `not_committed` and `unknown`, and `import_undone` lists the earlier imports `undo_previous` removed after the run committed, and any it failed to remove. Unavailable history must be reported, never substituted with current data.
46
+
47
+ `runs` lists the profile job's runs from the job history, newest first, 20 by default (`limit`). Each entry carries the run `uuid`, `status`, `startedAt`, `finishedAt` when the backend reports it, and `receipt: true` when a local receipt names that UUID. Use it to find the UUID to inspect or recover after a lost response; it never chooses a run for you.
48
+
49
+ `query` takes bindings `[{name, datasetId, versionId}]` and a single SELECT (WITH allowed); bind complete manifests to read immutable dataset versions, while a file binding `{name, file}` reads the current mutable Farseer File under `Data/` and is labeled as such, with no history guarantee. The worker downloads fixed signed HTTPS inputs to private temporary files (with an agent turn key the CLI fetches them through the API instead, because an agent sandbox can reach only the API; 256 MiB total across all bindings), then runs DuckDB with 256 MB memory, 256 MB spill, two threads, 30 seconds total, at most 1,000 rows and 256 KiB of results; it gets no tenant credentials, loads no HTTP extension, cannot reach other files or URLs or change settings, is killed on cancellation or timeout, and these engine limits (not an OS memory sandbox) are fixed in this build. SQL filters do not reduce the full download, so use a smaller admitted output when capacity or network speed is insufficient; truncated results are samples, so use COUNT or SUM for whole-input claims.
50
+
51
+ `inspect-import` reads the owning import service for a load's import ID: CREATED can still have a commit in flight, and COMMITED confirms completion. `versions` lists a dataset's retained versions. `restore(datasetId, versionId, expectedCurrentVersionId)` repairs a wrong publication of a dataset: first inspect versions and run effects, coordinate with colleagues and confirm the run has stopped. Restore selects an eligible retained publication and moves its reading position in the same transaction, cancels outstanding unpublished candidates, and refuses a stale expected current version; if its response is lost, inspect dataset state before any next action. Restore covers datasets only, not model loads: it does not reverse imports, recalculation or exports, so reconcile model results separately through existing model access. For an incremental recipe, fix the definition and reprocess from the restored cursor, then verify counts, duplicate keys and totals; historical source replay must be supported and unchanged.
52
+
53
+ ## Setup facts
54
+
55
+ The backend records each run before dispatch and answers with its run UUID. The tenant's jobrunner must be 3.6.0 or newer: an older one cannot keep the run id the backend assigns, so the backend refuses to send it the run and says so, and no run starts. Reading datasets, their versions and download links needs the right to run remote jobs (CLASS.REMOTE_JOB.RUN), which `init`, `check`, `query` and `versions` rely on; `restore` needs the right to update jobs (CLASS.REMOTE_JOB.UPDATE); creating or deleting datasets stays with super users and the runner. A permission refusal from `check` is a setup issue to report to the setup owner.
56
+
57
+ `check` reads the prepared job, its runner image, whether a newer CLI was released with the tenant's runner image (`cli-version`, pending means update before authoring), and the output manifests, then probes the first Parquet file using signed HTTPS access, or through the API when the CLI runs with an agent turn key, because an agent sandbox can reach only the API. This CLI authors for exactly one engine: the one inside the runner image it was released with. Only jobs already using a Simple Pipelines runner are eligible for image pinning. TypeScript, other runner families and an unknown or inherited image are refused by init, source sync and run; use the existing app tools and preserve the app. The CLI never changes a job's image on its own. A Simple Pipelines job on an older released image is reported as failed: `run`, `pull` and reads still work on its own image, but `push` is refused (`RUNTIME_UPGRADE_REQUIRED`) until the job is upgraded with `upgrade-runtime` (CLI: `farseer pipeline upgrade-runtime`), which moves it to this CLI's image and reports where it moved from. Upgrading changes the engine for everyone on that tenant and, on a scheduled job, for the next scheduled run, so ask the user before upgrading, then `run` once and fix whatever the newer engine's preflight rejects. A job on a moving tag such as `latest`, or on a digest, is reported as pending and left as it is: `upgrade-runtime` refuses it, and each run reports the engine it started on (`engine` in `inspect`). A job on a newer released image is reported as pending: it runs and accepts pushes, but update the CLI to author what the newer engine added. No job is ever moved down. A dataset declared under `Models/` is created by the engine on the first run, so init and check report a dataset that does not exist yet as pending, not as an error; after the first run, rerun `init jobId=<id> force=true` to record the new dataset IDs (a rerun for the same job and folder keeps the setup record, declared config files and author), and the profile's `datasetIds` lists the outputs recorded so far. No published version means read verification stays pending until the first prepared run. The setup record (owner, evidence, checkedAt, retentionDays, otherWritersExcluded=true, runtimeVerified=true) is the owner's statement, not an API-verified fact: do not invent it, and reconfirm it after setup changes. `readyForAcceptance` does not establish source replay, reconciliation or real-client acceptance.
58
+
59
+ ## Authoring rules
60
+
61
+ Extract: one dataset per source extraction, separate from the transformation that reshapes it. Read another pipeline's or this pipeline's published dataset with `extract.type: farseer`, `source: datasets` and the dataset's `qualified_name` (optionally pinned to a `version_id`). Never add a `farseer_credentials` block; the pipeline always uses the tenant it runs in.
62
+
63
+ Transform: choose SQL first (`engine: duckdb` with inline `transform.query`, never a SQL file), then `engine: ibis` with an `@ibis_transform` script when the logic needs Python to compose, and `engine: python` (`@transform`, pandas) only for work with no lazy form, because it is the one surface that holds whole frames in memory. Always write `engine:`; the default is `python`. Section 3 of `topic=practices` has the rules. A script transform names its `Code/` script in `transform.script`; missing code, compile errors and invalid definitions fail before extraction when the pipeline policy is enabled. Declare `deps`, add quality checks, and reconcile the agreed business scope. Folder names under `Models/` become dataset namespaces. Output versions are candidates until published, failed quality checks do not publish the failed candidate, and publication is per dataset, so a later failure can leave earlier effects in place.
64
+
65
+ Load: the engine's full surface is available, with `load.target: farseer` and `load.farseer.cells[].source_dataset` naming a dependency. Each `mapping.variables[]` entry has `source_column`, `target_variable` and `fixed_dimension_members`; `mapping.dimension_tables` maps a column onto a dimension. `options.overwrite_cells: true` repairs the same coordinates on a rerun; it does not erase omitted rows or old mappings. `undo_previous: true` (which requires at least one `labels` entry) undoes, after the new import commits, every earlier import job that carries all the same labels, so rows that left the source leave the model; a failed undo is logged as a warning, not raised. `create_missing_members: true` lets the import job create members that mapped columns name but the model lacks; it does not create `fixed_dimension_members`, which must already exist or be written by a dimension load earlier in the run. On a production model a created member is a permanent change, so say so before running. Dimension-table loads and exports are allowed. Statically, the only hard refusals are credentials in YAML and SQL files.
66
+
67
+ Before reading any source, the run also checks the pipeline against the tenant and reports every problem at once: each load's variable exists; its mapped and fixed dimension tables are dimensions of that variable; each fixed member exists; a `date` mapping needs a time dimension (Years, Half years, Quarters or Months) on the variable, because otherwise every dated row for the same members is added into one cell; a variables extract's dimensions and filters belong to its variable; a Files export's folder exists under the tenant's Files; and `undo_previous` can list earlier imports. A mismatch costs a run start but no extraction. Member names inside mapped columns are row values, so only the import checks those. Discover the model first all the same.
68
+
69
+ `PipelinePolicy()` takes no arguments. Pipelines written for the pilot engine used `PipelinePolicy("Versions", "Actual")`, which now fails at start with `TypeError: PipelinePolicy.__init__() takes 1 positional argument`; replace it with `PipelinePolicy()`.
70
+
71
+ Starter `main.py`, exactly what init writes:
72
+
73
+ ```python
74
+ from farseer_simple_pipelines.runner import run_pipeline
75
+ from farseer_simple_pipelines.storage import StoreType
76
+ from farseer_simple_pipelines.authoring import PipelinePolicy
77
+ run_pipeline(store_type=StoreType.DATASETS, pipeline_policy=PipelinePolicy(), experimental__emit_pipeline_visualization_markers=True)
78
+ ```
79
+
80
+ Incremental recipes are not the default. They need `StoreType.ICEBERG` in `main.py`, which applies to the whole pipeline, so give an incremental source its own pipeline folder and read it downstream with `source: datasets`. Section 8 of `topic=practices` covers choosing the store, `overwrite`, `append` or `upsert`, qualifying a cursor, and rebuilding safely; read it before declaring `cursor_column`, `write_mode` or `merge_keys`, because the store, the format and the merge keys of a dataset are fixed once it exists.
81
+
82
+ ## Moving a pipeline to another tenant
83
+
84
+ A pipeline is promoted the way every tenant file is: copied, then set up on the target. There is no promote command.
85
+
86
+ 1. Copy only `files/<name>/` from the source tenant's folder into the target tenant's folder. Never copy `.pipelines/` or `.pipeline-runs/`; the profile names the source tenant's job and every command refuses it with an explanation.
87
+ 2. Bind to the target tenant (a Mindseer instance focus, or a server started with its `FARSEER_TENANT`) and run `init name=<name>`. It adopts the copied folder, uploads it, creates the job on this CLI's image and writes a fresh profile.
88
+ 3. Re-create the secret arguments on the new job (step 3 above). Secrets never travel between tenants.
89
+ 4. Check the names. Variables, members and dimension tables the loads target must exist on the target model, and the source must be the target's own data (a different folder id or company than the sandbox copy). The first run's tenant check refuses a missing variable, table or fixed member before reading any source; it cannot tell whether the source is the right one.
90
+ 5. `run`, then `inspect`, then `init jobId=<id> force=true` so the profile records the datasets the first run created.
91
+ 6. Set a schedule (in the web app or with `farseer_configure_app`) once the first run is verified, then run `init jobId=<id> force=true` so the profile records it.
92
+
93
+ On a production tenant, state the effects of step 5 before running: real cells, and real members if `create_missing_members` is set. A run never changes the job's image; only `upgrade-runtime` does, as its own step.
94
+
95
+ Source provisioning, self-service job creation beyond init, broad runtime compatibility, mutable Farseer Files history, automatic whole-run rollback, tenant editing sessions, mutation guards, abandoned-session recovery, finer locks and a fair or durable queue remain deferred. The legacy separate-workspace experiment is retained only for regression tests.
@@ -0,0 +1,325 @@
1
+ # How simple-pipelines is meant to be written
2
+
3
+ Read this before designing a pipeline. The method gives the loop and the grammar topics give every field. This page gives the house style: which responsibility lives in which part of a pipeline, how datasets are layered and named, which transform surface to choose, and how to write schemas. A pipeline that produces the right numbers but ignores this is still wrong, because the next engineer, reviewer or agent cannot reason about it. Each rule says why, so you can tell when it does not apply.
4
+
5
+ ## 1. What goes where
6
+
7
+ A pipeline is three things in a folder: `main.py`, `Models/` (one YAML per dataset) and `Code/` (scripts). Every responsibility has one home.
8
+
9
+ | Part | Holds | Never holds |
10
+ |---|---|---|
11
+ | `main.py` | Argument checks and canonical spellings, then one `run_pipeline()` call with `store_type=StoreType.DATASETS` and `pipeline_policy=PipelinePolicy()` | Data reads, business logic, API calls, starting other jobs |
12
+ | `Models/<layer>/<name>.yaml` | One dataset: its step, `deps`, `schema`, `quality_rules`, and its load or export mapping. Or one `expand:` fan-out over one axis | Copies per company or period; two run cadences in one folder (use two pipeline folders) |
13
+ | `extract` block | How to reach the source: connector, the source-side filter and columns, `optional` for a source that may genuinely be missing | Reshaping; reading another pipeline's output through `deps`; credentials |
14
+ | `parse` block | How to read the bytes: format, encoding, separator, decimal, header, start row, positional columns | What the values should be: no fixing, mapping or filtering |
15
+ | `schema` | The dataset's column contract: every column it keeps, with `type` and `not_null` | Reshaping |
16
+ | `quality_rules` | What the values must mean, on extract and transform steps | Comparisons between datasets (write a reconciliation transform) |
17
+ | SQL transform (`engine: duckdb`, `query`) | All set-based work: filter, join, map, aggregate, reshape, final casts | Procedural row-by-row logic |
18
+ | `@ibis_transform` (`engine: ibis`, `script`) | Logic that needs Python to compose, still streaming | DataFrames, `.to_pandas()`, `.execute()` |
19
+ | `@transform` (`engine: python`, `script`) | Only work with no lazy form | Set-based work; I/O, environment reads, the clock |
20
+ | `Code/` | One script per transform function; a function shared by many datasets through `transform.function` and `transform.args` | Helper modules imported across scripts: each script runs on its own |
21
+ | `load` block | Column-to-model mapping, labels, import options | Any logic. To change a number, change a transform |
22
+ | `export` block | File target, format, conflict behaviour | Shaping |
23
+ | Files | Mapping tables, read with `source: files` and joined in SQL | |
24
+ | The model | Member lists, read with `source: dimensions` to check codes before loading | Guesses: every name comes from the model tools |
25
+ | Job arguments | The run's slice (period, company), fan-out lists, secrets as secret arguments | Credentials in YAML; truthiness tests (every value is a string) |
26
+
27
+ ## 2. Layers and names
28
+
29
+ Start from the target. Before any YAML, write down each variable the pipeline fills, all of its dimensions (Versions and time included), its grain, and what one value means. The gold layer's columns follow from that.
30
+
31
+ | Folder | Holds | Rule |
32
+ |---|---|---|
33
+ | `Models/bronze/` | Extract-only datasets, one per source extraction | Lands the source with its own `schema` and structural rules and nothing else. No transform unless the data needs work |
34
+ | `Models/silver/` | Conformed rows | Codes cleaned, types settled, mappings joined, and an explicit flag on every row a mapping missed |
35
+ | `Models/gold/` | One row per target cell | Columns are exactly what the load maps: dimension columns, date or time columns, value columns, and any `custom_fields` |
36
+ | `Models/load/` | Load steps | Thin: they map `gold` columns, nothing else |
37
+
38
+ - **Why layer.** Extracting is the slow, metered part. Each extract runs once, and every transform after it can be tested with `query` against the published extract. Rules at each boundary localise a fault to one step. Because the load is thin, the dataset you reconcile is exactly what was imported.
39
+ - **`name:` equals the file name, and the folder becomes the namespace:** `Models/bronze/erp_sales_lines.yaml` is `bronze.erp_sales_lines`.
40
+ - **Qualified names are shared by every pipeline on the tenant.** Name datasets after their subject (`bronze.erp_sales_lines`, not `bronze.lines`), so two pipelines never write the same dataset.
41
+ - **Leaf names must be unique within one step's `deps`.** SQL sees each dependency as a view named by its leaf, and Python sees it as a parameter named by its leaf.
42
+ - **Read another pipeline's output** with `extract.type: farseer`, `source: datasets` and its `qualified_name`. It reads the last published version, and there is no ordering between pipelines.
43
+ - **Keep `StoreType.DATASETS`** unless the pipeline accumulates data (section 8). `FARSEER_FILES`, the engine default, publishes on write and keeps no versions.
44
+
45
+ ## 3. Transforms: SQL, then ibis, then pandas
46
+
47
+ There is one compute engine, DuckDB. The `engine:` field chooses how you author against it, and with that how much memory the step may take. Choose in this order:
48
+
49
+ 1. **SQL** (`engine: duckdb` with an inline `query`) for anything set-based: filters, joins, mappings, aggregation, reshaping, allocation, carry-forward. It streams, it is plain to review, and it is the only surface you can test with `query` before a run. Write the query inline; authored pipelines refuse `sql_file`.
50
+ 2. **ibis** (`engine: ibis` with a script) when the logic needs Python to compose. Examples: a loop over a list of columns, expressions built by a helper, or one function serving many datasets with different `args`. It streams like SQL.
51
+ 3. **pandas** (`engine: python` with a script) only when the work has no lazy form: arbitrary row-by-row Python, an iterative algorithm, or a call into a Python library. It is the only surface that holds every input and its output in memory, so the data must fit the container.
52
+
53
+ **Always write `engine:`.** The engine's default is `python`, the last resort, so a transform without it silently becomes a pandas step.
54
+
55
+ ```python
56
+ # Code/silver/sales_lines_clean.py, for engine: ibis with
57
+ # transform: {engine: ibis, script: sales_lines_clean.py, args: {code_columns: [product_code, region]}}
58
+ from farseer_simple_pipelines import ibis_transform
59
+
60
+ @ibis_transform
61
+ def sales_lines_clean(erp_sales_lines, *, args):
62
+ t = erp_sales_lines
63
+ for column in args["code_columns"]:
64
+ t = t.mutate(**{column: t[column].strip().upper()})
65
+ return t.order_by(args["code_columns"])
66
+ ```
67
+
68
+ **Rules for every script surface:**
69
+ - The function is named after the dataset's leaf, unless `transform.function` names another.
70
+ - Its positional parameters are the dependency leaf names, in `deps` order. That signature is the dependency contract, so there is no `**deps` catch-all.
71
+ - It may take keyword-only `args` (from `transform.args`) and `logger`.
72
+ - It must be pure: no I/O, no environment, no current time, no randomness. The runner may call it again on a retry.
73
+ - The script lives under `Code/`, mirroring the dataset's folder under `Models/`.
74
+
75
+ | | SQL | ibis | pandas |
76
+ |---|---|---|---|
77
+ | Memory | Bounded, spills to disk | Bounded, spills to disk | Whole frames in memory |
78
+ | Row order | Unstable without `ORDER BY` | Unstable without `.order_by()` | Stable |
79
+ | Testable with `query` before a run | Yes | No | No |
80
+ | Watch out for | Cast `DECIMAL` (`SUM(x)::DOUBLE`) and `DATE`; arguments are pasted into the text | Integer sums become decimals, so cast; untyped null columns are refused; returning a DataFrame is refused | Call `reset_index()` after `groupby` or the keys are dropped; time zones become UTC |
81
+
82
+ Use a `LEFT JOIN` to a mapping and flag the rows that found no match. An `INNER JOIN` drops them silently. Keep mappings as data, a Files table or a model attribute, rather than a `CASE` copied into several queries.
83
+
84
+ ## 4. Writing schemas
85
+
86
+ Declare a `schema:` on every extract and transform, listing every column the dataset keeps, each with a `type`. The schema is the dataset's contract with whatever reads it. The one exception is a bronze extract that deliberately captures a source whole.
87
+
88
+ - **Types:** `str`, `int`, `float`, `datetime`, `bool`, `list[str]`. There is no date or decimal type. A `DECIMAL` column fails `float` and a `DATE` column fails `datetime`, so cast in SQL.
89
+ - **Cast or check.** For file payloads (CSV, JSON, Excel) the declared type is a cast: `type: str` keeps `0042` as text. For SQL, Parquet, API and Farseer sources, and for every transform, the type is only a check, so cast in the query.
90
+ - **`not_null` is separate from `type`.** Built-in quality checks let nulls pass, so pair them with `not_null`. NaN is not NULL to these checks.
91
+ - **Undeclared columns are not dropped.** They land with guessed types, except in JSON, where they are dropped with a warning. Select exactly the columns you want in the query or with the extract's column selection.
92
+ - **Dates.** There is no format declaration; the reader guesses one format per column from its first value. Keep dates ISO at the source. For an ambiguous `dd/mm/yyyy` source, declare the column `str` and parse it in SQL with an explicit `strptime` pattern.
93
+ - **Codes are `str`,** always. Declare them, even when the source looks numeric.
94
+ A gold dataset written the intended way, with SQL, explicit casts, a full schema and its load contract:
95
+
96
+ ```yaml
97
+ # Models/gold/revenue_cells.yaml
98
+ name: revenue_cells
99
+ type: transform
100
+ deps: [silver.sales_lines]
101
+ transform:
102
+ engine: duckdb
103
+ query: |
104
+ SELECT product_code, region, strftime(month_start, '%Y-%m-%d') AS month,
105
+ SUM(net_amount)::DOUBLE AS revenue
106
+ FROM sales_lines
107
+ WHERE month_start >= '{{ pipeline_args.PERIOD_FROM }}' AND month_start < '{{ pipeline_args.PERIOD_TO }}'
108
+ GROUP BY ALL
109
+ ORDER BY ALL
110
+ schema:
111
+ columns:
112
+ - { name: product_code, type: str, not_null: true }
113
+ - { name: region, type: str, not_null: true }
114
+ - { name: month, type: str, not_null: true }
115
+ - { name: revenue, type: float, not_null: true }
116
+ quality_rules:
117
+ - type: custom__unique_composite
118
+ params: { columns: [product_code, region, month] }
119
+ ```
120
+
121
+ - **CSV defaults that bite.** The separator is not detected (default `,`). `NA`, `null`, `None`, `n/a` and empty read as NULL, which turns the country code `NA` into a missing value. There is no option to change that, so check such columns on purpose. Set `csv_options.decimal: ","` for decimal commas.
122
+
123
+ ## 5. Quality rules: which kind goes where
124
+
125
+ - **Bronze, structure:** `not_null` on mandatory source columns, types, and `isin` on enumerations. A changed or truncated source fails at the door.
126
+ - **Silver, business and reference:** every mapped code found, codes in the expected pattern (`str_matches`), values in range.
127
+ - **Gold, the load contract:**
128
+ - `custom__unique_composite` over the coordinate columns, because the import sums duplicates;
129
+ - `not_null` on coordinates and values;
130
+ - `isin` on the period columns set to the run's period.
131
+ - **Reconcile in a transform.** A rule cannot compare two datasets, and `custom__sum_equals` and `custom__compare` work per row. Write a small transform that totals both sides per period into one row, assert it with `custom__compare`, and list it in the gold dataset's `deps`. A failed total then stops gold, and the load with it.
132
+ - **Severity.** `error`, the default, is for structural garbage where loading is pointless; `warn` is for findings to report; the review gate (section 7) is for anything a person should decide.
133
+ - **A SQL `error()` guard must be read.** DuckDB drops a column or CTE that the final `SELECT` never uses, and the `error()` inside it with it, so `... CROSS JOIN guard` alone never fails. Use the guard in the `WHERE` (`WHERE guard.g IS NULL`) or in a selected column. Prefer a quality rule when one can say it.
134
+ - **Regexes run on RE2:** no lookahead or backreferences.
135
+ - **Any rule loads the whole dataset** to validate it.
136
+
137
+ ## 6. `main.py`, arguments and fan-out
138
+
139
+ Job arguments arrive as one JSON object of strings in the `FARSEER_ARGS` environment variable, and `run_pipeline` reads them there when it is called. `main.py` checks them and writes back one canonical spelling, so labels and dataset names never drift:
140
+
141
+ ```python
142
+ import json, os, re, sys
143
+ from datetime import date, timedelta
144
+
145
+ args = json.loads(os.environ.get("FARSEER_ARGS") or "{}")
146
+ month = (args.get("MONTH") or "").strip()
147
+ if not month: # a scheduled run leaves it empty: load the previous month
148
+ previous = date.today().replace(day=1) - timedelta(days=1)
149
+ month = f"{previous.year}-{previous.month}"
150
+ match = re.fullmatch(r"(\d{4})-(\d{1,2})", month)
151
+ if not match or not 1 <= int(match[2]) <= 12:
152
+ sys.exit(f"MONTH must look like 2026-03, got {month!r}")
153
+ args["MONTH"] = f"{match[1]}-{int(match[2]):02d}" # one spelling, so labels always match
154
+ os.environ["FARSEER_ARGS"] = json.dumps(args)
155
+ # ...then the starter's imports and run_pipeline(...)
156
+ ```
157
+
158
+ - **Every value is a string.** A boolean arrives as `"true"` or `"false"`, so compare explicitly.
159
+ - **Settle empty values here.** Jinja's `default()` fires only for a missing argument, never for an empty string.
160
+ - **Arguments are pasted into the YAML verbatim, SQL included.** Validate each one against a pattern.
161
+ - **Secrets** come from secret job arguments, `{{ pipeline_args.NAME }}`, and never appear in YAML, code, logs or the conversation.
162
+
163
+ **One definition, many datasets.** Use `expand` rather than copied YAML. The grammar topics do not cover this shape, so follow it exactly:
164
+
165
+ ```yaml
166
+ # Models/bronze/tb_file.yaml: one extract per company
167
+ expand:
168
+ values:
169
+ - [{key: company, value: C100}]
170
+ - [{key: company, value: C200}]
171
+ template:
172
+ name: "tb_file_{{ each.company }}"
173
+ type: extract
174
+ extract:
175
+ type: sharepoint
176
+ optional: true
177
+ sharepoint:
178
+ file_path: "Finance/TB/{{ each.company }}/{{ pipeline_args.MONTH }}.csv"
179
+ # site_url and the credential arguments as usual
180
+ ```
181
+
182
+ - **`expand:` is the only top-level key.** Everything else, `name` and `type` included, goes under `template:`.
183
+ - **Each `values:` entry is a list of `{key, value}` pairs,** read as `each.<key>`. `values_expr:` computes the same list from arguments. Every rendered name must be unique.
184
+ - **A downstream fan-out repeats the same `values:`** and names its dependency with the same key, for example `deps: ["bronze.tb_file_{{ each.company }}"]`. Its SQL then reads the view `tb_file_{{ each.company }}`.
185
+ - **Logic shared by the fanned datasets is one ibis or pandas function** named in `transform.function`, with what differs passed in `transform.args`.
186
+ - **A YAML varies one axis.** Put the axis value in each load's labels.
187
+
188
+ ## 7. Loading: the rules that change numbers silently
189
+
190
+ | Behaviour | Do |
191
+ |---|---|
192
+ | Rows with the same coordinates in one import are summed | Aggregate in gold; assert uniqueness |
193
+ | A variable without a time dimension sums every dated row into one cell | Aggregate to the variable's grain; map no date |
194
+ | `overwrite_cells: true` replaces only the coordinates in this import; other cells keep their values | Replace a slice with labels and `undo_previous` (below) |
195
+ | `overwrite_cells: false` refuses the whole import if any target cell holds a value | Use `true` for anything that reruns |
196
+ | Empty values never clear a cell; with `import_zeros: false` zeros are dropped too | Send a known zero as `0`, and leave `import_zeros` on |
197
+ | A value is parsed as a number: `"1,234"` becomes `1` | Cast values to numbers in the transform |
198
+ | A date sets Months and Years only; an ISO time zone shifts to the UTC date | Send `YYYY-MM-DD` strings with the default format |
199
+ | Years and Months members are never created by an import, and a missing year fails it | Confirm the year exists; extending the timeline is the model owner's job |
200
+ | Every dimension of the variable needs a member on every row; Versions is never defaulted | Pin Versions with `fixed_dimension_members` |
201
+
202
+ **Labels, `undo_previous` and `overwrite_cells: true` make a rerun replace its slice.** The engine adds `pipeline:<load qualified name>` to the labels. After the new import commits, every earlier import with all the same labels is undone. Undo deletes that import's cells and never restores the values they replaced.
203
+
204
+ - **Labels name exactly the slice one run owns:** `[<pipeline>, <kind>, <entity>, <period>]`, built from canonical values.
205
+ - **One owner per slice.** Two cells entries with the same labels undo each other.
206
+ - **Moving or renaming a load's YAML** changes its automatic label, so earlier imports are no longer undone.
207
+ - **A skipped or empty load undoes nothing,** which is what makes per-company `optional` extracts safe.
208
+ - **A failed undo is only a warning.** Read the run log.
209
+
210
+ **Members.** Whether a source value the model lacks is created, defaulted or blocked is a business decision per dimension, and a created member is permanent.
211
+
212
+ - `missing_member_policy: DISALLOW`, the default, fails the import. `SKIP_ROW` drops the row without counting it, so count it yourself if you use it.
213
+ - `create_missing_members: true` creates members from mapped columns during staging, never fixed members. Guard such columns with an `error`-level `str_matches`.
214
+ - **To let finance review new members first,** compute string columns `CHECK` (`OK`, `MISSING` or `EXEMPT`), `CHECK_DETAIL` and `NEW_MEMBER` in the transform, map them as `custom_fields`, and set `review_gate: {column: CHECK, block_values: [MISSING]}`, with `create_missing_members: false`.
215
+ - A blocked import is staged for a person to accept, and the run ends red on purpose.
216
+ - Keep `error` rules off the gate column.
217
+ - A manual commit skips `undo_previous`.
218
+
219
+ **Never load into a formula variable.** The loaded values shadow the formula; load its inputs instead.
220
+
221
+ **Dimension loads are permanent.** Members match by name, ignoring case. A renamed value becomes a new member. `delete_missing: true` deletes members absent from the load, together with their cells, so a partial run keeps it `false`.
222
+
223
+ **A load step is not atomic.** Dimensions sync first, then each cells entry is its own import. If a step fails, no dataset is published, but loads that already ran keep their cells.
224
+
225
+ ## 8. Storing data: stores, write modes, incremental extraction
226
+
227
+ Storage choices are the hardest to undo. A dataset's store and file format are fixed when it is first created, merge keys are fixed at the first keyed write, and nothing is ever deleted. Decide them before the first run.
228
+
229
+ ### The store is chosen once per pipeline
230
+
231
+ `store_type` is one argument to `run_pipeline`, so every dataset of a pipeline lives in the same store.
232
+
233
+ | Store | What it does | Use for | Never |
234
+ |---|---|---|---|
235
+ | `DATASETS` | Versioned datasets in the registry. A run writes candidates, which become visible only when published | Almost everything: any dataset rebuilt whole each run and read downstream | Incremental extraction: a cursor is refused |
236
+ | `ICEBERG` (experimental) | One Iceberg table per dataset. Each run writes on its own branch, frozen as a tag when complete | Datasets that accumulate: `append`, `upsert`, incremental SQL extracts | Data that a full rebuild each run would serve as well |
237
+ | `FARSEER_FILES` (the engine default) | One file per dataset under the pipeline's `Data/` folder. Saving is publishing; there are no versions | Ad hoc output nobody else reads | Anything read downstream: a failing run has already replaced the file |
238
+
239
+ - **An incremental source gets its own pipeline folder on `ICEBERG`.** Everything that consumes it lives in a `DATASETS` pipeline and reads it with `source: datasets`. That keeps the experimental store to the datasets that need it.
240
+ - **A dataset never changes store.** A run that names a dataset on the wrong store creates it there. For example, a cursor on `DATASETS` is refused only after the dataset exists. Moving it to `ICEBERG` afterwards is refused too, so give the dataset a new name.
241
+
242
+ ### Versions, publication and restore
243
+
244
+ - **Publication waits for the whole run.** By default every dataset publishes only after every step has succeeded, each dataset separately. One failing step therefore publishes nothing, and it holds back every reading position in the pipeline.
245
+ - **Readers see the last published version.** Other pipelines, `source: datasets` and `query` keep seeing it while a run is in progress. A dataset that was never published reads as missing.
246
+ - **`restore` makes an earlier published version current again,** and rewinds the reading position to where that version stopped. It cancels any candidate in flight. It does not undo model loads or exports.
247
+ - **Nothing is deleted.** Published versions, cancelled candidates, Iceberg snapshots and files superseded by upserts all stay indefinitely, with no expiry and no compaction. A dataset may hold at most 10 unpublished candidates, and abandoned ones are marked cancelled after 24 hours.
248
+
249
+ ### Write modes: decide per dataset
250
+
251
+ `write_mode` is set per extract or transform and defaults to `overwrite`. `append` and `upsert` work only on `ICEBERG`.
252
+
253
+ | | `overwrite` | `append` | `upsert` (with `merge_keys`) |
254
+ |---|---|---|---|
255
+ | A run | Replaces every row with this run's output | Adds this run's rows to everything kept | Replaces rows whose keys arrive, inserts new keys, keeps the rest |
256
+ | Rerunning the same input | Same result | **Duplicates it** | Same result, per key |
257
+ | Rows deleted at the source | Gone | Kept forever | Kept forever |
258
+ | A new source column | Added | Added; older rows read null | Added; older rows read null |
259
+ | A column that disappears | Allowed | Refused | Refused |
260
+ | A changed column type (`ICEBERG`) | Refused unless a legal widening: new dataset | Refused: new dataset | Refused: new dataset |
261
+ | Row and column order | As written | Write order kept | Unstable: rows and columns move on every merge |
262
+ | Fits | Most datasets | Immutable events, read once each | Records that change, with a stable business key |
263
+
264
+ - **`merge_keys` are fixed for the dataset's life.** They must be unique within each run's output, non-null, and finite. Keys cannot be added to a dataset that already has unkeyed history; changing them means a new dataset and a rebuild. A composite key with very many distinct combinations is refused, so lead it with a low-cardinality column, such as the period.
265
+ - **A mode can change between runs, and nothing stops a harmful change.** Switching a populated dataset from `overwrite` to `append` silently starts accumulating. Change a mode deliberately, with a rebuild if the history no longer fits.
266
+ - **Rules and `schema:` check the whole accumulated dataset on every run,** including quiet ones, and quality rules load all of it to do so. A rule tightened so that old rows fail it blocks every future publication of that dataset. Budget the validation cost as the history grows.
267
+ - **An empty full extract under `overwrite` publishes an empty dataset.** No built-in rule checks a minimum row count. Where an empty source is a fault, put `custom__distinct_count` with `min: 1` on a column that is never null, such as a key.
268
+ - **Under `upsert`, select columns by name and sort explicitly.** Never read by position.
269
+
270
+ ### Incremental extraction
271
+
272
+ Only a `sql_database` extract with `cursor_column`, on `ICEBERG`, reads incrementally. Default to extracting the run's slice in full with `overwrite`: it reruns cleanly, and deletions simply disappear. Go incremental only when re-reading the slice is too slow, and only after the source's cursor passes every check below.
273
+
274
+ - **The window is everything strictly after the last committed position, up to a maximum measured at the start, with no lookback.** Three things are never read:
275
+ - rows that become visible later with a cursor at or below the committed position;
276
+ - edits that do not move the cursor;
277
+ - deletions.
278
+ - **Qualify the cursor:**
279
+ - It is a column the source types as a number, a timestamp or a sequence. A text column holding numbers sorts `10.00` below `9.50`: the dataset silently stops growing while the runs stay green.
280
+ - It is assigned when the row commits. Rows that share the measured maximum and commit after the measurement are lost.
281
+ - It is never null. The first read refuses null cursors, and later reads skip historical nulls for good.
282
+ - **The position advances only when the version publishes,** in the same step that makes it current. A failed run publishes nothing, and the retry may read a wider window.
283
+ - **The position is tied to the exact query text,** along with the host, database, table and cursor column. Any edit, a comment or reformatting included, makes later runs refuse until an operator moves the position to the new query through the dataset's watermark endpoint. Treat an incremental query as frozen.
284
+ - **A quiet run,** with no new rows, cancels its candidate and keeps the data and the position. It still runs validation.
285
+ - **There is no lease.** Two runs of one incremental dataset at once cancel each other's work. Give each such dataset one schedule and no overlapping manual runs.
286
+ - **Rebuilding safely:**
287
+ 1. Stop the schedule.
288
+ 2. Have the operator delete the watermark.
289
+ 3. Run once with `write_mode: overwrite`. That reads from the beginning, replaces the table and records a fresh position, and merge keys survive.
290
+ 4. Switch back to `append` or `upsert`.
291
+
292
+ Never delete the watermark and rerun under `append`: that stores everything twice. To undo one bad publication, `restore` the previous version instead.
293
+
294
+ ### Choosing by source shape
295
+
296
+ | Source | Store and mode | Extraction | Never |
297
+ |---|---|---|---|
298
+ | Small reference table (products, accounts) | `DATASETS`, `overwrite` | Full each run | Upsert with a cursor: deleted rows linger and the keys are fixed for life |
299
+ | File delivered per period | `DATASETS`, `overwrite`, one dataset per period through `expand`, unioned downstream | Each run extracts its period | `append`: a re-delivered month doubles |
300
+ | Full-refresh export | `DATASETS`, `overwrite` | Full; earlier exports remain as versions | `append` |
301
+ | Large immutable event log | `ICEBERG`, `append`, its own pipeline | Cursor on a sequence assigned at commit | A text or transaction-start timestamp cursor; `append` on a source that edits rows |
302
+ | Large records that change, with `updated_at` | `ICEBERG`, `upsert` on a stable business id, its own pipeline | Cursor on a commit-time `updated_at`, plus a periodic rebuild to drop rows deleted at the source | `append`; wide composite keys; reading by position |
303
+
304
+ ## 9. Verify
305
+
306
+ - **Before the first run:** run `check`, confirm every model name with the model tools, and run the extracts once. Then test each SQL transform with `query` against the published extracts, asking for shapes (`DESCRIBE`, `COUNT`, `SUM`, `GROUP BY ... HAVING count(*) > 1`) rather than rows.
307
+ - **After every run:**
308
+ - `inspect` the run by its UUID: every step OK, `skippedOutputs` empty, each import `commit_confirmed`, and no failed undo.
309
+ - Query gold for its row count, zero duplicate coordinates, and totals per period against the control totals.
310
+ - Check what each load committed with `inspect-import` on its import ID; never check with a model or variable export.
311
+ - Rerun the same slice and confirm nothing changed.
312
+ - Report what you verified, with run and version identifiers, and what you did not.
313
+
314
+ ## 10. Anti-patterns
315
+
316
+ - A transform without `engine:`, or pandas doing set-based work.
317
+ - Logic in the load step or in `main.py`; reading data or calling APIs from `main.py`.
318
+ - The same YAML or function copied per company or month.
319
+ - A dataset named generically enough to collide with another pipeline's.
320
+ - Columns kept without being declared, or codes left as numbers.
321
+ - An `INNER JOIN` to a mapping, or a mapping `CASE` repeated across queries.
322
+ - `optional: true` on a path nobody verified, or `SKIP_ROW` with no count.
323
+ - Labels from unnormalised arguments, or two loads sharing labels.
324
+ - Transforms that read the environment or the clock.
325
+ - Comments carrying dates, people's names, ticket numbers or runner versions. Say what the code relies on.