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.
- continuo_python_runtime/cli.py +108 -37
- continuo_python_runtime/content_check.py +73 -0
- continuo_python_runtime/contract/kinds.py +37 -21
- continuo_python_runtime/contract/loader.py +207 -389
- continuo_python_runtime/contract/model.py +13 -6
- continuo_python_runtime/contract/pack.py +299 -0
- continuo_python_runtime/contract/paths.py +34 -1
- continuo_python_runtime/contract/read_tables.py +85 -0
- continuo_python_runtime/errors.py +13 -1
- continuo_python_runtime/harness.py +21 -6
- continuo_python_runtime/hash_inputs.py +63 -0
- continuo_python_runtime/hashing.py +54 -72
- continuo_python_runtime/lint.py +194 -6
- continuo_python_runtime/packages.py +56 -0
- continuo_python_runtime/validation/preflight.py +410 -0
- continuo_python_runtime/validation/runner.py +20 -3
- continuo_python_runtime-0.13.0.dist-info/METADATA +600 -0
- continuo_python_runtime-0.13.0.dist-info/RECORD +36 -0
- continuo_python_runtime/contract/merge.py +0 -197
- continuo_python_runtime/contract/secret_ref.py +0 -31
- continuo_python_runtime-0.11.0.dist-info/METADATA +0 -411
- continuo_python_runtime-0.11.0.dist-info/RECORD +0 -32
- {continuo_python_runtime-0.11.0.dist-info → continuo_python_runtime-0.13.0.dist-info}/WHEEL +0 -0
- {continuo_python_runtime-0.11.0.dist-info → continuo_python_runtime-0.13.0.dist-info}/entry_points.txt +0 -0
- {continuo_python_runtime-0.11.0.dist-info → continuo_python_runtime-0.13.0.dist-info}/licenses/LICENSE +0 -0
- {continuo_python_runtime-0.11.0.dist-info → continuo_python_runtime-0.13.0.dist-info}/licenses/NOTICE +0 -0
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""The runtime's view of a node, read from its ODCS contract."""
|
|
2
2
|
|
|
3
3
|
from dataclasses import dataclass, field
|
|
4
|
+
from pathlib import Path
|
|
4
5
|
from typing import Any
|
|
5
6
|
|
|
7
|
+
from continuo_contracts.python import PythonNode
|
|
8
|
+
|
|
6
9
|
# Module-level constants
|
|
7
|
-
CRITICALITIES = frozenset({"REGULATORY", "CORE", "SECONDARY"})
|
|
8
|
-
EXTRA_COLUMNS_POLICIES = frozenset({"raise", "warn"})
|
|
9
10
|
KINDS = frozenset({"python-node", "python-csv", "python-api"})
|
|
10
11
|
DEFAULT_KIND = "python-node"
|
|
11
12
|
# How the harness writes a node's table on each run: replace empties it first,
|
|
@@ -13,7 +14,6 @@ DEFAULT_KIND = "python-node"
|
|
|
13
14
|
# primary_key exists and keeps the rest.
|
|
14
15
|
MODE_TYPES = frozenset({"append", "upsert", "replace"})
|
|
15
16
|
DEFAULT_MODE_TYPE = "replace"
|
|
16
|
-
CONTRACT_VERSION = 1
|
|
17
17
|
|
|
18
18
|
|
|
19
19
|
@dataclass(frozen=True)
|
|
@@ -27,7 +27,12 @@ class Column:
|
|
|
27
27
|
|
|
28
28
|
@dataclass(frozen=True)
|
|
29
29
|
class Node:
|
|
30
|
-
"""A node
|
|
30
|
+
"""A node: the table it fills, how it fills it and the contract it is read from.
|
|
31
|
+
|
|
32
|
+
``python`` is the ``PythonNode`` continuo-contracts reads from the same
|
|
33
|
+
contract, and ``path`` is the contract file. ``primary_key`` is the key the
|
|
34
|
+
harness upserts on, empty unless ``mode_type`` is upsert.
|
|
35
|
+
"""
|
|
31
36
|
|
|
32
37
|
schema: str
|
|
33
38
|
table: str
|
|
@@ -37,15 +42,17 @@ class Node:
|
|
|
37
42
|
script: str
|
|
38
43
|
reads: dict[str, str]
|
|
39
44
|
output_columns: tuple[Column, ...]
|
|
45
|
+
python: PythonNode
|
|
46
|
+
path: Path
|
|
40
47
|
description: str = ""
|
|
41
48
|
extra_columns: str = "raise"
|
|
42
49
|
config: dict[str, Any] = field(default_factory=dict)
|
|
43
|
-
content_hash: str | None = None
|
|
44
50
|
kind: str = DEFAULT_KIND
|
|
45
51
|
secret_ref: str = ""
|
|
46
52
|
mode_type: str = DEFAULT_MODE_TYPE
|
|
47
53
|
primary_key: tuple[str, ...] = ()
|
|
48
54
|
timeout_minutes: int | None = None
|
|
55
|
+
assets: tuple[str, ...] = ()
|
|
49
56
|
|
|
50
57
|
@property
|
|
51
58
|
def relation(self) -> str:
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
"""``continuo-runtime pack``: the bundle of a service's ODCS contracts.
|
|
2
|
+
|
|
3
|
+
A service's CI packs the contracts of its ``contracts/`` folder into one
|
|
4
|
+
``odcs-bundle.json`` and uploads it with the release. The bundle is UTF-8 JSON,
|
|
5
|
+
written by :func:`write_bundle` as ``json.dumps(doc, sort_keys=True, indent=2,
|
|
6
|
+
ensure_ascii=False)`` and a newline, and holds::
|
|
7
|
+
|
|
8
|
+
{"bundle_version": 1,
|
|
9
|
+
"service": <service>,
|
|
10
|
+
"producer": {"continuo_python_runtime": <version>, "continuo_contracts": <version>},
|
|
11
|
+
"image_packages": {<name>: <version>},
|
|
12
|
+
"nodes": [{"path": <repo path of the contract file>,
|
|
13
|
+
"text": <the file's text as written>,
|
|
14
|
+
"source_hash": <bare hex>,
|
|
15
|
+
"shared_code_hash": <bare hex, or "" when the node has none>}]}
|
|
16
|
+
|
|
17
|
+
``nodes`` is sorted by ``path``. A node's ``source_hash`` and ``shared_code_hash``
|
|
18
|
+
are the two parts :func:`~continuo_python_runtime.hashing.hash_parts` computes from
|
|
19
|
+
the files of the repository; the third part, the config hash, is computed from the
|
|
20
|
+
contract text by whoever reads the bundle. ``image_packages`` is the package list of
|
|
21
|
+
the image the service runs, read from that image, never from the environment ``pack``
|
|
22
|
+
runs in.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import contextlib
|
|
28
|
+
import json
|
|
29
|
+
import os
|
|
30
|
+
import subprocess
|
|
31
|
+
import uuid
|
|
32
|
+
from collections.abc import Mapping
|
|
33
|
+
from importlib import metadata
|
|
34
|
+
from pathlib import Path
|
|
35
|
+
from typing import Any
|
|
36
|
+
|
|
37
|
+
from continuo_contracts.validate import validate_python_contract
|
|
38
|
+
|
|
39
|
+
from continuo_python_runtime.contract.loader import (
|
|
40
|
+
issue_lines,
|
|
41
|
+
load_contract_dir,
|
|
42
|
+
parse_contract,
|
|
43
|
+
read_contract_text,
|
|
44
|
+
)
|
|
45
|
+
from continuo_python_runtime.contract.model import Node
|
|
46
|
+
from continuo_python_runtime.errors import ContractError
|
|
47
|
+
from continuo_python_runtime.hash_inputs import gather_hash_inputs
|
|
48
|
+
from continuo_python_runtime.hashing import hash_parts
|
|
49
|
+
from continuo_python_runtime.lint import lint_source
|
|
50
|
+
|
|
51
|
+
BUNDLE_VERSION = 1
|
|
52
|
+
|
|
53
|
+
PACKAGE_SOURCE_USAGE = (
|
|
54
|
+
"pack records the package list of the image the service runs: give exactly one of "
|
|
55
|
+
"--image <ref> (read from the image) or --image-packages <file> "
|
|
56
|
+
"(a JSON object of package name to version)"
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
# What `docker run` exits with when docker itself, not the container, failed.
|
|
60
|
+
_DOCKER_OWN_FAILURE = 125
|
|
61
|
+
_STARTUP_HOOKS = ("sitecustomize.py", "usercustomize.py")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _lint_node_closure(
|
|
65
|
+
node: Node,
|
|
66
|
+
repo_root: Path,
|
|
67
|
+
code_files: tuple[tuple[Path, bytes], ...],
|
|
68
|
+
) -> None:
|
|
69
|
+
"""Lint the node's script and every resolved closure member.
|
|
70
|
+
|
|
71
|
+
Every file that executes for this node — the script plus its transitive
|
|
72
|
+
in-repo import closure — is held to the same lint rules
|
|
73
|
+
(``continuo_python_runtime.lint.lint_source``: L1 forbidden driver
|
|
74
|
+
imports, L2 SQL string literals, L3 forbidden data-access calls, L4
|
|
75
|
+
private-attribute access, L5 dynamic-import constructs, L6 constructs
|
|
76
|
+
that run code the hash cannot see) that CI's
|
|
77
|
+
``continuo-runtime lint`` applies to ``scripts/``. Enforcing it again
|
|
78
|
+
here, at pack 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 bundle is the
|
|
82
|
+
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
|
+
violations: list[str] = []
|
|
111
|
+
for path, data in code_files:
|
|
112
|
+
rel = path.relative_to(repo_root_resolved)
|
|
113
|
+
try:
|
|
114
|
+
text = data.decode("utf-8-sig")
|
|
115
|
+
except UnicodeDecodeError as exc:
|
|
116
|
+
raise ContractError(f"{node.relation}: {rel}: not valid UTF-8: {exc}") from exc
|
|
117
|
+
violations.extend(lint_source(text, str(rel)))
|
|
118
|
+
|
|
119
|
+
if violations:
|
|
120
|
+
report = "\n".join(violations)
|
|
121
|
+
raise ContractError(
|
|
122
|
+
f"{node.relation}: lint violations in script or import closure:\n{report}"
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _refuse_startup_hooks(repo_root: Path) -> None:
|
|
127
|
+
"""Refuse a ``sitecustomize.py`` or ``usercustomize.py`` at the repository root.
|
|
128
|
+
|
|
129
|
+
Python imports either at startup, before the harness, so nothing in a node's
|
|
130
|
+
import closure reaches it and the hash cannot see it.
|
|
131
|
+
"""
|
|
132
|
+
for hook in _STARTUP_HOOKS:
|
|
133
|
+
if (repo_root / hook).exists():
|
|
134
|
+
raise ContractError(
|
|
135
|
+
f"{hook} at the repository root runs before the harness and is not in the hash"
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _repo_path(file: Path, repo_root: Path) -> str:
|
|
140
|
+
"""The POSIX path of the contract ``file`` below ``repo_root``, as the bundle names it.
|
|
141
|
+
|
|
142
|
+
The folder of ``file`` and ``repo_root`` are resolved, so the path does not
|
|
143
|
+
depend on how either is spelled (relative, through a symlink). Raises
|
|
144
|
+
``ContractError`` for a contract outside the repository root.
|
|
145
|
+
"""
|
|
146
|
+
resolved = file.parent.resolve() / file.name
|
|
147
|
+
try:
|
|
148
|
+
return resolved.relative_to(repo_root.resolve()).as_posix()
|
|
149
|
+
except ValueError:
|
|
150
|
+
raise ContractError(
|
|
151
|
+
f"{file}: the contract is not inside the repository root {repo_root}"
|
|
152
|
+
) from None
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def build_bundle(
|
|
156
|
+
contract_dir: Path,
|
|
157
|
+
repo_root: Path,
|
|
158
|
+
service: str,
|
|
159
|
+
image_packages: Mapping[str, str],
|
|
160
|
+
*,
|
|
161
|
+
dialect: str | None = None,
|
|
162
|
+
) -> dict[str, Any]:
|
|
163
|
+
"""Build and return the bundle of the contracts in ``contract_dir``.
|
|
164
|
+
|
|
165
|
+
The contracts are loaded as :func:`~continuo_python_runtime.contract.loader
|
|
166
|
+
.load_contract_dir` loads them, every read checked under ``dialect`` (``None``
|
|
167
|
+
is sqlglot's dialect-neutral parser). Each contract is then checked once more
|
|
168
|
+
against ``service`` by continuo-contracts, as the release does: one
|
|
169
|
+
``ContractError`` lists every issue of every file, one line each, naming the
|
|
170
|
+
file by its path below ``repo_root``.
|
|
171
|
+
|
|
172
|
+
Each node's script, in-repo import closure and assets are gathered from
|
|
173
|
+
``repo_root``, every file that executes is linted by :func:`_lint_node_closure`
|
|
174
|
+
and the two hash parts of the bundle are computed.
|
|
175
|
+
|
|
176
|
+
Raises ``ContractError`` for any refusal above, for a ``sitecustomize.py`` or
|
|
177
|
+
``usercustomize.py`` at ``repo_root``, for a script or asset that is missing or
|
|
178
|
+
leaves ``repo_root``, and for a contract outside ``repo_root``.
|
|
179
|
+
"""
|
|
180
|
+
nodes = load_contract_dir(contract_dir, dialect=dialect, check_reads=True)
|
|
181
|
+
_refuse_startup_hooks(repo_root)
|
|
182
|
+
|
|
183
|
+
files = [(node, _repo_path(node.path, repo_root), read_contract_text(node.path)) for node in nodes]
|
|
184
|
+
issues: list[str] = []
|
|
185
|
+
for _, path, text in files:
|
|
186
|
+
found = validate_python_contract(parse_contract(text, path), path=path, service=service)
|
|
187
|
+
issues.extend(issue_lines(path, found))
|
|
188
|
+
if issues:
|
|
189
|
+
raise ContractError("\n".join(issues))
|
|
190
|
+
|
|
191
|
+
entries = []
|
|
192
|
+
for node, path, text in files:
|
|
193
|
+
inputs = gather_hash_inputs(node, repo_root)
|
|
194
|
+
_lint_node_closure(node, repo_root, inputs.code_files)
|
|
195
|
+
parts = hash_parts(node, inputs.primary, inputs.units)
|
|
196
|
+
entries.append(
|
|
197
|
+
{
|
|
198
|
+
"path": path,
|
|
199
|
+
"text": text,
|
|
200
|
+
"source_hash": parts["source_hash"],
|
|
201
|
+
"shared_code_hash": parts["shared_code_hash"],
|
|
202
|
+
}
|
|
203
|
+
)
|
|
204
|
+
entries.sort(key=lambda entry: entry["path"])
|
|
205
|
+
|
|
206
|
+
return {
|
|
207
|
+
"bundle_version": BUNDLE_VERSION,
|
|
208
|
+
"service": service,
|
|
209
|
+
"producer": {
|
|
210
|
+
"continuo_python_runtime": metadata.version("continuo-python-runtime"),
|
|
211
|
+
"continuo_contracts": metadata.version("continuo-contracts"),
|
|
212
|
+
},
|
|
213
|
+
"image_packages": dict(image_packages),
|
|
214
|
+
"nodes": entries,
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def write_bundle(doc: Mapping[str, Any], out: Path) -> None:
|
|
219
|
+
"""Write ``doc`` to ``out`` as the bundle's JSON, creating ``out``'s missing folders.
|
|
220
|
+
|
|
221
|
+
The JSON goes to a temporary file in ``out``'s folder, which is renamed over
|
|
222
|
+
``out`` once written, so a failure leaves no partial ``out`` (and a file that
|
|
223
|
+
was there stays as it was) and no temporary file.
|
|
224
|
+
"""
|
|
225
|
+
data = (json.dumps(doc, sort_keys=True, indent=2, ensure_ascii=False) + "\n").encode("utf-8")
|
|
226
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
227
|
+
temporary = out.with_name(f".{out.name}.{uuid.uuid4().hex}.tmp")
|
|
228
|
+
try:
|
|
229
|
+
with open(temporary, "xb") as handle:
|
|
230
|
+
handle.write(data)
|
|
231
|
+
handle.flush()
|
|
232
|
+
os.fsync(handle.fileno())
|
|
233
|
+
os.replace(temporary, out)
|
|
234
|
+
except BaseException:
|
|
235
|
+
with contextlib.suppress(FileNotFoundError):
|
|
236
|
+
temporary.unlink()
|
|
237
|
+
raise
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _parse_packages(text: str, source: str) -> dict[str, str]:
|
|
241
|
+
"""Return the package list in ``text``: one JSON object of name to version strings.
|
|
242
|
+
|
|
243
|
+
``source`` names where the text came from, for the refusals.
|
|
244
|
+
"""
|
|
245
|
+
try:
|
|
246
|
+
value = json.loads(text)
|
|
247
|
+
except ValueError as exc:
|
|
248
|
+
raise ContractError(f"{source} is not JSON: {exc}") from None
|
|
249
|
+
if not isinstance(value, dict) or not all(isinstance(version, str) for version in value.values()):
|
|
250
|
+
raise ContractError(f"{source} must be one JSON object of name to version strings")
|
|
251
|
+
return value
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _packages_from_file(path: Path) -> dict[str, str]:
|
|
255
|
+
try:
|
|
256
|
+
text = path.read_text(encoding="utf-8")
|
|
257
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
258
|
+
raise ContractError(f"{path}: cannot read the package list ({exc})") from None
|
|
259
|
+
return _parse_packages(text, str(path))
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _packages_from_image(image: str) -> dict[str, str]:
|
|
263
|
+
command = ["docker", "run", "--rm", "--entrypoint", "continuo-runtime", image, "packages"]
|
|
264
|
+
try:
|
|
265
|
+
result = subprocess.run(
|
|
266
|
+
command, capture_output=True, text=True, encoding="utf-8", errors="replace", check=False
|
|
267
|
+
)
|
|
268
|
+
except OSError as exc:
|
|
269
|
+
raise ContractError(
|
|
270
|
+
f"{image}: cannot read the package list of the image, `docker` could not be run ({exc})"
|
|
271
|
+
) from None
|
|
272
|
+
if result.returncode != 0:
|
|
273
|
+
detail = result.stderr.strip() or "no output"
|
|
274
|
+
if result.returncode == _DOCKER_OWN_FAILURE:
|
|
275
|
+
raise ContractError(f"{image}: docker could not run the image: {detail}")
|
|
276
|
+
raise ContractError(
|
|
277
|
+
f"{image}: the image has no `packages` command: build it on continuo-python-runtime "
|
|
278
|
+
f"0.13.0 or later (`docker run` exited with status {result.returncode}: {detail})"
|
|
279
|
+
)
|
|
280
|
+
return _parse_packages(result.stdout, f"{image}: the output of its `packages` command")
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def image_packages_from(*, image: str | None, image_packages: Path | None) -> dict[str, str]:
|
|
284
|
+
"""Return the package list ``pack`` records, from exactly one of two sources.
|
|
285
|
+
|
|
286
|
+
``image`` is an image reference: its list is the output of ``docker run --rm
|
|
287
|
+
--entrypoint continuo-runtime <image> packages``. ``image_packages`` is a file
|
|
288
|
+
that holds that output, one JSON object of package name to version string.
|
|
289
|
+
|
|
290
|
+
Raises ``ContractError`` when neither or both are given, and, for an image,
|
|
291
|
+
when ``docker`` cannot be run, exits with a non-zero status (the image has no
|
|
292
|
+
``packages`` command, or docker could not run it) or prints anything but one
|
|
293
|
+
JSON object of strings; for a file, when it cannot be read or does not hold one.
|
|
294
|
+
"""
|
|
295
|
+
if image is not None and image_packages is None:
|
|
296
|
+
return _packages_from_image(image)
|
|
297
|
+
if image is None and image_packages is not None:
|
|
298
|
+
return _packages_from_file(image_packages)
|
|
299
|
+
raise ContractError(PACKAGE_SOURCE_USAGE)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""Shared script-path resolution used by both
|
|
1
|
+
"""Shared script-path resolution used by both hashing and the harness."""
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
@@ -36,3 +36,36 @@ def resolve_script_path(script: str, repo_root: Path, *, context: str) -> Path:
|
|
|
36
36
|
raise ContractError(f"{context}: script not found: {script}")
|
|
37
37
|
|
|
38
38
|
return script_path
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def resolve_asset_path(asset: str, repo_root: Path, *, context: str) -> Path:
|
|
42
|
+
"""Resolve ``asset`` (relative to ``repo_root``) and validate it.
|
|
43
|
+
|
|
44
|
+
Rejects absolute paths, paths that escape ``repo_root`` once symlinks
|
|
45
|
+
resolve, paths that do not exist and paths that are not a regular file.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
asset: The asset path as declared in the contract, relative to
|
|
49
|
+
``repo_root``.
|
|
50
|
+
repo_root: The repository root the asset path is resolved against.
|
|
51
|
+
context: A label prefixed to every error message (e.g. a node's
|
|
52
|
+
relation) to identify which node's asset failed.
|
|
53
|
+
|
|
54
|
+
Raises:
|
|
55
|
+
ContractError: If the path is absolute, escapes the repository root,
|
|
56
|
+
does not exist or is not a file.
|
|
57
|
+
"""
|
|
58
|
+
if Path(asset).is_absolute():
|
|
59
|
+
raise ContractError(
|
|
60
|
+
f"{context}: asset path {asset!r} must be relative to the repository root"
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
asset_path = (repo_root / asset).resolve()
|
|
64
|
+
if not asset_path.is_relative_to(repo_root.resolve()):
|
|
65
|
+
raise ContractError(f"{context}: asset path {asset!r} escapes the repository root")
|
|
66
|
+
if not asset_path.exists():
|
|
67
|
+
raise ContractError(f"{context}: asset not found: {asset}")
|
|
68
|
+
if not asset_path.is_file():
|
|
69
|
+
raise ContractError(f"{context}: asset {asset!r} is not a file")
|
|
70
|
+
|
|
71
|
+
return asset_path
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""The tables a read query names without their schema.
|
|
2
|
+
|
|
3
|
+
Which relation a table with no schema means depends on the session's search
|
|
4
|
+
path, so a read query must name the schema of every table it reads. The one
|
|
5
|
+
name that goes without a schema is a reference to a CTE that is in scope where
|
|
6
|
+
the name is used: the body of ``WITH orders AS (SELECT * FROM orders)`` reads
|
|
7
|
+
the table ``orders``, not the CTE it defines, while the CTEs of a
|
|
8
|
+
``WITH RECURSIVE`` list all see each other.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import sqlglot
|
|
14
|
+
from sqlglot import exp
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def unqualified_tables(sql: str, *, dialect: str | None) -> list[str]:
|
|
18
|
+
"""Return the lower-case names of the tables ``sql`` names with no schema.
|
|
19
|
+
|
|
20
|
+
Each table is listed once, in the order sqlglot walks the query: the tables
|
|
21
|
+
of the outer query come before those of its subqueries. A name with no
|
|
22
|
+
schema is skipped only when it refers to a CTE that is in scope where the
|
|
23
|
+
name is written. In a ``WITH`` list a CTE is in scope in the CTEs defined
|
|
24
|
+
after it, in the query that carries the ``WITH`` clause and in the
|
|
25
|
+
subqueries of those, and not in its own body. In a ``WITH RECURSIVE`` list
|
|
26
|
+
every CTE is in scope in every CTE body of the list, itself and the CTEs
|
|
27
|
+
defined after it included, and in the query that carries the clause and its
|
|
28
|
+
subqueries. A CTE is never in scope in a query that contains the query that
|
|
29
|
+
defines it. Any other name with no schema is a table, even when a CTE of
|
|
30
|
+
that name is defined somewhere else in the query, and a qualified name is
|
|
31
|
+
never a CTE reference and is never listed. A table with no schema and no
|
|
32
|
+
name, which sqlglot models for a table function such as
|
|
33
|
+
``generate_series(1, 3)``, is listed by its SQL text under ``dialect``
|
|
34
|
+
(lower case, without its alias). A table function that names its schema
|
|
35
|
+
(``pg_catalog.generate_series(1, 3)``) reads no relation and is skipped.
|
|
36
|
+
|
|
37
|
+
``dialect`` is the sqlglot dialect the query is parsed under (``None`` is
|
|
38
|
+
sqlglot's neutral grammar). A query sqlglot cannot parse raises sqlglot's
|
|
39
|
+
own error: callers check that the query is one read first.
|
|
40
|
+
"""
|
|
41
|
+
parsed = sqlglot.parse_one(sql, dialect=dialect)
|
|
42
|
+
|
|
43
|
+
named: list[str] = []
|
|
44
|
+
for table in parsed.find_all(exp.Table):
|
|
45
|
+
if table.db:
|
|
46
|
+
continue
|
|
47
|
+
name = table.name.lower() or _sql_text(table, dialect)
|
|
48
|
+
if (table.name and _names_a_visible_cte(table, name)) or name in named:
|
|
49
|
+
continue
|
|
50
|
+
named.append(name)
|
|
51
|
+
return named
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _names_a_visible_cte(table: exp.Table, name: str) -> bool:
|
|
55
|
+
"""Whether the unqualified ``table`` refers to a CTE called ``name`` (lower case).
|
|
56
|
+
|
|
57
|
+
Climbs from the table through its parents, so every kind of statement
|
|
58
|
+
resolves the same way, one sqlglot cannot build a scope for (DuckDB's
|
|
59
|
+
``PIVOT`` statement) included. A query that carries a ``WITH`` clause shows
|
|
60
|
+
every CTE of the clause to everything under it except the clause itself. A
|
|
61
|
+
CTE body sees, in the clause it stands in, the CTEs defined before it, or
|
|
62
|
+
all of them under ``WITH RECURSIVE``. Names compare in lower case.
|
|
63
|
+
"""
|
|
64
|
+
child: exp.Expr = table
|
|
65
|
+
node = table.parent
|
|
66
|
+
while node is not None:
|
|
67
|
+
visible: list[exp.Expr]
|
|
68
|
+
if isinstance(node, exp.With):
|
|
69
|
+
ctes = list(node.expressions)
|
|
70
|
+
position = next((i for i, cte in enumerate(ctes) if cte is child), 0)
|
|
71
|
+
visible = ctes if node.recursive else ctes[:position]
|
|
72
|
+
else:
|
|
73
|
+
clause = node.args.get("with_")
|
|
74
|
+
visible = list(clause.expressions) if isinstance(clause, exp.With) and clause is not child else []
|
|
75
|
+
if any(cte.alias.lower() == name for cte in visible):
|
|
76
|
+
return True
|
|
77
|
+
child, node = node, node.parent
|
|
78
|
+
return False
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _sql_text(table: exp.Table, dialect: str | None) -> str:
|
|
82
|
+
"""The lower-case SQL of a table that has no name, without its alias."""
|
|
83
|
+
bare = table.copy()
|
|
84
|
+
bare.set("alias", None)
|
|
85
|
+
return bare.sql(dialect=dialect).lower()
|
|
@@ -6,7 +6,13 @@ remediation classifier can key off it without parsing free text.
|
|
|
6
6
|
|
|
7
7
|
|
|
8
8
|
class HarnessError(Exception):
|
|
9
|
-
"""Base for all runtime failures the harness converts to a sentinel block.
|
|
9
|
+
"""Base for all runtime failures the harness converts to a sentinel block.
|
|
10
|
+
|
|
11
|
+
``reason`` is a machine-readable code the block carries beside the message;
|
|
12
|
+
empty for the errors that have none.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
reason: str = ""
|
|
10
16
|
|
|
11
17
|
@property
|
|
12
18
|
def error_class(self) -> str:
|
|
@@ -20,6 +26,12 @@ class ContractError(HarnessError):
|
|
|
20
26
|
"""Contract missing, invalid, node not found, or script missing."""
|
|
21
27
|
|
|
22
28
|
|
|
29
|
+
class ImageContractMismatch(ContractError):
|
|
30
|
+
"""The image does not hold the contract, script, imports or assets the release hashed."""
|
|
31
|
+
|
|
32
|
+
reason = "image_contract_mismatch"
|
|
33
|
+
|
|
34
|
+
|
|
23
35
|
class ReadError(HarnessError):
|
|
24
36
|
"""Unknown read name, or a declared read failed at the warehouse."""
|
|
25
37
|
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
"""Container entrypoint: dispatches a single node's script and writes its output.
|
|
2
2
|
|
|
3
|
-
``run_node`` is the sole write sink for a python node. It
|
|
4
|
-
|
|
3
|
+
``run_node`` is the sole write sink for a python node. It reads the ODCS
|
|
4
|
+
contracts in ``CONTRACT_DIR`` (one ``*.odcs.yaml`` file per node), selects
|
|
5
|
+
the node, loads and executes its script inside a
|
|
5
6
|
:class:`~continuo_python_runtime.context.RunContext`, conforms the result to
|
|
6
7
|
the declared schema, and writes it through the runtime adapter with the
|
|
7
8
|
node's ``mode_type``: ``load`` (replace), ``append`` or ``upsert``. Exactly one
|
|
@@ -32,6 +33,7 @@ from continuo_engine_contract.port import ( # type: ignore[import-untyped]
|
|
|
32
33
|
from continuo_engine_contract.result import result_block # type: ignore[import-untyped]
|
|
33
34
|
|
|
34
35
|
from continuo_python_runtime.conform import conform, to_arrow
|
|
36
|
+
from continuo_python_runtime.content_check import check_image_contract
|
|
35
37
|
from continuo_python_runtime.context import RunContext
|
|
36
38
|
from continuo_python_runtime.contract.loader import load_contract_dir
|
|
37
39
|
from continuo_python_runtime.contract.model import Node
|
|
@@ -62,7 +64,7 @@ def select_node(nodes: list[Node], node_id: str) -> Node:
|
|
|
62
64
|
"""Select the node matching the trailing ``schema.table`` of ``node_id``.
|
|
63
65
|
|
|
64
66
|
``node_id`` is split on ``.``; the trailing two segments are taken as
|
|
65
|
-
``(schema, table)`` and matched against the
|
|
67
|
+
``(schema, table)`` and matched against the nodes the contracts declare.
|
|
66
68
|
|
|
67
69
|
Raises:
|
|
68
70
|
ContractError: If ``node_id`` has fewer than 2 dot-separated
|
|
@@ -318,10 +320,16 @@ def run_node(
|
|
|
318
320
|
) -> int:
|
|
319
321
|
"""Run a single node end-to-end and print exactly one sentinel result block.
|
|
320
322
|
|
|
323
|
+
``env`` names the node (``NODE_ID``, ``TABLE_NAME``, ``TARGET_SCHEMA``) and
|
|
324
|
+
where it lives: ``CONTRACT_DIR`` holds the node contracts (``*.odcs.yaml``,
|
|
325
|
+
``/app/contracts`` when unset) and ``APP_ROOT`` the repository its script
|
|
326
|
+
path is resolved against (``CONTRACT_DIR``'s parent when unset).
|
|
327
|
+
|
|
321
328
|
``reader`` is threaded into the python-csv producer instead of letting
|
|
322
329
|
it pick a reader via ``reader_for``; the script producer ignores it.
|
|
323
330
|
|
|
324
|
-
Returns 0 on success, 1 on any :class:`HarnessError
|
|
331
|
+
Returns 0 on success, 1 on any :class:`HarnessError`, which includes a
|
|
332
|
+
contracts folder that holds a YAML file that is not a ``*.odcs.yaml`` contract.
|
|
325
333
|
"""
|
|
326
334
|
node_id = env.get("NODE_ID") or ""
|
|
327
335
|
active_adapter: Any = None
|
|
@@ -330,13 +338,15 @@ def run_node(
|
|
|
330
338
|
table_name = _require_env(env, "TABLE_NAME")
|
|
331
339
|
target_schema = _require_env(env, "TARGET_SCHEMA")
|
|
332
340
|
|
|
341
|
+
# CONTRACT_DIR holds the node contracts, one `*.odcs.yaml` file per node.
|
|
333
342
|
contract_dir = Path(env.get("CONTRACT_DIR") or "/app/contracts")
|
|
334
343
|
app_root = Path(env["APP_ROOT"]) if env.get("APP_ROOT") else contract_dir.parent
|
|
335
344
|
|
|
336
345
|
logger.info("running node %s -> %s.%s", node_id, target_schema, table_name)
|
|
337
346
|
|
|
338
347
|
# check_reads=False: the harness has no --dialect of its own, so
|
|
339
|
-
# re-running the read
|
|
348
|
+
# re-running the read checks here (each read is one read query, and
|
|
349
|
+
# each table it names has its schema) would judge the reads against
|
|
340
350
|
# sqlglot's dialect-neutral grammar -- a different, in places stricter
|
|
341
351
|
# grammar than the one CI used -- and could only disagree with the
|
|
342
352
|
# gates already passed (CI's `continuo-runtime validate`, then
|
|
@@ -345,6 +355,7 @@ def run_node(
|
|
|
345
355
|
# Every other loader validation still runs at container start.
|
|
346
356
|
nodes = load_contract_dir(contract_dir, check_reads=False)
|
|
347
357
|
node = select_node(nodes, node_id)
|
|
358
|
+
check_image_contract(node, app_root, env)
|
|
348
359
|
|
|
349
360
|
if adapter is not None:
|
|
350
361
|
active_adapter = adapter
|
|
@@ -402,7 +413,11 @@ def run_node(
|
|
|
402
413
|
)
|
|
403
414
|
print(
|
|
404
415
|
result_block(
|
|
405
|
-
"error",
|
|
416
|
+
"error",
|
|
417
|
+
message=err.sentinel_message(),
|
|
418
|
+
failures=1,
|
|
419
|
+
unique_id=node_id,
|
|
420
|
+
reason=err.reason,
|
|
406
421
|
)
|
|
407
422
|
)
|
|
408
423
|
return 1
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""The bytes each node kind hashes, gathered from the repository.
|
|
2
|
+
|
|
3
|
+
A script kind hashes its script, its in-repo import closure and the assets it
|
|
4
|
+
declares (a file that is both is one unit). A csv node has
|
|
5
|
+
no script and no closure: its source is its uri, so new file content at the same
|
|
6
|
+
uri is new data, not a new node version.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from continuo_python_runtime.closure import resolve_closure
|
|
14
|
+
from continuo_python_runtime.contract.model import Node
|
|
15
|
+
from continuo_python_runtime.contract.paths import resolve_asset_path, resolve_script_path
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class HashInputs:
|
|
20
|
+
"""What a node's hash parts are computed from.
|
|
21
|
+
|
|
22
|
+
``primary`` is the script's bytes (a csv node's uri, encoded). ``units`` maps
|
|
23
|
+
each closure file's and each declared asset's repo-relative POSIX path to
|
|
24
|
+
its bytes. ``code_files`` holds every file that executes for the node, the
|
|
25
|
+
script first, for the lint.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
primary: bytes
|
|
29
|
+
units: dict[str, bytes]
|
|
30
|
+
code_files: tuple[tuple[Path, bytes], ...]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _script_inputs(node: Node, repo_root: Path) -> HashInputs:
|
|
34
|
+
script_path = resolve_script_path(node.script, repo_root, context=node.relation)
|
|
35
|
+
script_bytes = script_path.read_bytes()
|
|
36
|
+
root = repo_root.resolve()
|
|
37
|
+
members = [(member, member.read_bytes()) for member in resolve_closure(script_path, repo_root)]
|
|
38
|
+
units = {member.relative_to(root).as_posix(): data for member, data in members}
|
|
39
|
+
# Assets are data the script reads, not code that runs, so they are hashed
|
|
40
|
+
# but not part of code_files (which the lint reads).
|
|
41
|
+
for asset in node.assets:
|
|
42
|
+
units[asset] = resolve_asset_path(asset, repo_root, context=node.relation).read_bytes()
|
|
43
|
+
return HashInputs(
|
|
44
|
+
primary=script_bytes,
|
|
45
|
+
units=units,
|
|
46
|
+
code_files=((script_path, script_bytes), *members),
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _csv_inputs(node: Node, repo_root: Path) -> HashInputs:
|
|
51
|
+
return HashInputs(node.reads["csv"].encode(), {}, ())
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
HASH_INPUTS: dict[str, Callable[[Node, Path], HashInputs]] = {
|
|
55
|
+
"python-node": _script_inputs,
|
|
56
|
+
"python-csv": _csv_inputs,
|
|
57
|
+
"python-api": _script_inputs,
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def gather_hash_inputs(node: Node, repo_root: Path) -> HashInputs:
|
|
62
|
+
"""Read the files *node* hashes, by its kind."""
|
|
63
|
+
return HASH_INPUTS[node.kind](node, repo_root)
|