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,25 +1,36 @@
1
- """CLI for continuo-runtime: validate, merge, hash, lint, and run contract workflows."""
1
+ """CLI for continuo-runtime: validate, pack, hash, packages, lint, run and validation-op."""
2
2
 
3
3
  import argparse
4
+ import json
4
5
  import logging
5
6
  import os
6
7
  import sys
8
+ from importlib import metadata
7
9
  from pathlib import Path
8
10
 
9
11
  from continuo_python_runtime.contract.loader import load_contract_dir
10
- from continuo_python_runtime.contract.merge import (
11
- build_wire_contract,
12
- write_wire_contract,
12
+ from continuo_python_runtime.contract.pack import (
13
+ PACKAGE_SOURCE_USAGE,
14
+ build_bundle,
15
+ image_packages_from,
16
+ write_bundle,
13
17
  )
14
18
  from continuo_python_runtime.errors import HarnessError
19
+ from continuo_python_runtime.hash_inputs import gather_hash_inputs
20
+ from continuo_python_runtime.hashing import hash_parts
15
21
  from continuo_python_runtime.lint import lint_paths
22
+ from continuo_python_runtime.packages import installed_packages
16
23
  from continuo_python_runtime import harness
17
24
 
18
25
  logger = logging.getLogger(__name__)
19
26
 
20
27
 
21
28
  def main(argv: list[str] | None = None) -> int:
22
- """Main CLI entry point with validate, merge, and hash subcommands."""
29
+ """Run the subcommand ``argv`` names and return its exit code.
30
+
31
+ A usage error exits 2 through argparse. A :class:`HarnessError` or an
32
+ ``OSError`` raised by a subcommand is logged and returns 1.
33
+ """
23
34
  # Configure logging once
24
35
  logging.basicConfig(
25
36
  stream=sys.stderr,
@@ -28,6 +39,11 @@ def main(argv: list[str] | None = None) -> int:
28
39
  )
29
40
 
30
41
  parser = argparse.ArgumentParser(prog="continuo-runtime")
42
+ parser.add_argument(
43
+ "--version",
44
+ action="version",
45
+ version=f"continuo-runtime {metadata.version('continuo-python-runtime')}",
46
+ )
31
47
  subparsers = parser.add_subparsers(dest="command", required=True)
32
48
 
33
49
  dialect_help = (
@@ -42,15 +58,31 @@ def main(argv: list[str] | None = None) -> int:
42
58
  validate_parser.add_argument("contract_dir", help="Path to contract directory")
43
59
  validate_parser.add_argument("--dialect", default=None, help=dialect_help)
44
60
 
45
- # merge subcommand
46
- merge_parser = subparsers.add_parser(
47
- "merge", help="Merge contracts into wire contract"
61
+ # pack subcommand
62
+ pack_parser = subparsers.add_parser(
63
+ "pack",
64
+ help="Pack the contracts into the bundle (odcs-bundle.json) a release carries",
65
+ description=(
66
+ "Check every contract of the folder, lint every script it runs and write "
67
+ "the bundle. " + PACKAGE_SOURCE_USAGE + "."
68
+ ),
69
+ )
70
+ pack_parser.add_argument("contract_dir", help="Path to contract directory")
71
+ pack_parser.add_argument("--service", required=True, help="Service name")
72
+ pack_parser.add_argument("--repo-root", required=True, help="Repository root path")
73
+ pack_parser.add_argument(
74
+ "--image",
75
+ default=None,
76
+ help="Image the service runs; its package list is read with "
77
+ "`docker run --entrypoint continuo-runtime <image> packages`",
78
+ )
79
+ pack_parser.add_argument(
80
+ "--image-packages",
81
+ default=None,
82
+ help="File holding the package list of that image, one JSON object of name to version",
48
83
  )
49
- merge_parser.add_argument("contract_dir", help="Path to contract directory")
50
- merge_parser.add_argument("--service", required=True, help="Service name")
51
- merge_parser.add_argument("--repo-root", required=True, help="Repository root path")
52
- merge_parser.add_argument("--out", required=True, help="Output file path")
53
- merge_parser.add_argument("--dialect", default=None, help=dialect_help)
84
+ pack_parser.add_argument("--out", required=True, help="Output file path")
85
+ pack_parser.add_argument("--dialect", default=None, help=dialect_help)
54
86
 
55
87
  # hash subcommand
56
88
  hash_parser = subparsers.add_parser(
@@ -62,6 +94,13 @@ def main(argv: list[str] | None = None) -> int:
62
94
  )
63
95
  hash_parser.add_argument("--dialect", default=None, help=dialect_help)
64
96
 
97
+ # packages subcommand
98
+ subparsers.add_parser(
99
+ "packages",
100
+ help="Print the installed packages of this environment as one JSON object "
101
+ "({normalised name: version})",
102
+ )
103
+
65
104
  # lint subcommand
66
105
  lint_parser = subparsers.add_parser(
67
106
  "lint", help="Lint Python scripts for forbidden imports and SQL literals"
@@ -70,7 +109,7 @@ def main(argv: list[str] | None = None) -> int:
70
109
 
71
110
  # run subcommand
72
111
  subparsers.add_parser(
73
- "run", help="Execute a node script (container entrypoint)"
112
+ "run", help="Run the node the environment names (container entrypoint)"
74
113
  )
75
114
 
76
115
  # validation-op subcommand
@@ -81,16 +120,26 @@ def main(argv: list[str] | None = None) -> int:
81
120
  )
82
121
 
83
122
  args = parser.parse_args(argv)
123
+ if args.command == "pack" and (args.image is None) == (args.image_packages is None):
124
+ pack_parser.error(PACKAGE_SOURCE_USAGE)
84
125
 
85
126
  try:
86
127
  if args.command == "validate":
87
128
  return cmd_validate(args.contract_dir, args.dialect)
88
- elif args.command == "merge":
89
- return cmd_merge(
90
- args.contract_dir, args.service, args.repo_root, args.out, args.dialect
129
+ elif args.command == "pack":
130
+ return cmd_pack(
131
+ args.contract_dir,
132
+ args.service,
133
+ args.repo_root,
134
+ args.out,
135
+ image=args.image,
136
+ image_packages=args.image_packages,
137
+ dialect=args.dialect,
91
138
  )
92
139
  elif args.command == "hash":
93
140
  return cmd_hash(args.contract_dir, args.repo_root, args.dialect)
141
+ elif args.command == "packages":
142
+ return cmd_packages()
94
143
  elif args.command == "lint":
95
144
  return cmd_lint(args.path)
96
145
  elif args.command == "run":
@@ -115,36 +164,56 @@ def cmd_validate(contract_dir: str, dialect: str | None = None) -> int:
115
164
  return 0
116
165
 
117
166
 
118
- def cmd_merge(
167
+ def cmd_pack(
119
168
  contract_dir: str,
120
169
  service: str,
121
170
  repo_root: str,
122
171
  out: str,
172
+ *,
173
+ image: str | None,
174
+ image_packages: str | None,
123
175
  dialect: str | None = None,
124
176
  ) -> int:
125
- """Merge contracts into a wire contract file."""
126
- doc = build_wire_contract(Path(contract_dir), Path(repo_root), service, dialect=dialect)
127
- write_wire_contract(doc, Path(out))
177
+ """Pack the contracts into the bundle file ``out``.
178
+
179
+ The bundle records the package list of ``image``, or the one ``image_packages``
180
+ holds, never the packages of the environment this command runs in. Nothing is
181
+ written to ``out`` unless every check passed.
182
+ """
183
+ packages = image_packages_from(
184
+ image=image, image_packages=None if image_packages is None else Path(image_packages)
185
+ )
186
+ doc = build_bundle(Path(contract_dir), Path(repo_root), service, packages, dialect=dialect)
187
+ write_bundle(doc, Path(out))
128
188
  return 0
129
189
 
130
190
 
131
191
  def cmd_hash(contract_dir: str, repo_root: str, dialect: str | None = None) -> int:
132
- """Print relation and content hash for each node.
192
+ """Print ``<relation>\\t<content_hash>`` for each node, one line each, sorted by relation.
133
193
 
134
- Reuses build_wire_contract for consistent hashing and error handling.
135
- Service value is irrelevant to per-node hashes since entries don't include it.
194
+ Each node is the one a contract in ``contract_dir`` declares, hashed from the
195
+ files of ``repo_root`` it names. Every node is hashed before the first line
196
+ is printed, so a node that cannot be hashed leaves stdout empty.
136
197
  """
137
- # Reuse build_wire_contract for consistent hashing and error handling
138
- doc = build_wire_contract(
139
- Path(contract_dir), Path(repo_root), service="_hash", dialect=dialect
140
- )
198
+ root = Path(repo_root)
199
+ hashes = {}
200
+ for node in load_contract_dir(Path(contract_dir), dialect=dialect):
201
+ inputs = gather_hash_inputs(node, root)
202
+ hashes[node.relation] = hash_parts(node, inputs.primary, inputs.units)["content_hash"]
203
+
204
+ for relation, content_hash in sorted(hashes.items()):
205
+ print(f"{relation}\t{content_hash}")
206
+
207
+ return 0
141
208
 
142
- # Print relation\thash from wire contract nodes (already sorted by relation)
143
- for node_entry in doc["nodes"]:
144
- relation = f"{node_entry['schema']}.{node_entry['table']}"
145
- hash_value = node_entry["content_hash"]
146
- print(f"{relation}\t{hash_value}")
147
209
 
210
+ def cmd_packages() -> int:
211
+ """Print every installed package as one JSON object, ``{normalised name: version}``, and a newline.
212
+
213
+ The object is the only thing on stdout: a caller that runs this command in an image
214
+ parses it as the image's package list.
215
+ """
216
+ print(json.dumps(installed_packages(), sort_keys=True))
148
217
  return 0
149
218
 
150
219
 
@@ -162,10 +231,12 @@ def cmd_lint(paths: list[str]) -> int:
162
231
 
163
232
 
164
233
  def cmd_run() -> int:
165
- """Execute a node script reading configuration from os.environ.
234
+ """Run the node ``os.environ`` names and return its exit code.
166
235
 
167
- This is the container entrypoint: reads NODE_ID, TABLE_NAME, TARGET_SCHEMA,
168
- CONTRACT_DIR, and APP_ROOT from environment, then calls harness.run_node()
169
- which produces exactly one sentinel result block.
236
+ This is the container entrypoint. ``harness.run_node`` reads ``NODE_ID``,
237
+ ``TABLE_NAME`` and ``TARGET_SCHEMA``, and, when set, ``CONTRACT_DIR`` (the
238
+ folder of the image's ``*.odcs.yaml`` contracts) and ``APP_ROOT`` (the
239
+ repository root a script path is resolved against), runs the node and
240
+ prints exactly one sentinel result block.
170
241
  """
171
242
  return harness.run_node(os.environ)
@@ -0,0 +1,73 @@
1
+ """The harness's start check: the image must hold what the release hashed.
2
+
3
+ continuo sets ``CONTENT_HASH`` to the ``content_hash`` the release promoted for
4
+ the node. The check recomputes the node's hash from the files in the image with
5
+ the helpers ``continuo-runtime hash`` uses (``gather_hash_inputs`` and
6
+ ``hash_parts``), so the two can never disagree, and refuses to run a node whose
7
+ image reproduces a different one: the image holds other code, imports, assets or
8
+ contract than the release.
9
+ """
10
+
11
+ import logging
12
+ from collections.abc import Mapping
13
+ from importlib import metadata
14
+ from pathlib import Path
15
+
16
+ from continuo_python_runtime.contract.model import Node
17
+ from continuo_python_runtime.errors import ContractError, ImageContractMismatch
18
+ from continuo_python_runtime.hash_inputs import gather_hash_inputs
19
+ from continuo_python_runtime.hashing import hash_parts
20
+
21
+ logger = logging.getLogger("continuo_python_runtime.content_check")
22
+
23
+ _ENV_KEY = "CONTENT_HASH"
24
+
25
+
26
+ def check_image_contract(node: Node, app_root: Path, env: Mapping[str, str]) -> None:
27
+ """Fail unless the image reproduces the ``content_hash`` in ``CONTENT_HASH``.
28
+
29
+ An unset or empty ``CONTENT_HASH`` logs a warning and skips the check. Any
30
+ other value is compared as an exact string, so a value without the
31
+ ``sha256:`` prefix, in upper case or with surrounding whitespace is a
32
+ mismatch.
33
+
34
+ Raises:
35
+ ImageContractMismatch: The recomputed ``content_hash`` differs, or a
36
+ file the release hashed is missing from the image.
37
+ """
38
+ released = env.get(_ENV_KEY)
39
+ if not released:
40
+ logger.warning(
41
+ "%s is not set: skipping the check that the image holds the release's content for %s",
42
+ _ENV_KEY, node.relation,
43
+ )
44
+ return
45
+
46
+ try:
47
+ inputs = gather_hash_inputs(node, app_root)
48
+ parts = hash_parts(node, inputs.primary, inputs.units)
49
+ except ContractError as exc:
50
+ raise ImageContractMismatch(
51
+ _message(node, f"the image cannot reproduce {_ENV_KEY} {released}: {exc}")
52
+ ) from exc
53
+
54
+ if parts["content_hash"] != released:
55
+ detail = (
56
+ f"the image's content_hash {parts['content_hash']} "
57
+ f"(source_hash {parts['source_hash']}, "
58
+ f"shared_code_hash {parts['shared_code_hash']}, "
59
+ f"config_hash {parts['config_hash']}, "
60
+ f"units {sorted(inputs.units)})"
61
+ )
62
+ raise ImageContractMismatch(_message(node, f"{_ENV_KEY} {released} differs from {detail}"))
63
+
64
+ logger.info("image holds the release's content for %s (%s)", node.relation, released)
65
+
66
+
67
+ def _message(node: Node, detail: str) -> str:
68
+ return (
69
+ f"the image does not hold what the release hashed for {node.relation}: "
70
+ f"{detail}. "
71
+ f"This image runs runtime {metadata.version('continuo-python-runtime')}. "
72
+ "Fix: rebuild the image from the released commit, with CI on the runtime of the image's FROM tag."
73
+ )
@@ -1,9 +1,12 @@
1
- """Per-kind contract rules: which fields a node of each kind must carry.
2
-
3
- Each kind is one ``KindRules`` entry composed of a script policy, a reads rule,
4
- whether it may name a Secret, and which write modes it may declare. Adding a
5
- kind means adding one entry to ``RULES``; nothing that parses a contract
6
- branches on the kind's name.
1
+ """Per-kind reads rules: how the runtime checks the reads of a node of each kind.
2
+
3
+ continuo-contracts decides which fields a node of each kind must, may and may
4
+ not carry. The runtime keeps one rule per kind for itself, the check of its
5
+ reads: a python-node's reads each parse as one read query under the
6
+ repository's dialect and name the schema of every table they read, a
7
+ python-csv node's uri is one its readers fetch, and a python-api node reads
8
+ nothing. Adding a kind means adding one entry to ``RULES``; nothing that loads
9
+ a contract branches on the kind's name.
7
10
  """
8
11
 
9
12
  from __future__ import annotations
@@ -13,9 +16,10 @@ from dataclasses import dataclass
13
16
  from typing import Any
14
17
 
15
18
  from continuo_engine_contract.sql import ensure_single_read # type: ignore[import-untyped]
16
- from sqlglot.errors import TokenError
19
+ from sqlglot.errors import ParseError, TokenError
17
20
 
18
- from continuo_python_runtime.contract.model import DEFAULT_MODE_TYPE, KINDS, MODE_TYPES
21
+ from continuo_python_runtime.contract.model import KINDS
22
+ from continuo_python_runtime.contract.read_tables import unqualified_tables
19
23
  from continuo_python_runtime.csv_source import parse_csv_uri
20
24
  from continuo_python_runtime.errors import ContractError
21
25
 
@@ -30,7 +34,11 @@ class ReadsRule(ABC):
30
34
 
31
35
 
32
36
  class SqlReads(ReadsRule):
33
- """A non-empty mapping of read name -> single SELECT."""
37
+ """A non-empty mapping of read name -> single SELECT.
38
+
39
+ When the reads are checked, every table a query names must name its schema
40
+ (a reference to a CTE in scope excepted).
41
+ """
34
42
 
35
43
  def validate(
36
44
  self, reads: Any, label: str, *, dialect: str | None, check_reads: bool
@@ -69,6 +77,22 @@ class SqlReads(ReadsRule):
69
77
  raise ContractError(
70
78
  f"{label}: 'reads.{name}' must be a single read query ({exc})"
71
79
  ) from exc
80
+ try:
81
+ unqualified = unqualified_tables(sql, dialect=dialect)
82
+ except ParseError as exc:
83
+ # ensure_single_read keeps the statements sqlglot parsed and
84
+ # accepts a query that starts with an empty statement (`; select
85
+ # ...`); sqlglot's parse_one, which finds the tables here and in
86
+ # topology-controller, refuses it. The read is refused as the
87
+ # release would refuse it.
88
+ raise ContractError(
89
+ f"{label}: 'reads.{name}' must be a single read query ({exc})"
90
+ ) from exc
91
+ if unqualified:
92
+ raise ContractError(
93
+ f"{label}: read {name!r} names table {unqualified[0]!r} without its schema; "
94
+ f"write <schema>.{unqualified[0]}"
95
+ )
72
96
  return dict(reads)
73
97
 
74
98
 
@@ -104,23 +128,15 @@ class NoReads(ReadsRule):
104
128
 
105
129
  @dataclass(frozen=True)
106
130
  class KindRules:
107
- """What a node of one kind must declare."""
131
+ """The rules the runtime keeps for a node of one kind."""
108
132
 
109
- script_required: bool
110
133
  reads: ReadsRule
111
- secret_allowed: bool = False
112
- # The write modes a node of this kind may declare. A new kind gets replace
113
- # only unless its entry opts into more.
114
- mode_types: frozenset[str] = frozenset({DEFAULT_MODE_TYPE})
115
134
 
116
135
 
117
136
  RULES: dict[str, KindRules] = {
118
- "python-node": KindRules(script_required=True, reads=SqlReads(), mode_types=MODE_TYPES),
119
- # A csv drop is a snapshot of its source: replace only (spec D2).
120
- "python-csv": KindRules(script_required=False, reads=CsvRead()),
121
- "python-api": KindRules(
122
- script_required=True, reads=NoReads(), secret_allowed=True, mode_types=MODE_TYPES
123
- ),
137
+ "python-node": KindRules(reads=SqlReads()),
138
+ "python-csv": KindRules(reads=CsvRead()),
139
+ "python-api": KindRules(reads=NoReads()),
124
140
  }
125
141
 
126
142