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.
@@ -1,6 +1,7 @@
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,19 +9,28 @@ from importlib import metadata
8
9
  from pathlib import Path
9
10
 
10
11
  from continuo_python_runtime.contract.loader import load_contract_dir
11
- from continuo_python_runtime.contract.merge import (
12
- build_wire_contract,
13
- 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,
14
17
  )
15
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
16
21
  from continuo_python_runtime.lint import lint_paths
22
+ from continuo_python_runtime.packages import installed_packages
17
23
  from continuo_python_runtime import harness
18
24
 
19
25
  logger = logging.getLogger(__name__)
20
26
 
21
27
 
22
28
  def main(argv: list[str] | None = None) -> int:
23
- """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
+ """
24
34
  # Configure logging once
25
35
  logging.basicConfig(
26
36
  stream=sys.stderr,
@@ -48,15 +58,31 @@ def main(argv: list[str] | None = None) -> int:
48
58
  validate_parser.add_argument("contract_dir", help="Path to contract directory")
49
59
  validate_parser.add_argument("--dialect", default=None, help=dialect_help)
50
60
 
51
- # merge subcommand
52
- merge_parser = subparsers.add_parser(
53
- "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",
54
83
  )
55
- merge_parser.add_argument("contract_dir", help="Path to contract directory")
56
- merge_parser.add_argument("--service", required=True, help="Service name")
57
- merge_parser.add_argument("--repo-root", required=True, help="Repository root path")
58
- merge_parser.add_argument("--out", required=True, help="Output file path")
59
- 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)
60
86
 
61
87
  # hash subcommand
62
88
  hash_parser = subparsers.add_parser(
@@ -68,6 +94,13 @@ def main(argv: list[str] | None = None) -> int:
68
94
  )
69
95
  hash_parser.add_argument("--dialect", default=None, help=dialect_help)
70
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
+
71
104
  # lint subcommand
72
105
  lint_parser = subparsers.add_parser(
73
106
  "lint", help="Lint Python scripts for forbidden imports and SQL literals"
@@ -76,7 +109,7 @@ def main(argv: list[str] | None = None) -> int:
76
109
 
77
110
  # run subcommand
78
111
  subparsers.add_parser(
79
- "run", help="Execute a node script (container entrypoint)"
112
+ "run", help="Run the node the environment names (container entrypoint)"
80
113
  )
81
114
 
82
115
  # validation-op subcommand
@@ -87,16 +120,26 @@ def main(argv: list[str] | None = None) -> int:
87
120
  )
88
121
 
89
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)
90
125
 
91
126
  try:
92
127
  if args.command == "validate":
93
128
  return cmd_validate(args.contract_dir, args.dialect)
94
- elif args.command == "merge":
95
- return cmd_merge(
96
- 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,
97
138
  )
98
139
  elif args.command == "hash":
99
140
  return cmd_hash(args.contract_dir, args.repo_root, args.dialect)
141
+ elif args.command == "packages":
142
+ return cmd_packages()
100
143
  elif args.command == "lint":
101
144
  return cmd_lint(args.path)
102
145
  elif args.command == "run":
@@ -121,36 +164,56 @@ def cmd_validate(contract_dir: str, dialect: str | None = None) -> int:
121
164
  return 0
122
165
 
123
166
 
124
- def cmd_merge(
167
+ def cmd_pack(
125
168
  contract_dir: str,
126
169
  service: str,
127
170
  repo_root: str,
128
171
  out: str,
172
+ *,
173
+ image: str | None,
174
+ image_packages: str | None,
129
175
  dialect: str | None = None,
130
176
  ) -> int:
131
- """Merge contracts into a wire contract file."""
132
- doc = build_wire_contract(Path(contract_dir), Path(repo_root), service, dialect=dialect)
133
- 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))
134
188
  return 0
135
189
 
136
190
 
137
191
  def cmd_hash(contract_dir: str, repo_root: str, dialect: str | None = None) -> int:
138
- """Print relation and content hash for each node.
192
+ """Print ``<relation>\\t<content_hash>`` for each node, one line each, sorted by relation.
139
193
 
140
- Reuses build_wire_contract for consistent hashing and error handling.
141
- 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.
142
197
  """
143
- # Reuse build_wire_contract for consistent hashing and error handling
144
- doc = build_wire_contract(
145
- Path(contract_dir), Path(repo_root), service="_hash", dialect=dialect
146
- )
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
147
208
 
148
- # Print relation\thash from wire contract nodes (already sorted by relation)
149
- for node_entry in doc["nodes"]:
150
- relation = f"{node_entry['schema']}.{node_entry['table']}"
151
- hash_value = node_entry["content_hash"]
152
- print(f"{relation}\t{hash_value}")
153
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))
154
217
  return 0
155
218
 
156
219
 
@@ -168,10 +231,12 @@ def cmd_lint(paths: list[str]) -> int:
168
231
 
169
232
 
170
233
  def cmd_run() -> int:
171
- """Execute a node script reading configuration from os.environ.
234
+ """Run the node ``os.environ`` names and return its exit code.
172
235
 
173
- This is the container entrypoint: reads NODE_ID, TABLE_NAME, TARGET_SCHEMA,
174
- CONTRACT_DIR, and APP_ROOT from environment, then calls harness.run_node()
175
- 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.
176
241
  """
177
242
  return harness.run_node(os.environ)
@@ -2,10 +2,10 @@
2
2
 
3
3
  continuo sets ``CONTENT_HASH`` to the ``content_hash`` the release promoted for
4
4
  the node. The check recomputes the node's hash from the files in the image with
5
- the helpers ``merge`` uses (``gather_hash_inputs`` and ``hash_parts``), so the
6
- two can never disagree, and refuses to run a node whose image reproduces a
7
- different one: the image holds other code, imports, assets or contract than the
8
- release.
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
9
  """
10
10
 
11
11
  import logging
@@ -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,31 +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
- # Whether a node of this kind may list the repository files its script reads.
116
- assets_allowed: bool = False
117
134
 
118
135
 
119
136
  RULES: dict[str, KindRules] = {
120
- "python-node": KindRules(
121
- script_required=True, reads=SqlReads(), mode_types=MODE_TYPES, assets_allowed=True
122
- ),
123
- # A csv drop is a snapshot of its source: replace only (spec D2).
124
- "python-csv": KindRules(script_required=False, reads=CsvRead()),
125
- "python-api": KindRules(
126
- script_required=True,
127
- reads=NoReads(),
128
- secret_allowed=True,
129
- mode_types=MODE_TYPES,
130
- assets_allowed=True,
131
- ),
137
+ "python-node": KindRules(reads=SqlReads()),
138
+ "python-csv": KindRules(reads=CsvRead()),
139
+ "python-api": KindRules(reads=NoReads()),
132
140
  }
133
141
 
134
142