continuo-python-runtime 0.12.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 +102 -37
- continuo_python_runtime/content_check.py +4 -4
- continuo_python_runtime/contract/kinds.py +37 -29
- continuo_python_runtime/contract/loader.py +207 -439
- continuo_python_runtime/contract/model.py +12 -6
- continuo_python_runtime/contract/pack.py +299 -0
- continuo_python_runtime/contract/paths.py +1 -1
- continuo_python_runtime/contract/read_tables.py +85 -0
- continuo_python_runtime/harness.py +14 -5
- continuo_python_runtime/hashing.py +23 -40
- continuo_python_runtime/packages.py +56 -0
- {continuo_python_runtime-0.12.0.dist-info → continuo_python_runtime-0.13.0.dist-info}/METADATA +191 -119
- {continuo_python_runtime-0.12.0.dist-info → continuo_python_runtime-0.13.0.dist-info}/RECORD +17 -16
- continuo_python_runtime/contract/merge.py +0 -178
- continuo_python_runtime/contract/secret_ref.py +0 -31
- {continuo_python_runtime-0.12.0.dist-info → continuo_python_runtime-0.13.0.dist-info}/WHEEL +0 -0
- {continuo_python_runtime-0.12.0.dist-info → continuo_python_runtime-0.13.0.dist-info}/entry_points.txt +0 -0
- {continuo_python_runtime-0.12.0.dist-info → continuo_python_runtime-0.13.0.dist-info}/licenses/LICENSE +0 -0
- {continuo_python_runtime-0.12.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,10 +42,11 @@ 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
|
|
@@ -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)
|
|
@@ -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()
|
|
@@ -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
|
|
@@ -63,7 +64,7 @@ def select_node(nodes: list[Node], node_id: str) -> Node:
|
|
|
63
64
|
"""Select the node matching the trailing ``schema.table`` of ``node_id``.
|
|
64
65
|
|
|
65
66
|
``node_id`` is split on ``.``; the trailing two segments are taken as
|
|
66
|
-
``(schema, table)`` and matched against the
|
|
67
|
+
``(schema, table)`` and matched against the nodes the contracts declare.
|
|
67
68
|
|
|
68
69
|
Raises:
|
|
69
70
|
ContractError: If ``node_id`` has fewer than 2 dot-separated
|
|
@@ -319,10 +320,16 @@ def run_node(
|
|
|
319
320
|
) -> int:
|
|
320
321
|
"""Run a single node end-to-end and print exactly one sentinel result block.
|
|
321
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
|
+
|
|
322
328
|
``reader`` is threaded into the python-csv producer instead of letting
|
|
323
329
|
it pick a reader via ``reader_for``; the script producer ignores it.
|
|
324
330
|
|
|
325
|
-
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.
|
|
326
333
|
"""
|
|
327
334
|
node_id = env.get("NODE_ID") or ""
|
|
328
335
|
active_adapter: Any = None
|
|
@@ -331,13 +338,15 @@ def run_node(
|
|
|
331
338
|
table_name = _require_env(env, "TABLE_NAME")
|
|
332
339
|
target_schema = _require_env(env, "TARGET_SCHEMA")
|
|
333
340
|
|
|
341
|
+
# CONTRACT_DIR holds the node contracts, one `*.odcs.yaml` file per node.
|
|
334
342
|
contract_dir = Path(env.get("CONTRACT_DIR") or "/app/contracts")
|
|
335
343
|
app_root = Path(env["APP_ROOT"]) if env.get("APP_ROOT") else contract_dir.parent
|
|
336
344
|
|
|
337
345
|
logger.info("running node %s -> %s.%s", node_id, target_schema, table_name)
|
|
338
346
|
|
|
339
347
|
# check_reads=False: the harness has no --dialect of its own, so
|
|
340
|
-
# 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
|
|
341
350
|
# sqlglot's dialect-neutral grammar -- a different, in places stricter
|
|
342
351
|
# grammar than the one CI used -- and could only disagree with the
|
|
343
352
|
# gates already passed (CI's `continuo-runtime validate`, then
|
|
@@ -1,22 +1,26 @@
|
|
|
1
1
|
"""Content hashing: three independent parts folded into one content_hash.
|
|
2
2
|
|
|
3
3
|
A Python node's ``content_hash`` folds three parts: ``source_hash`` (the node's
|
|
4
|
-
own script bytes), ``shared_code_hash`` (the import closure
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
the
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
4
|
+
own script bytes, or a csv node's uri), ``shared_code_hash`` (the import closure
|
|
5
|
+
and the declared assets, each file with its repo-relative path) and
|
|
6
|
+
``config_hash`` (the code projection of the node's contract). The parts are
|
|
7
|
+
computed from already-gathered bytes and a loaded node, so this module does no
|
|
8
|
+
filesystem access and knows nothing about ``closure.py``.
|
|
9
|
+
|
|
10
|
+
``config_hash`` is computed from ``Node.python``, the ``PythonNode`` that
|
|
11
|
+
continuo-contracts reads from the node's ODCS contract: the runtime keeps no
|
|
12
|
+
mapping of its own from a node to the library's view of it. ``shared_code_hash``,
|
|
13
|
+
``config_hash`` and the fold are computed by continuo-contracts, the library
|
|
14
|
+
continuo's topology-controller pins and recomputes the config part with. Nothing
|
|
15
|
+
here canonicalises or normalises: the library does, so every producer of a hash
|
|
16
|
+
writes the same bytes, and a node declared as a contract file and the same node
|
|
17
|
+
declared as a wire entry have one hash.
|
|
18
|
+
|
|
19
|
+
The library refuses a few ``config`` values (an integer beyond 2**53 - 1, NaN
|
|
20
|
+
or an infinity, nesting deeper than 99 levels, a lone surrogate). No contract
|
|
21
|
+
file holds one, since the loader reads each file with the library's strict
|
|
22
|
+
YAML reader, which refuses them too; a refusal for a node built in code
|
|
23
|
+
reaches the caller as a ``ContractError`` naming the node.
|
|
20
24
|
"""
|
|
21
25
|
|
|
22
26
|
from collections.abc import Mapping
|
|
@@ -24,7 +28,7 @@ from hashlib import sha256
|
|
|
24
28
|
|
|
25
29
|
from continuo_contracts.errors import ContractsError
|
|
26
30
|
from continuo_contracts.hashing import fold3, shared_hash
|
|
27
|
-
from continuo_contracts.python import
|
|
31
|
+
from continuo_contracts.python import projection_hash
|
|
28
32
|
|
|
29
33
|
from continuo_python_runtime.contract.model import Node
|
|
30
34
|
from continuo_python_runtime.errors import ContractError
|
|
@@ -35,31 +39,10 @@ def source_hash(primary: bytes) -> str:
|
|
|
35
39
|
return sha256(primary).hexdigest()
|
|
36
40
|
|
|
37
41
|
|
|
38
|
-
def to_python_node(node: Node) -> PythonNode:
|
|
39
|
-
"""The library's view of *node*: the fields its code projection is made of."""
|
|
40
|
-
return PythonNode(
|
|
41
|
-
schema=node.schema,
|
|
42
|
-
table=node.table,
|
|
43
|
-
kind=node.kind,
|
|
44
|
-
script=node.script,
|
|
45
|
-
reads=dict(node.reads),
|
|
46
|
-
output_columns=tuple(
|
|
47
|
-
PythonColumn(column.name, column.type, column.nullable)
|
|
48
|
-
for column in node.output_columns
|
|
49
|
-
),
|
|
50
|
-
extra_columns=node.extra_columns,
|
|
51
|
-
config=dict(node.config),
|
|
52
|
-
secret_ref=node.secret_ref,
|
|
53
|
-
mode_type=node.mode_type,
|
|
54
|
-
primary_key=tuple(node.primary_key),
|
|
55
|
-
assets=node.assets,
|
|
56
|
-
)
|
|
57
|
-
|
|
58
|
-
|
|
59
42
|
def config_hash(node: Node) -> str:
|
|
60
|
-
"""Bare hex SHA-256 of the RFC 8785 bytes of the
|
|
43
|
+
"""Bare hex SHA-256 of the RFC 8785 bytes of the code projection of ``node.python``."""
|
|
61
44
|
try:
|
|
62
|
-
return projection_hash(
|
|
45
|
+
return projection_hash(node.python)
|
|
63
46
|
except ContractsError as exc:
|
|
64
47
|
raise ContractError(str(exc)) from exc
|
|
65
48
|
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""The distributions installed in the running Python environment.
|
|
2
|
+
|
|
3
|
+
``continuo-runtime packages`` prints them, so that a producer bundle records exactly
|
|
4
|
+
what the image its service runs holds.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import logging
|
|
8
|
+
import re
|
|
9
|
+
from importlib import metadata
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
_NAME_SEPARATORS = re.compile(r"[-_.]+")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _normalise_name(name: str) -> str:
|
|
17
|
+
"""The PEP 503 normalised form of a distribution name: lower case, every run of ``-``, ``_`` and ``.`` one ``-``."""
|
|
18
|
+
return _NAME_SEPARATORS.sub("-", name).lower()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def installed_packages() -> dict[str, str]:
|
|
22
|
+
"""Every installed distribution, as ``{normalised name: version}``.
|
|
23
|
+
|
|
24
|
+
When two distributions normalise to the same name (one on each of two ``sys.path``
|
|
25
|
+
entries), the version ``importlib.metadata.version`` resolves wins: the one an
|
|
26
|
+
``import`` of the package would find. When the metadata cannot resolve the name
|
|
27
|
+
(a folder that does not carry its distribution's name), the first one found wins.
|
|
28
|
+
A distribution whose metadata has no name or no version is logged and left out,
|
|
29
|
+
since it names nothing a release can record.
|
|
30
|
+
"""
|
|
31
|
+
packages: dict[str, str] = {}
|
|
32
|
+
for dist in metadata.distributions():
|
|
33
|
+
name = dist.metadata.get("Name")
|
|
34
|
+
version = dist.metadata.get("Version")
|
|
35
|
+
if not name or not version:
|
|
36
|
+
logger.warning(
|
|
37
|
+
"skipping a distribution under %s: its metadata has name %r and version %r",
|
|
38
|
+
dist.locate_file(""),
|
|
39
|
+
name,
|
|
40
|
+
version,
|
|
41
|
+
)
|
|
42
|
+
continue
|
|
43
|
+
key = _normalise_name(name)
|
|
44
|
+
if key not in packages:
|
|
45
|
+
packages[key] = version
|
|
46
|
+
continue
|
|
47
|
+
try:
|
|
48
|
+
packages[key] = metadata.version(key)
|
|
49
|
+
except metadata.PackageNotFoundError:
|
|
50
|
+
logger.warning(
|
|
51
|
+
"%s appears twice and importlib.metadata cannot tell which one it resolves, "
|
|
52
|
+
"keeping the first one found (%s)",
|
|
53
|
+
key,
|
|
54
|
+
packages[key],
|
|
55
|
+
)
|
|
56
|
+
return packages
|