continuo-python-runtime 0.11.0__py3-none-any.whl → 0.13.0__py3-none-any.whl

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 (26) hide show
  1. continuo_python_runtime/cli.py +108 -37
  2. continuo_python_runtime/content_check.py +73 -0
  3. continuo_python_runtime/contract/kinds.py +37 -21
  4. continuo_python_runtime/contract/loader.py +207 -389
  5. continuo_python_runtime/contract/model.py +13 -6
  6. continuo_python_runtime/contract/pack.py +299 -0
  7. continuo_python_runtime/contract/paths.py +34 -1
  8. continuo_python_runtime/contract/read_tables.py +85 -0
  9. continuo_python_runtime/errors.py +13 -1
  10. continuo_python_runtime/harness.py +21 -6
  11. continuo_python_runtime/hash_inputs.py +63 -0
  12. continuo_python_runtime/hashing.py +54 -72
  13. continuo_python_runtime/lint.py +194 -6
  14. continuo_python_runtime/packages.py +56 -0
  15. continuo_python_runtime/validation/preflight.py +410 -0
  16. continuo_python_runtime/validation/runner.py +20 -3
  17. continuo_python_runtime-0.13.0.dist-info/METADATA +600 -0
  18. continuo_python_runtime-0.13.0.dist-info/RECORD +36 -0
  19. continuo_python_runtime/contract/merge.py +0 -197
  20. continuo_python_runtime/contract/secret_ref.py +0 -31
  21. continuo_python_runtime-0.11.0.dist-info/METADATA +0 -411
  22. continuo_python_runtime-0.11.0.dist-info/RECORD +0 -32
  23. {continuo_python_runtime-0.11.0.dist-info → continuo_python_runtime-0.13.0.dist-info}/WHEEL +0 -0
  24. {continuo_python_runtime-0.11.0.dist-info → continuo_python_runtime-0.13.0.dist-info}/entry_points.txt +0 -0
  25. {continuo_python_runtime-0.11.0.dist-info → continuo_python_runtime-0.13.0.dist-info}/licenses/LICENSE +0 -0
  26. {continuo_python_runtime-0.11.0.dist-info → continuo_python_runtime-0.13.0.dist-info}/licenses/NOTICE +0 -0
@@ -1,197 +0,0 @@
1
- """Contract v1 merger: wire contract builder."""
2
-
3
- from collections.abc import Callable
4
- from pathlib import Path
5
-
6
- import yaml
7
-
8
- from continuo_python_runtime.closure import resolve_closure
9
- from continuo_python_runtime.contract.loader import load_contract_dir
10
- from continuo_python_runtime.contract.model import CONTRACT_VERSION, DEFAULT_MODE_TYPE, Node
11
- from continuo_python_runtime.contract.paths import resolve_script_path
12
- from continuo_python_runtime.errors import ContractError
13
- from continuo_python_runtime.hashing import hash_parts
14
- from continuo_python_runtime.lint import lint_source
15
-
16
-
17
- def node_entry(node: Node) -> dict:
18
- """Convert a Node to its wire form dict.
19
-
20
- Returns the node as a dict with all fields, output_columns as list of
21
- dicts. The entry carries no hash fields: build_wire_contract adds all
22
- four (source_hash, shared_code_hash, config_hash, content_hash). The
23
- nullable field is always present in output_columns. ``secret_ref``,
24
- ``mode_type`` and ``primary_key`` appear only when they differ from their
25
- default, so a node that does not use them has the entry (and hashes) it
26
- had before they existed.
27
- """
28
- entry = {
29
- "schema": node.schema,
30
- "table": node.table,
31
- "owner": node.owner,
32
- "schedule": node.schedule,
33
- "criticality": node.criticality,
34
- "kind": node.kind,
35
- "script": node.script,
36
- "reads": node.reads,
37
- "output_columns": [
38
- {
39
- "name": col.name,
40
- "type": col.type,
41
- "nullable": col.nullable,
42
- }
43
- for col in node.output_columns
44
- ],
45
- "description": node.description,
46
- "extra_columns": node.extra_columns,
47
- "config": dict(node.config),
48
- }
49
- # Only a kind that may name a Secret ever carries one; emitting the key
50
- # only when set keeps every other node's config_hash unchanged.
51
- if node.secret_ref:
52
- entry["secret_ref"] = node.secret_ref
53
- # Same reasoning: every replace node's entry, config_hash and content_hash
54
- # stay byte-identical, so contract_version stays 1.
55
- if node.mode_type != DEFAULT_MODE_TYPE:
56
- entry["mode_type"] = node.mode_type
57
- if node.mode_type == "upsert":
58
- entry["primary_key"] = list(node.primary_key)
59
- return entry
60
-
61
-
62
- def _lint_node_closure(
63
- node: Node,
64
- repo_root: Path,
65
- script_path: Path,
66
- script_bytes: bytes,
67
- closure: list[Path],
68
- member_bytes: list[bytes],
69
- ) -> None:
70
- """Lint the node's script and every resolved closure member.
71
-
72
- Every file that executes for this node — the script plus its transitive
73
- in-repo import closure — is held to the same lint rules
74
- (``continuo_python_runtime.lint.lint_source``: L1 forbidden driver
75
- imports, L2 SQL string literals, L3 forbidden data-access calls, L4
76
- private-attribute access, L5 dynamic-import constructs) that CI's
77
- ``continuo-runtime lint`` applies to ``scripts/``. Enforcing it again
78
- here, at merge time, means a helper file outside ``scripts/`` — which
79
- the CI lint step never looks at — cannot become a side channel around
80
- the harness's sole write sink, and the check cannot be defeated by a
81
- stale or hand-edited workflow file: whatever produces the release
82
- artifact is the thing that checked.
83
-
84
- Paths in violation messages are repo-root-relative (``str(path.relative_to
85
- (repo_root))``), so a message reads ``lib/shared.py:1: ...`` identically
86
- in CI and on a laptop, never an absolute path that differs between the
87
- two.
88
-
89
- Raises ``ContractError`` naming the node and listing every violation
90
- from every offending file — not just the first file's — so an author
91
- can act on the full report in one pass instead of an iterative guessing
92
- game.
93
-
94
- Every file is decoded as ``"utf-8-sig"`` (identical to plain ``"utf-8"``
95
- except that a leading BOM, if present, is stripped rather than kept as a
96
- literal ``U+FEFF`` character) — this matches what ``ast.parse(bytes)``
97
- already does for the same file in ``resolve_closure`` (bytes-mode
98
- parsing treats a UTF-8 BOM as an implicit encoding declaration and
99
- strips it), so a BOM file that parses and runs fine is not rejected here
100
- on a mismatch between the two decoders. A file that isn't valid UTF-8 at
101
- all (e.g. a PEP 263 ``# -*- coding: latin-1 -*-`` cookie plus a
102
- non-ASCII byte — valid input to ``ast.parse(bytes)``, which honors the
103
- cookie) raises ``UnicodeDecodeError``; that is caught and re-raised as a
104
- ``ContractError`` naming the node and the offending repo-relative path,
105
- so it joins the same error taxonomy as every other rejection here
106
- instead of escaping as a bare stdlib exception past ``cli.main``, which
107
- catches only ``HarnessError``/``OSError``.
108
- """
109
- repo_root_resolved = repo_root.resolve()
110
- files = [(script_path, script_bytes), *zip(closure, member_bytes, strict=True)]
111
-
112
- violations: list[str] = []
113
- for path, data in files:
114
- rel = path.relative_to(repo_root_resolved)
115
- try:
116
- text = data.decode("utf-8-sig")
117
- except UnicodeDecodeError as exc:
118
- raise ContractError(f"{node.relation}: {rel}: not valid UTF-8: {exc}") from exc
119
- violations.extend(lint_source(text, str(rel)))
120
-
121
- if violations:
122
- report = "\n".join(violations)
123
- raise ContractError(
124
- f"{node.relation}: lint violations in script or import closure:\n{report}"
125
- )
126
-
127
-
128
- def _script_hash_inputs(node: Node, repo_root: Path) -> tuple[bytes, list[bytes]]:
129
- """A script node's source is its script plus its in-repo import closure,
130
- every file of which is held to the closure lint."""
131
- script_path = resolve_script_path(node.script, repo_root, context=node.relation)
132
- script_bytes = script_path.read_bytes()
133
- closure = resolve_closure(script_path, repo_root)
134
- member_bytes = [member.read_bytes() for member in closure]
135
- _lint_node_closure(node, repo_root, script_path, script_bytes, closure, member_bytes)
136
- return script_bytes, member_bytes
137
-
138
-
139
- def _csv_hash_inputs(node: Node, repo_root: Path) -> tuple[bytes, list[bytes]]:
140
- """A csv node has no script and no import closure: its source is the uri.
141
- New file content at the same uri is new data, not a new node version."""
142
- return node.reads["csv"].encode(), []
143
-
144
-
145
- _HASH_INPUTS: dict[str, Callable[[Node, Path], tuple[bytes, list[bytes]]]] = {
146
- "python-node": _script_hash_inputs,
147
- "python-csv": _csv_hash_inputs,
148
- "python-api": _script_hash_inputs,
149
- }
150
-
151
-
152
- def build_wire_contract(
153
- contract_dir: Path, repo_root: Path, service: str, *, dialect: str | None = None
154
- ) -> dict:
155
- """Build and return a wire contract document.
156
-
157
- Loads contracts from contract_dir, resolves script paths against repo_root,
158
- computes content hashes, and returns a contract document sorted by relation.
159
- ``dialect`` is forwarded to :func:`~continuo_python_runtime.contract.loader
160
- .load_contract_dir` so every declared read is checked against that sqlglot
161
- dialect (``None`` -- the default -- uses sqlglot's dialect-neutral parser).
162
-
163
- Raises ContractError if any script file is missing.
164
- """
165
- nodes = load_contract_dir(contract_dir, dialect=dialect)
166
-
167
- wire_nodes = []
168
- for node in nodes:
169
- entry = node_entry(node)
170
-
171
- primary_bytes, member_bytes = _HASH_INPUTS[node.kind](node, repo_root)
172
- entry.update(hash_parts(entry, primary_bytes, member_bytes))
173
- # The one wire key outside config_hash: it is written after the hashes
174
- # are computed, so changing it alone never changes content_hash.
175
- if node.timeout_minutes is not None:
176
- entry["timeout_minutes"] = node.timeout_minutes
177
-
178
- wire_nodes.append(entry)
179
-
180
- # Sort by relation (schema.table)
181
- wire_nodes.sort(key=lambda entry: f"{entry['schema']}.{entry['table']}")
182
-
183
- return {
184
- "contract_version": CONTRACT_VERSION,
185
- "service": service,
186
- "nodes": wire_nodes,
187
- }
188
-
189
-
190
- def write_wire_contract(doc: dict, out: Path) -> None:
191
- """Write a wire contract document to a YAML file.
192
-
193
- Creates ``out``'s parent directory (and any missing ancestors) first, so
194
- callers don't need to pre-create the output directory.
195
- """
196
- out.parent.mkdir(parents=True, exist_ok=True)
197
- out.write_text(yaml.safe_dump(doc, sort_keys=False))
@@ -1,31 +0,0 @@
1
- """The name of the Kubernetes Secret a node's pod receives as env vars.
2
-
3
- The ``continuo-api-`` prefix keeps a contract from naming any other Secret in
4
- the namespace (the warehouse credentials, the platform's own credentials).
5
- continuo's topology-controller and execution-controller enforce the same
6
- pattern; this check gives the author the error in CI instead.
7
- """
8
-
9
- from __future__ import annotations
10
-
11
- import re
12
-
13
- from continuo_python_runtime.errors import ContractError
14
-
15
- SECRET_REF_PATTERN = re.compile(r"^continuo-api-[a-z0-9]([-a-z0-9]*[a-z0-9])?$")
16
- SECRET_REF_MAX_LEN = 253
17
-
18
-
19
- def validate_secret_ref(value: object, label: str) -> str:
20
- """Return ``value`` if it is a valid ``continuo-api-*`` Secret name."""
21
- if (
22
- not isinstance(value, str)
23
- or len(value) > SECRET_REF_MAX_LEN
24
- or not SECRET_REF_PATTERN.fullmatch(value)
25
- ):
26
- raise ContractError(
27
- f"{label}: 'secret_ref' must be a Kubernetes Secret name starting with "
28
- f"'continuo-api-' (lowercase letters, digits, '-'; at most "
29
- f"{SECRET_REF_MAX_LEN} chars), got {value!r}"
30
- )
31
- return value
@@ -1,411 +0,0 @@
1
- Metadata-Version: 2.5
2
- Name: continuo-python-runtime
3
- Version: 0.11.0
4
- Summary: Runtime harness, contract tooling, and CI lint for Continuo python nodes.
5
- Author: Simone Carolini
6
- Maintainer: Simone Carolini
7
- License-Expression: Apache-2.0
8
- License-File: LICENSE
9
- License-File: NOTICE
10
- Classifier: Development Status :: 4 - Beta
11
- Classifier: Intended Audience :: Developers
12
- Classifier: Programming Language :: Python :: 3.14
13
- Requires-Python: >=3.14
14
- Requires-Dist: boto3==1.43.114
15
- Requires-Dist: continuo-engine-contract==0.9.0
16
- Requires-Dist: pyarrow==26.0.0
17
- Requires-Dist: pyyaml==6.0.3
18
- Requires-Dist: sqlglot==30.23.0
19
- Description-Content-Type: text/markdown
20
-
21
- # Continuo Python Runtime
22
-
23
- [![CI](https://github.com/carolsimone/continuo-python-runtime/actions/workflows/ci.yml/badge.svg)](https://github.com/carolsimone/continuo-python-runtime/actions/workflows/ci.yml)
24
- [![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)
25
- [![Release](https://img.shields.io/github/v/release/carolsimone/continuo-python-runtime?label=release)](https://github.com/carolsimone/continuo-python-runtime/releases)
26
-
27
- Runtime harness, contract tooling, and CI lint for Continuo python nodes.
28
- This repo is what domain data teams (marketing, finance, …) template from to
29
- ship a python node into Continuo: write a contract + a `run(ctx)` script,
30
- push to `main`, and CI does the rest — lint, validate, merge, build, publish,
31
- and register the release with Continuo.
32
-
33
- ## What this repo is
34
-
35
- Five artifacts come out of this repository:
36
-
37
- - **The `continuo-python-runtime` PyPI package** — the `continuo-runtime` CLI
38
- (`validate` / `merge` / `hash` / `lint` / `run` / `validation-op`) and the
39
- harness library (`conform()`, `RunContext`, the error taxonomy) that domain
40
- repos install.
41
- - **The `continuo-engine-contract` PyPI package** — the `WarehouseAdapter`
42
- port, the contract schema, the shared SQL/type/config guards, and the
43
- sentinel result-block format. Adapter authors outside this repo pin it.
44
- - **The three engine-adapter PyPI packages** (`continuo-postgres-adapter`,
45
- `continuo-trino-adapter`, `continuo-duckdb-adapter`) — one `WarehouseAdapter` implementation per
46
- warehouse engine, each published independently under the same tag. A
47
- domain repo normally never installs these directly (the engine image
48
- already has the matching one baked in); they exist as standalone PyPI
49
- packages for the "build your own container" shape (see below) and for
50
- third-party adapter authors to reference.
51
- - **Per-engine base images**, one per warehouse engine
52
- (`continuo-python-runtime-postgres`, `continuo-python-runtime-trino`,
53
- `continuo-python-runtime-duckdb`), that
54
- domain repos build `FROM`. Each image bakes in the runtime and a single
55
- `WarehouseAdapter` for that engine, and serves both roles that adapter has:
56
- the node harness (`ENTRYPOINT ["continuo-runtime"]`, `CMD ["run"]`) and the
57
- validation runner (`continuo-runtime validation-op`).
58
- - **`template/`** — a copy-ready domain repo: `Dockerfile`, `contracts/`,
59
- `scripts/`, and the `release.yml` CI/CD workflow.
60
-
61
- One `vX.Y.Z` git tag releases all of it: `publish-pypi.yml` builds all five
62
- PyPI distributions into a single `dist/`, verifies them (and full engine
63
- images built from them) on amd64 and arm64, and only then publishes them
64
- together. It then builds all three engine images natively per architecture —
65
- each installing its matching pinned adapter version from that same release —
66
- pulls and smoke-tests the exact pushed digests, and finally gives the verified
67
- amd64 + arm64 digests one multi-arch tag. See `CONTRIBUTING.md` (Releasing).
68
-
69
- ### What this repo owns
70
-
71
- This repository owns the entire python-node surface: the engine contract, the three
72
- engine adapters, the validation runner, and the node harness. The former
73
- `continuo-validation` repository was merged in — there is no longer a separate
74
- validation-side port, adapter class, entry-point group, or image. One
75
- `WarehouseAdapter` per engine serves both the data plane (`fetch` /
76
- `ensure_table` / `load`, plus the opt-in `table_columns` / `append` / `upsert`
77
- capabilities) and validation (`ensure_schema` / `drop_schema` /
78
- `build_empty_from_sql` / `build_empty_from_columns` / `clone_empty_from_prod` /
79
- `check_binds`), and one image per engine runs both roles.
80
-
81
- | Package (distribution name) | Module | Lives in | Role |
82
- | --- | --- | --- | --- |
83
- | `continuo-python-runtime` | `continuo_python_runtime` | this repo (root) | Harness (CLI, `conform()`, `RunContext`, error taxonomy) **and** the validation runner (`continuo-runtime validation-op`). Published to PyPI. |
84
- | `continuo-engine-contract` | `continuo_engine_contract` | this repo, `contract/` | The `WarehouseAdapter` port, contract schema, the SQL/type/config guards adapters must run, and the result-block format. Published to PyPI. |
85
- | `continuo-postgres-adapter` | `continuo_postgres_adapter` | this repo, `adapters/postgres/` | `PostgresAdapter` — one class, both roles. Published to PyPI. |
86
- | `continuo-trino-adapter` | `continuo_trino_adapter` | this repo, `adapters/trino/` | `TrinoAdapter` — one class, both roles, for Trino/Iceberg. Published to PyPI. |
87
- | `continuo-duckdb-adapter` | `continuo_duckdb_adapter` | this repo, `adapters/duckdb/` | `DuckDBAdapter` — one class, both roles, for DuckDB on a DuckLake (Postgres catalog, Parquet on S3). Published to PyPI. |
88
-
89
- All five are uv workspace members (`[tool.uv.workspace]` in the root
90
- `pyproject.toml`), so `uv sync --all-packages --all-groups` at the repo root
91
- installs everything for local development.
92
-
93
- **All five packages in the table above are published to PyPI**, under the
94
- same `vX.Y.Z` tag. The three engine images then **install the matching pinned
95
- adapter version from PyPI** — `Dockerfile.postgres` installs
96
- `continuo-postgres-adapter==X.Y.Z`, `Dockerfile.trino` installs
97
- `continuo-trino-adapter==X.Y.Z` and `Dockerfile.duckdb` installs
98
- `continuo-duckdb-adapter==X.Y.Z` — rather than building it from this repo's
99
- source tree, so each image still ships exactly one adapter and the runtime
100
- still discovers it through the `continuo_engine.adapters` entry-point group
101
- at run time. The image **name** (`continuo-python-runtime-<engine>`) and the
102
- adapter's pip **distribution** name (`continuo-<engine>-adapter`) are two
103
- different artifacts of the same adapter — same engine, same version, same
104
- runtime behavior, different packaging; see "Build your own container" below
105
- for a build shape that installs the pip package directly instead of `FROM`
106
- the image. All five packages are still built, type-checked, and tested by CI
107
- on every change.
108
-
109
- ### The result block is a frozen wire contract
110
-
111
- `continuo_engine_contract.result` writes a sentinel-framed JSON block as the
112
- last line of stdout, and Continuo's Go side parses it byte-for-byte
113
- (`pkg/validationresult` in the `continuo` repository). That wire format — the
114
- sentinel markers, the framing, and the field names inside the block — is
115
- **frozen**. Reuse it; never change it from this side alone. A change here that
116
- the Go parser has not been taught is a production outage, not a refactor.
117
-
118
- ## Quickstart for domain teams
119
-
120
- 1. Copy `template/` into a new repository.
121
- 2. Edit `template/.github/workflows/release.yml` and set `SERVICE` to your
122
- service name (one service name per domain repo).
123
- 3. Configure repository variables in GitHub (Settings → Secrets and
124
- variables → Actions): `REGISTRY` (your Docker registry), `BUCKET` (your
125
- S3 bucket for contract artifacts), `RELEASE_ENDPOINT` (the base
126
- URL of your continuo install, `scheme://host[:port]` with no path, the origin of continuo's
127
- `auth.publicUrl`). The
128
- workflow calls `<RELEASE_ENDPOINT>/api/v1/releases` with its GitHub Actions
129
- OIDC token, so the repository must be bound to your service in continuo's
130
- `ciAuth.bindings` (see [Releasing from CI](https://github.com/carolsimone/continuo/blob/main/deploy/README.md#releasing-from-ci-github-actions)),
131
- and an operator bootstraps the service's first release.
132
- 4. Configure repository secrets: `AWS_ACCESS_KEY_ID` and
133
- `AWS_SECRET_ACCESS_KEY` for the S3 upload. The template workflow pushes
134
- the built image to GHCR using the workflow's own `GITHUB_TOKEN` (granted
135
- `packages: write`) — no registry secret is needed for that. If you point
136
- `REGISTRY` at a different or private registry, add your own `docker
137
- login` step to `release.yml`.
138
- 5. Write a contract file under `contracts/` (see
139
- `template/contracts/example.yml`) and a script under `scripts/` that
140
- implements `run(ctx)` (see `template/scripts/example.py`). A node that
141
- only needs to land a csv file needs no script at all — see
142
- `template/contracts/example_csv.yml` and "Node kinds" below.
143
- 6. Push to `main`. The `release.yml` workflow lints the scripts, validates
144
- and merges the contracts, builds and pushes the image, uploads the merged
145
- contract to S3, and POSTs the release.
146
-
147
- ### Upgrading an existing domain repo
148
-
149
- `validate` / `merge` / `hash` now hand every declared read to a real SQL
150
- parser (sqlglot, via `continuo_engine_contract.sql.ensure_single_read`)
151
- instead of scanning it for a leading `SELECT`/`WITH`. Two things follow for a
152
- repo written before this, on its next release: SQL a driver would accept but
153
- a parser will not — most commonly a driver-specific bind placeholder like
154
- psycopg2's `%(name)s`, which `ctx.read(name)` could never have used anyway —
155
- now fails validation, and engine-specific syntax (postgres `~`, `@>`, …)
156
- needs `--dialect <engine>`, which a repo should be passing regardless since
157
- Continuo bind-checks every read in the install's own warehouse dialect. Run
158
- the pre-flight check once before your next release; it reports every affected
159
- read at once:
160
-
161
- ```bash
162
- continuo-runtime validate contracts/ --dialect postgres # or trino, duckdb
163
- ```
164
-
165
- The runtime image does not re-run this gate, so a read that passes here is
166
- not re-judged under a different grammar in production. See
167
- `docs/boundary-contract.md` §13.1.
168
-
169
- ## Node kinds
170
-
171
- A contract node's `kind:` field selects how the node produces its rows.
172
- Every rule below (`extra_columns`, `output_columns`, "Conform rules") applies
173
- to both kinds identically — `kind` only changes how the pre-conform table is
174
- produced, never how it is checked or written.
175
-
176
- - **`python-node`** (the default; the field may be omitted) — a script node.
177
- It requires `script:` and a `reads:` map of one or more named SQL queries,
178
- as described in "The script API" below.
179
- - **`python-csv`** — a contract-only node: it has no script and its `reads:`
180
- map must be exactly `{csv: <uri>}`, where the uri is `s3://bucket/key` or
181
- an `https://` url (`http://` is rejected at validate time, not run time).
182
- The harness fetches the file, parses it with RFC 4180 defaults, and feeds
183
- the result straight into `conform()` — declared `output_columns` types
184
- decide the warehouse schema, not whatever pyarrow infers from the csv.
185
- Because there is no script, `script:` is a forbidden key for this kind;
186
- `continuo-runtime validate`/`merge`/`lint` reject one that sets it. The
187
- csv's header row must contain every declared output column (checked again,
188
- independently, at release time before promotion); columns present in the
189
- header but not declared are governed by the same `extra_columns` policy as
190
- a script node's output — `raise` (default) fails the run, `warn` drops
191
- them and logs a warning. See `template/contracts/example_csv.yml`.
192
- - **`python-api`** — a script node that fetches its own data (typically over
193
- HTTP) and declares no `reads:`. `ctx.read` has nothing to return. It may name
194
- one Kubernetes Secret with `secret_ref: continuo-api-<name>`; continuo
195
- attaches that Secret to the node's pod, so each of its keys is an env var the
196
- script reads with `os.environ[...]`. The contract never holds a secret value
197
- or env var name; the Secret itself is created in the cluster by the operator.
198
-
199
- ### Task timeout
200
-
201
- Any node may set `timeout_minutes:` — an integer from 1 to 10,080 (one week) —
202
- to declare how long its task may run before continuo gives up on it. A value
203
- outside that range, or one that is not an integer, fails
204
- `continuo-runtime validate`/`merge`/`lint`. It is the one key that is not part
205
- of `config_hash`, so changing only the timeout never changes the node's
206
- `content_hash`.
207
-
208
- ## Write modes
209
-
210
- `mode_type:` chooses how the harness writes a node's table on each run:
211
-
212
- | `mode_type` | Each run | Rows from earlier runs |
213
- | --- | --- | --- |
214
- | `replace` (default) | empties the table, inserts this run's rows | gone |
215
- | `append` | inserts this run's rows | kept |
216
- | `upsert` | inserts rows with a new key, overwrites rows whose key exists | kept unless overwritten; never deleted |
217
-
218
- ```yaml
219
- - schema: fx
220
- table: fx_rates
221
- kind: python-api
222
- mode_type: upsert
223
- primary_key: [rate_date, base, quote]
224
- output_columns:
225
- - {name: rate_date, type: DATE, nullable: false}
226
- - {name: base, type: VARCHAR(3), nullable: false}
227
- - {name: quote, type: VARCHAR(3), nullable: false}
228
- - {name: rate, type: DECIMAL(12,6)}
229
- ```
230
-
231
- - `python-csv` nodes only `replace`.
232
- - `primary_key` is required for `upsert` and rejected otherwise: a non-empty
233
- list of output columns declared `nullable: false` (a NULL key never
234
- matches), each spelled exactly as in `output_columns`, names unique
235
- case-insensitively. A Postgres `replace` table that
236
- wants uniqueness uses `config.indexes` with `unique: true`.
237
- - Every write is atomic: all of the run's rows or none. An `append` or
238
- `upsert` run with zero rows writes nothing (a `replace` run with zero rows
239
- still empties the table).
240
- - `append` is a plain insert: a run that committed but was reported failed
241
- and is retried stores its rows twice. `upsert` is idempotent.
242
- - An `upsert` run whose own rows repeat a key fails with `ConformError` and
243
- writes nothing.
244
- - Before an `append` or `upsert` the harness compares the live table with
245
- `output_columns` — names case-insensitively, nullability exactly; order and
246
- types are not compared — and fails with `LoadError` naming every missing
247
- column, unexpected column and nullability mismatch. Changing an `append` or
248
- `upsert` table (columns, types, nullability, key or mode) needs a new table
249
- name (`_v2`) under a new contract; continuo rejects the release otherwise.
250
- Adding a nullable column is no exception: the existing rows cannot be
251
- backfilled.
252
- - The installed engine must support the mode; all three shipped adapters do.
253
- A bring-your-own adapter declares `AppendCapable` / `UpsertCapable` from
254
- `continuo-engine-contract` (and can run its conformance suite); without them
255
- an `append`/`upsert` node fails with `LoadError: <Adapter> does not support
256
- <mode>` before its script runs.
257
- - Engines: on Postgres the key is the table's `PRIMARY KEY`, created with the
258
- table; DuckLake and Trino/Iceberg have no constraints, so the key is
259
- guaranteed by the write path only. On Trino an `upsert` table needs Iceberg
260
- `format_version` 2 (the default).
261
- - `full_refresh` stays refused for every python node: a rebuild would destroy
262
- an accumulating table.
263
-
264
- ## The script API
265
-
266
- A node script is a Python file with exactly one required entry point:
267
-
268
- ```python
269
- def run(ctx):
270
- ...
271
- ```
272
-
273
- - `ctx` is a `RunContext` (`continuo_python_runtime.context.RunContext`).
274
- Its only method is `ctx.read(name)`, where `name` is one of the read
275
- names declared under the node's `reads:` map in the contract — reading
276
- anything else raises `ReadError`. Each declared read is fetched once and
277
- memoized; `ctx.read(name)` returns a `pyarrow.Table`.
278
- - `run(ctx)` can return anything Arrow-convertible: a `pyarrow.Table`
279
- as-is, a pandas `DataFrame` (converted via
280
- `pa.Table.from_pandas(..., preserve_index=False)`), or any object
281
- implementing the Arrow C stream protocol (`__arrow_c_stream__`) — for
282
- example a polars DataFrame. Returning anything else raises `ScriptError`.
283
- - The dataframe library is your choice. No dataframe library is baked into
284
- the base image — the package's own runtime dependencies are `pyarrow`,
285
- `PyYAML`, and `continuo-engine-contract`. Add whatever you script
286
- against (pandas, polars, …) as a `RUN pip install` line in your own
287
- `Dockerfile`, on top of the base image. The base image runs as non-root
288
- (uid 65532), which pip cannot install under, so switch to root for the
289
- install and back afterward — `USER root`, then the `RUN pip install`
290
- line, then `USER 65532:65532` — since the executor's pod spec expects
291
- the image to end at uid 65532. See `template/Dockerfile` for the pattern.
292
- - Scripts do not import warehouse drivers, write raw SQL literals, or call
293
- data-access methods directly — `continuo-runtime lint` rejects those:
294
- - forbidden driver imports (`psycopg2`/`sqlalchemy`/`trino`/etc.),
295
- - SQL string literals (in plain strings, f-strings, and `+` concatenation),
296
- - forbidden data-access calls (`execute`/`read_sql`/etc.), including ones
297
- reached via a `from ... import` alias (e.g. `from pandas import
298
- read_sql as rs` then calling `rs(...)`),
299
- - private/protected attribute access (`obj._x`) — except on `self`/`cls`,
300
- so a script's own class-private helpers (`self._helper()`) aren't
301
- flagged.
302
-
303
- The SQL-literal rule is best-effort: docstrings are exempt, but other
304
- prose may still occasionally match. The hard guarantees enforced by lint
305
- are the driver-import and data-access-call rules, together with the fact
306
- that `RunContext` only exposes `ctx.read()` — all warehouse access goes
307
- through it.
308
- - Scripts may import shared in-repo helpers. Before executing a script the
309
- harness puts the repo root (`APP_ROOT`) and the script's own directory on
310
- `sys.path`, so both `import helpers` (a sibling of the script) and
311
- `from lib.shared import ...` (anywhere under the repo root) work, including
312
- from inside `run()`. Every helper a script reaches transitively is folded
313
- into `shared_code_hash`, so editing one re-fingerprints the node — but the
314
- hash does not put the file in the image: **`COPY` every directory your
315
- scripts import from in your `Dockerfile`**, or the release is valid and the
316
- node dies with `ModuleNotFoundError` on its first run. Because the repo root
317
- precedes the standard library on `sys.path`, avoid naming a top-level module
318
- after a stdlib one (`types.py`, `json.py`, `logging.py`, …).
319
- - The harness — not the script — performs the write. It calls `conform()`
320
- on whatever `run()` returned and issues the only INSERT; the script never
321
- writes directly.
322
-
323
- ## Conform rules
324
-
325
- `conform()` (`continuo_python_runtime/conform.py`) enforces the node's
326
- declared `output_columns` on the table `run()` returned, in this order:
327
-
328
- | Check | Behavior |
329
- | --- | --- |
330
- | Duplicate columns | Any duplicate column name in the returned table always raises `ConformError`. |
331
- | Extra columns | Governed by the node's `extra_columns` policy: `raise` (default) fails the run; `warn` drops the undeclared column(s) and logs a warning. |
332
- | Missing columns | Any declared column absent from the returned table always raises `ConformError`. |
333
- | Column order | The table is reselected into the declared column order. |
334
- | Strict cast | Each column is cast to its declared Arrow type with `safe=True`. Casts pyarrow's `safe=True` would silently accept but that are not value-lossless are rejected before the cast even runs: floating → decimal (rounds to scale), non-boolean → boolean (coerces truthiness), timestamp → date (drops time-of-day). Any other cast failure also raises `ConformError`. |
335
- | Not-null | A column declared `nullable: false` that contains any null raises `ConformError`. |
336
- | VARCHAR/CHAR length | A column declared `VARCHAR(n)`/`CHAR(n)` whose longest value exceeds `n` raises `ConformError`. |
337
-
338
- ## Error taxonomy
339
-
340
- Every runtime failure is one of five `HarnessError` subclasses
341
- (`continuo_python_runtime/errors.py`). The sentinel result block's message
342
- is prefixed `<ErrorClass>: ` so failures can be triaged without parsing free
343
- text. The harness also logs the same message at ERROR on stderr, with the
344
- traceback of the exception it wraps (a driver error, the script's own
345
- exception), so the stored log of a failed run names its failure: Continuo cuts
346
- the result block out of the log before storing it.
347
-
348
- | Class | Meaning | Typical fix target |
349
- | --- | --- | --- |
350
- | `ContractError` | Contract missing or invalid, node not found for `NODE_ID`, or the declared script is missing/unreachable. | The contract yaml or the `script:` path. |
351
- | `ReadError` | `ctx.read()` was called with an undeclared name, or a declared read failed at the warehouse. | The `reads:` map, or the upstream query/warehouse access. |
352
- | `ScriptError` | `run()` raised, has no callable `run`, or returned a value that isn't Arrow-convertible. | The node script. |
353
- | `ConformError` | Structural mismatch (extra/missing/duplicate columns), a strict-cast failure, a not-null violation, a VARCHAR/CHAR overflow, or an `upsert` run whose rows repeat a primary key. | The script's output shape, or the `output_columns` declaration. |
354
- | `LoadError` | Adapter construction failed, the installed engine does not support the node's `mode_type`, the live table's shape differs from `output_columns` (append/upsert), or the DDL/INSERT failed at the warehouse during the write. | Warehouse connectivity/permissions, the engine image, or the target table. |
355
-
356
- ## Engine selection
357
-
358
- A domain repo picks its warehouse engine by which base image it builds
359
- `FROM`:
360
-
361
- ```dockerfile
362
- FROM ghcr.io/carolsimone/continuo-python-runtime-postgres:v0.11.0
363
- # or
364
- FROM ghcr.io/carolsimone/continuo-python-runtime-trino:v0.11.0
365
- # or
366
- FROM ghcr.io/carolsimone/continuo-python-runtime-duckdb:v0.11.0
367
- ```
368
-
369
- The engine is part of the image **name**; the tag is the bare version, so
370
- Continuo's Helm chart can pin an image as `<name>:vX.Y.Z@sha256:<digest>`.
371
-
372
- Each image bakes in exactly one `WarehouseAdapter` for that engine — the
373
- pinned PyPI version of the `continuo-postgres-adapter`,
374
- `continuo-trino-adapter` or `continuo-duckdb-adapter` package built from this
375
- repo's `adapters/postgres/`, `adapters/trino/` or `adapters/duckdb/` source
376
- (see the table above) — registered under the
377
- `continuo_engine.adapters` entry-point group (entry names `postgres` /
378
- `trino` / `duckdb`). The runtime discovers it via `discover_adapter()` at run time, so a
379
- single image serves every node in the service and the release-time
380
- validation Job for it. The executor injects the warehouse connection as
381
- environment variables (engine-native, e.g.
382
- `POSTGRES_HOST`/`POSTGRES_DB`/`POSTGRES_USER`) plus the node-selection
383
- environment (`NODE_ID`, `TABLE_NAME`, `TARGET_SCHEMA`, and optionally
384
- `CONTRACT_DIR`/`APP_ROOT`) that `continuo-runtime run` reads to dispatch the
385
- right node's script.
386
-
387
- ### Build your own container
388
-
389
- A domain repo does not have to build `FROM` the published engine image.
390
- `template/` ships two Dockerfiles for the two build shapes (see
391
- `template/README.md` § "Choosing a base" for the full comparison):
392
-
393
- - **Shape 1 — `template/Dockerfile`** — `FROM` the published engine image
394
- (`continuo-python-runtime-<engine>`), as shown above. Simplest; the image
395
- already has the runtime and adapter installed and pinned.
396
- - **Shape 2 — `template/Dockerfile.pip`** — your own base image, installing
397
- `continuo-python-runtime` and one `continuo-<engine>-adapter` from PyPI
398
- via a hash-locked `requirements.lock` (`template/requirements.lock`). Use
399
- this when you must control the base image yourself.
400
-
401
- Both shapes end up running the same runtime and the same adapter version;
402
- which one you pick only changes who controls the base OS layer underneath
403
- them.
404
-
405
- ## Further reading
406
-
407
- - `docs/superpowers/specs/2026-07-31-python-runtime-design.md` — this
408
- repo's design.
409
- - `docs/boundary-contract.md` — the parent design's boundary contract (§13):
410
- the five surfaces (S3 artifact, `content_hash`, the release call, the
411
- runtime image, and the domain repo's CI/CD) that this repo implements.