continuo-python-runtime 0.12.0__py3-none-any.whl → 0.14.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,120 +1,71 @@
1
- """Contract v1 loader and validator.
2
-
3
- Parses YAML contract files into validated :class:`~continuo_python_runtime
4
- .contract.model.Node` instances, raising :class:`ContractError` for any
5
- structural or semantic violation.
1
+ """The contract loader: one ODCS contract per node.
2
+
3
+ A contracts folder holds one ODCS v3.2.0 contract per node, in a file named
4
+ ``<table>.odcs.yaml``, or ``<schema>.<table>.odcs.yaml`` when two nodes of one
5
+ service share a table name. continuo-contracts reads each file strictly, checks
6
+ it and maps it to its ``PythonNode``; the runtime then applies the rules it
7
+ keeps for itself and builds its :class:`~continuo_python_runtime.contract.model
8
+ .Node`. Every refusal is a :class:`ContractError` that names the file.
6
9
  """
7
10
 
8
11
  from __future__ import annotations
9
12
 
10
- import re
11
- from pathlib import Path, PurePosixPath
13
+ from collections.abc import Iterable, Mapping
14
+ from pathlib import Path
12
15
  from typing import Any
13
16
 
14
- import yaml
17
+ from continuo_contracts import yaml_strict
18
+ from continuo_contracts.errors import StrictYamlError
19
+ from continuo_contracts.python import PythonNode, node_from_odcs
20
+ from continuo_contracts.validate import validate_python_contract
21
+ from continuo_contracts.vocabulary import continuo_values
15
22
  from sqlglot import Dialect
16
23
 
17
- from continuo_python_runtime.contract.kinds import KindRules, rules_for
18
- from continuo_python_runtime.contract.model import (
19
- CRITICALITIES,
20
- DEFAULT_KIND,
21
- DEFAULT_MODE_TYPE,
22
- EXTRA_COLUMNS_POLICIES,
23
- MODE_TYPES,
24
- Column,
25
- Node,
26
- )
27
- from continuo_python_runtime.contract.secret_ref import validate_secret_ref
24
+ from continuo_python_runtime.contract.kinds import rules_for
25
+ from continuo_python_runtime.contract.model import Column, Node
28
26
  from continuo_python_runtime.errors import ContractError
29
- from continuo_python_runtime.types import parse_sql_type
30
-
31
- _ALLOWED_KEYS = {
32
- "schema",
33
- "table",
34
- "description",
35
- "owner",
36
- "schedule",
37
- "criticality",
38
- "kind",
39
- "script",
40
- "extra_columns",
41
- "reads",
42
- "output_columns",
43
- "config",
44
- "content_hash",
45
- "secret_ref",
46
- "mode_type",
47
- "primary_key",
48
- "timeout_minutes",
49
- "assets",
50
- }
51
-
52
- # Bounds of a node's declared task timeout, in minutes (one minute to one week).
53
- MIN_TIMEOUT_MINUTES = 1
54
- MAX_TIMEOUT_MINUTES = 10_080
55
-
56
- _REQUIRED_STRING_FIELDS = ("schema", "table", "owner", "schedule")
57
-
58
- _ALLOWED_OUTPUT_COLUMN_KEYS = {"name", "type", "nullable"}
59
-
60
27
 
61
- class _StrictLoader(yaml.SafeLoader):
62
- """SafeLoader that rejects duplicate mapping keys instead of keeping the last."""
63
-
64
-
65
- def _strict_construct_mapping(
66
- loader: _StrictLoader, node: yaml.MappingNode, deep: bool = False
67
- ):
68
- seen = set()
69
- for key_node, _ in node.value:
70
- key = loader.construct_object(key_node, deep=deep)
71
- if key in seen:
72
- raise ContractError(f"duplicate key {key!r} at {key_node.start_mark}")
73
- seen.add(key)
74
- return yaml.SafeLoader.construct_mapping(loader, node, deep=deep)
75
-
76
-
77
- _StrictLoader.add_constructor(
78
- yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _strict_construct_mapping
28
+ CONTRACT_SUFFIX = ".odcs.yaml"
29
+ # The endings of a YAML file's name, compared in lower case: any file that ends
30
+ # in one of them and not exactly in CONTRACT_SUFFIX is refused.
31
+ _YAML_SUFFIXES = (".yml", ".yaml")
32
+
33
+ # Where a refused file's author finds how to convert it: the refusal is read in
34
+ # the CI of the domain team that owns the repository, which does not hold this
35
+ # repository's docs.
36
+ _CONVERSION_GUIDE = (
37
+ "https://github.com/carolsimone/continuo-python-runtime/blob/main/"
38
+ "docs/boundary-contract.md#converting-a-contract-file"
79
39
  )
80
40
 
81
-
82
- def _node_label(raw: dict[str, Any], source: str) -> str:
83
- """Build a `source (schema.table)`-style label for error messages."""
84
- schema = raw.get("schema")
85
- table = raw.get("table")
86
- if isinstance(schema, str) and schema and isinstance(table, str) and table:
87
- return f"{source} ({schema}.{table})"
88
- return source
89
-
90
-
91
41
  _JSON_SCALARS = (str, int, float, bool, type(None))
92
42
 
43
+ # What a document that is not a mapping is, as the words of a message.
44
+ _DOCUMENT_KINDS = {
45
+ list: "a list",
46
+ str: "a string",
47
+ bool: "a boolean",
48
+ int: "a number",
49
+ float: "a number",
50
+ }
51
+
93
52
 
94
53
  def _validate_config(raw: Any, label: str) -> dict[str, Any]:
95
- """Validate the node's physical-layout `config` as a JSON-shaped mapping.
96
-
97
- The engine's adapter — not this loader — owns the vocabulary (§3.3), so the
98
- only rules here are the ones the hash and the wire format need: it is a
99
- mapping, every key at every level is a string, and every value is
100
- JSON-serializable. Non-string keys would make `json.dumps(..., sort_keys=True)`
101
- raise inside the hasher, and a non-serializable value would break the wire
102
- artifact — both must surface here, naming the node, not deep in CI.
103
-
104
- YAML aliases (``&anchor`` / ``*anchor``) can make PyYAML construct a
105
- genuinely cyclic object graph — a mapping whose own value (however deeply
106
- nested) is itself. Recursing into that without tracking what is already
107
- on the call stack raises an uncaught ``RecursionError`` instead of this
108
- function's promised ``ContractError``. ``active`` holds the ``id()`` of
109
- every dict/list container currently being descended into; a container is
110
- added just before recursing into its items and discarded right after, so
111
- re-entering one still on the stack is a genuine back-edge (a cycle), while
112
- the *same* container reached twice at sibling positions — a legal DAG,
113
- e.g. one list aliased under two different keys — is not: its first visit
114
- finishes (and is discarded) before the second begins.
54
+ """Validate the node's physical-layout ``config`` as a JSON-shaped mapping.
55
+
56
+ The engine's adapter, not this loader, owns the vocabulary, so the only
57
+ rules here are the ones the hash and the adapters need: it is a mapping,
58
+ every key at every level is a string, and every value is a JSON scalar, a
59
+ list or a mapping. A contract file always passes, since ``yaml_strict``
60
+ reads nothing else; a document built in code can hold a key that is not a
61
+ string, a value JSON cannot write or a container that contains itself, and
62
+ each is refused here, naming the node.
63
+
64
+ ``active`` holds the ``id()`` of every dict or list being descended into:
65
+ a container is added just before its items are checked and discarded right
66
+ after, so meeting one that is still in ``active`` is a cycle, while one
67
+ container reached twice at sibling positions is not.
115
68
  """
116
- if raw is None:
117
- return {}
118
69
  if not isinstance(raw, dict):
119
70
  raise ContractError(f"{label}: 'config' must be a mapping")
120
71
 
@@ -151,339 +102,191 @@ def _validate_config(raw: Any, label: str) -> dict[str, Any]:
151
102
  return raw
152
103
 
153
104
 
154
- def _validate_primary_key(
155
- raw: dict[str, Any], mode_type: str, columns: list[Column], label: str
156
- ) -> tuple[str, ...]:
157
- """Validate ``primary_key`` against ``mode_type`` and the declared columns.
158
-
159
- Required for ``upsert`` and rejected otherwise: a key on ``append`` or
160
- ``replace`` would look enforced when it is not. Names keep their order,
161
- which is what the wire entry carries. Each must be spelled exactly as an
162
- output column (postgres quotes identifiers, so ``Rate_Date`` is not
163
- ``rate_date``) declared ``nullable: false``, because a NULL key never
164
- matches an existing row. Repeats are refused case-insensitively too, so a
165
- key cannot name two columns that differ only in case. A floating-point
166
- column is refused as well: the warehouse treats ``0.0`` and ``-0.0`` as
167
- one key, so ``ensure_unique_key`` would reject the rows at write time --
168
- failing here instead keeps an unwritable upsert out of the contract.
105
+ def _upsert_key(python: PythonNode, label: str) -> tuple[str, ...]:
106
+ """Return the key the harness upserts on: the node's key when it upserts, else none.
107
+
108
+ On a replace or append node a key only describes the table. The names of
109
+ an upsert key are compared case-insensitively too, so a key cannot name
110
+ two columns that differ only in case.
169
111
  """
170
- if mode_type != "upsert":
171
- if "primary_key" in raw:
172
- raise ContractError(
173
- f"{label}: 'primary_key' is only allowed when mode_type is upsert "
174
- f"(got {mode_type})"
175
- )
112
+ if python.mode_type != "upsert":
176
113
  return ()
177
- if "primary_key" not in raw:
178
- raise ContractError(f"{label}: 'primary_key' is required when mode_type is upsert")
179
- raw_key = raw["primary_key"]
180
- if not isinstance(raw_key, list) or not raw_key:
181
- raise ContractError(
182
- f"{label}: 'primary_key' must be a non-empty list of output column names"
183
- )
184
- by_name = {column.name: column for column in columns}
185
114
  seen: set[str] = set()
186
- for name in raw_key:
187
- if not isinstance(name, str) or not name.strip():
188
- raise ContractError(
189
- f"{label}: 'primary_key' entry {name!r} must be a non-empty string"
190
- )
191
- folded = name.lower() # same folding as continuo's parser
115
+ for name in python.primary_key:
116
+ folded = name.lower()
192
117
  if folded in seen:
193
118
  raise ContractError(
194
- f"{label}: 'primary_key' names {name!r} more than once "
119
+ f"{label}: the upsert key names {name!r} more than once "
195
120
  "(names are compared case-insensitively)"
196
121
  )
197
122
  seen.add(folded)
198
- column = by_name.get(name)
199
- if column is None:
200
- raise ContractError(
201
- f"{label}: 'primary_key' column {name!r} is not in output_columns"
202
- )
203
- if column.nullable:
204
- raise ContractError(
205
- f"{label}: 'primary_key' column {name!r} must be declared nullable: false"
206
- )
207
- if parse_sql_type(column.type).base == "DOUBLE_PRECISION":
208
- raise ContractError(
209
- f"{label}: 'primary_key' column {name!r} is floating-point "
210
- f"({column.type}); a floating-point column cannot be a primary key"
211
- )
212
- return tuple(raw_key)
213
-
123
+ return tuple(python.primary_key)
214
124
 
215
- _DRIVE_PATH = re.compile(r"^[A-Za-z]:")
216
125
 
126
+ def issue_lines(file: Path | str, issues: Iterable[object]) -> list[str]:
127
+ """One line per issue of the contract in ``file``, ``f"{file}: {issue}"``."""
128
+ return [f"{file}: {issue}" for issue in issues]
217
129
 
218
- def _validate_assets(
219
- raw: dict[str, Any], rules: KindRules, kind: str, label: str
220
- ) -> tuple[str, ...]:
221
- """Validate ``assets``: repo-relative paths of the files a script reads.
222
130
 
223
- A kind without a script has nothing that reads a file, so it refuses the
224
- key. Each path is written with forward slashes, relative to the repository
225
- root and without a ``..`` segment; it is normalised (``./data//ref.json``
226
- is ``data/ref.json``) and keeps its declared position. A repeat after
227
- normalising is refused. Whether the file exists is checked where a
228
- repository root is known.
229
- """
230
- if "assets" not in raw:
231
- return ()
232
- if not rules.assets_allowed:
233
- raise ContractError(
234
- f"{label}: 'assets' is not allowed for kind {kind} (it has no script to read files)"
235
- )
236
- raw_assets = raw["assets"]
237
- if not isinstance(raw_assets, list):
238
- raise ContractError(f"{label}: 'assets' must be a list of repository-relative paths")
239
- assets: list[str] = []
240
- for entry in raw_assets:
241
- if not isinstance(entry, str) or not entry.strip():
242
- raise ContractError(f"{label}: 'assets' entry {entry!r} must be a non-empty string")
243
- if "\\" in entry:
244
- raise ContractError(f"{label}: 'assets' entry {entry!r} must use forward slashes")
245
- path = PurePosixPath(entry)
246
- if path.is_absolute() or _DRIVE_PATH.match(entry):
247
- raise ContractError(
248
- f"{label}: 'assets' entry {entry!r} must be relative to the repository root"
249
- )
250
- if ".." in path.parts:
251
- raise ContractError(f"{label}: 'assets' entry {entry!r} must not contain '..'")
252
- normalised = path.as_posix()
253
- if normalised == ".":
254
- raise ContractError(f"{label}: 'assets' entry {entry!r} must name a file")
255
- if normalised in assets:
256
- raise ContractError(f"{label}: 'assets' names {normalised!r} more than once")
257
- assets.append(normalised)
258
- return tuple(assets)
259
-
260
-
261
- def parse_node(
262
- raw: dict[str, Any],
263
- source: str,
131
+ def node_from_contract(
132
+ doc: Mapping[str, Any],
133
+ file: Path,
264
134
  *,
265
- dialect: str | None = None,
266
- check_reads: bool = True,
135
+ dialect: str | None,
136
+ check_reads: bool,
137
+ service: str | None = None,
267
138
  ) -> Node:
268
- """Validate a single raw mapping and build a :class:`Node`.
269
-
270
- ``source`` is the originating filename; it appears in every error message.
271
- ``dialect`` is a sqlglot dialect name (e.g. ``"postgres"``, ``"trino"``)
272
- each declared read is checked against via
273
- :func:`~continuo_engine_contract.sql.ensure_single_read`; ``None``
274
- (the default) uses sqlglot's dialect-neutral parser.
275
-
276
- ``check_reads=False`` skips *only* that :func:`ensure_single_read` call —
277
- the read-shape gate — leaving every other rule here (required fields,
278
- criticality, the ``reads`` map's own shape, output-column types and
279
- uniqueness, ``mode_type`` and ``primary_key``, ``config``,
280
- ``content_hash``) in force. It exists for
281
- :func:`~continuo_python_runtime.harness.run_node`; see
282
- :func:`load_contract_dir` for why the runtime opts out.
139
+ """Check the ODCS contract ``doc``, read from ``file``, and build its :class:`Node`.
140
+
141
+ continuo-contracts checks the contract first
142
+ (``validate_python_contract``, of which only the base name of ``file``
143
+ counts for the file-name rule). With a ``service`` it also refuses a
144
+ contract whose authored ``service`` property names another service; with
145
+ none, that property is not compared. When it finds issues they become one
146
+ :class:`ContractError` with one :func:`issue_lines` line per issue, and
147
+ nothing else runs.
148
+
149
+ The runtime's own rules follow, each naming ``file`` and the relation:
150
+ the kind's reads rule (:mod:`~continuo_python_runtime.contract.kinds`),
151
+ which, unless ``check_reads`` is false, parses each read of a python-node
152
+ as one read query under ``dialect`` and refuses a read that names a table
153
+ without its schema (a reference to a CTE in scope excepted); the shape of ``config``;
154
+ and the case-insensitive uniqueness of an upsert key's names.
155
+
156
+ The node takes ``owner`` from ``team.name``, ``description`` from
157
+ ``description.purpose`` (``""`` when absent), and ``schedule``,
158
+ ``criticality`` and ``timeout_minutes`` (``None`` when absent) from the
159
+ contract's ``continuo`` custom properties. Every other field is the
160
+ library's ``PythonNode``, kept as ``python``: the kind as the library
161
+ reads it, the script, the reads, the columns (nullable unless
162
+ ``required``), ``extra_columns``, ``config``, ``secret_ref``,
163
+ ``mode_type``, the key when the node upserts and the assets.
283
164
  """
284
- if not isinstance(raw, dict):
285
- raise ContractError(
286
- f"{source}: node must be a mapping, got {type(raw).__name__}"
287
- )
288
-
289
- label = _node_label(raw, source)
290
-
291
- unknown = set(raw) - _ALLOWED_KEYS
292
- if unknown:
293
- raise ContractError(f"{label}: unknown key(s) {sorted(unknown)}")
294
-
295
- kind = raw.get("kind", DEFAULT_KIND)
296
- rules = rules_for(kind, label)
297
-
298
- for field in _REQUIRED_STRING_FIELDS:
299
- value = raw.get(field)
300
- if not isinstance(value, str) or not value.strip():
301
- raise ContractError(
302
- f"{label}: required field '{field}' must be a non-empty string"
303
- )
304
-
305
- schema = raw["schema"]
306
- table = raw["table"]
307
- owner = raw["owner"]
308
- schedule = raw["schedule"]
309
-
310
- if rules.script_required:
311
- raw_script = raw.get("script")
312
- if not isinstance(raw_script, str) or not raw_script.strip():
313
- raise ContractError(
314
- f"{label}: required field 'script' must be a non-empty string"
315
- )
316
- script = raw_script
317
- else:
318
- if "script" in raw:
319
- raise ContractError(
320
- f"{label}: 'script' is forbidden for kind {kind} "
321
- "(it is a contract-only kind)"
322
- )
323
- script = ""
324
-
325
- criticality = raw.get("criticality")
326
- if not isinstance(criticality, str) or criticality not in CRITICALITIES:
327
- raise ContractError(
328
- f"{label}: 'criticality' must be one of {sorted(CRITICALITIES)}, got {criticality!r}"
329
- )
330
-
331
- extra_columns = raw.get("extra_columns", "raise")
332
- if (
333
- not isinstance(extra_columns, str)
334
- or extra_columns not in EXTRA_COLUMNS_POLICIES
335
- ):
336
- raise ContractError(
337
- f"{label}: 'extra_columns' must be one of {sorted(EXTRA_COLUMNS_POLICIES)}, "
338
- f"got {extra_columns!r}"
339
- )
340
-
341
- reads = rules.reads.validate(
342
- raw.get("reads"), label, dialect=dialect, check_reads=check_reads
165
+ issues = validate_python_contract(doc, path=str(file), service=service)
166
+ if issues:
167
+ raise ContractError("\n".join(issue_lines(file, issues)))
168
+ python = node_from_odcs(doc)
169
+ label = f"{file} ({python.relation})"
170
+
171
+ reads = rules_for(python.kind, label).reads.validate(
172
+ dict(python.reads), label, dialect=dialect, check_reads=check_reads
343
173
  )
174
+ config = _validate_config(python.config, label)
175
+ primary_key = _upsert_key(python, label)
344
176
 
345
- secret_ref = ""
346
- if "secret_ref" in raw:
347
- if not rules.secret_allowed:
348
- raise ContractError(f"{label}: 'secret_ref' is not allowed for kind {kind}")
349
- secret_ref = validate_secret_ref(raw["secret_ref"], label)
350
-
351
- timeout_minutes = raw.get("timeout_minutes")
352
- if "timeout_minutes" in raw and (
353
- type(timeout_minutes) is not int
354
- or not MIN_TIMEOUT_MINUTES <= timeout_minutes <= MAX_TIMEOUT_MINUTES
355
- ):
356
- raise ContractError(
357
- f"{label}: 'timeout_minutes' must be an integer between "
358
- f"{MIN_TIMEOUT_MINUTES} and {MAX_TIMEOUT_MINUTES}, got {timeout_minutes!r}"
359
- )
360
-
361
- mode_type = raw.get("mode_type", DEFAULT_MODE_TYPE)
362
- if not isinstance(mode_type, str) or mode_type not in MODE_TYPES:
363
- raise ContractError(
364
- f"{label}: 'mode_type' must be one of {sorted(MODE_TYPES)}, got {mode_type!r}"
365
- )
366
- if mode_type not in rules.mode_types:
367
- raise ContractError(
368
- f"{label}: 'mode_type' {mode_type!r} is not allowed for kind {kind!r} "
369
- f"(allowed: {sorted(rules.mode_types)})"
370
- )
371
-
372
- raw_columns = raw.get("output_columns")
373
- if not isinstance(raw_columns, list) or not raw_columns:
374
- raise ContractError(f"{label}: 'output_columns' must be a non-empty list")
375
-
376
- seen_names: set[str] = set()
377
- columns: list[Column] = []
378
- for entry in raw_columns:
379
- if not isinstance(entry, dict):
380
- raise ContractError(
381
- f"{label}: each 'output_columns' entry must be a mapping, got {entry!r}"
382
- )
383
- unknown_col_keys = set(entry) - _ALLOWED_OUTPUT_COLUMN_KEYS
384
- if unknown_col_keys:
385
- raise ContractError(
386
- f"{label}: output column has unknown key(s) {sorted(unknown_col_keys)}"
387
- )
388
- name = entry.get("name")
389
- if not isinstance(name, str) or not name.strip():
390
- raise ContractError(f"{label}: output column missing non-empty 'name'")
391
- col_type = entry.get("type")
392
- if not isinstance(col_type, str):
393
- raise ContractError(
394
- f"{label}: output column '{name}' has unsupported 'type' {col_type!r}"
395
- )
396
- try:
397
- parse_sql_type(col_type)
398
- except ContractError as e:
399
- raise ContractError(
400
- f"{label}: output column '{name}' has unsupported {str(e)}"
401
- ) from e
402
- nullable = entry.get("nullable", True)
403
- if not isinstance(nullable, bool):
404
- raise ContractError(
405
- f"{label}: output column '{name}' has non-boolean 'nullable' {nullable!r}"
406
- )
407
- if name in seen_names:
408
- raise ContractError(f"{label}: duplicate column '{name}' in output_columns")
409
- seen_names.add(name)
410
- columns.append(Column(name=name, type=col_type, nullable=nullable))
411
-
412
- primary_key = _validate_primary_key(raw, mode_type, columns, label)
413
- assets = _validate_assets(raw, rules, kind, label)
414
-
415
- description = raw.get("description", "")
416
- if not isinstance(description, str):
417
- raise ContractError(f"{label}: 'description' must be a string")
418
-
419
- config = _validate_config(raw.get("config"), label)
420
-
421
- content_hash = raw.get("content_hash")
422
- if content_hash is not None and not isinstance(content_hash, str):
423
- raise ContractError(f"{label}: 'content_hash' must be a string")
424
-
177
+ values = continuo_values(doc.get("customProperties"))
178
+ description = doc.get("description", {}).get("purpose", "")
425
179
  return Node(
426
- schema=schema,
427
- table=table,
428
- owner=owner,
429
- schedule=schedule,
430
- criticality=criticality,
431
- script=script,
180
+ schema=python.schema,
181
+ table=python.table,
182
+ owner=doc["team"]["name"],
183
+ schedule=values["schedule"],
184
+ criticality=values["criticality"],
185
+ script=python.script,
432
186
  reads=reads,
433
- output_columns=tuple(columns),
187
+ output_columns=tuple(
188
+ Column(name=column.name, type=column.type, nullable=column.nullable)
189
+ for column in python.output_columns
190
+ ),
191
+ python=python,
192
+ path=file,
434
193
  description=description,
435
- extra_columns=extra_columns,
194
+ extra_columns=python.extra_columns,
436
195
  config=config,
437
- content_hash=content_hash,
438
- kind=kind,
439
- secret_ref=secret_ref,
440
- mode_type=mode_type,
196
+ kind=python.kind,
197
+ secret_ref=python.secret_ref,
198
+ mode_type=python.mode_type,
441
199
  primary_key=primary_key,
442
- timeout_minutes=timeout_minutes,
443
- assets=assets,
200
+ timeout_minutes=values.get("timeoutMinutes"),
201
+ assets=tuple(python.assets),
444
202
  )
445
203
 
446
204
 
205
+ def read_contract_text(file: Path) -> str:
206
+ """Return the text of the contract ``file`` exactly as written, line endings included."""
207
+ try:
208
+ return file.read_bytes().decode("utf-8")
209
+ except UnicodeDecodeError as exc:
210
+ raise ContractError(f"{file}: the file is not UTF-8 text ({exc})") from None
211
+
212
+
213
+ def parse_contract(text: str, file: Path | str) -> Mapping[str, Any]:
214
+ """Return the document of the contract ``text``, read strictly by continuo-contracts.
215
+
216
+ ``file`` is only the name the refusals carry.
217
+ """
218
+ try:
219
+ doc = yaml_strict.load(text)
220
+ except StrictYamlError as exc:
221
+ raise ContractError(f"{file}: {exc}") from None
222
+ if not isinstance(doc, Mapping):
223
+ holds = "nothing" if doc is None else _DOCUMENT_KINDS.get(type(doc), type(doc).__name__)
224
+ raise ContractError(
225
+ f"{file}: a contract file holds one ODCS contract, a mapping; this one holds {holds}"
226
+ )
227
+ return doc
228
+
229
+
447
230
  def load_contract_dir(
448
231
  path: Path, *, dialect: str | None = None, check_reads: bool = True
449
232
  ) -> list[Node]:
450
- """Load and validate every `*.yml`/`*.yaml` contract file under ``path``.
233
+ """Load and check every ``*.odcs.yaml`` contract in ``path``, in file-name order.
234
+
235
+ The nodes, as :func:`load_contract_docs` loads them with no service. Every
236
+ refusal and every rule are described there.
237
+ """
238
+ return [node for node, _ in load_contract_docs(path, dialect=dialect, check_reads=check_reads)]
239
+
451
240
 
452
- ``check_reads=False`` skips the per-read
453
- :func:`~continuo_engine_contract.sql.ensure_single_read` gate and
454
- nothing else; every other rule in :func:`parse_node` and every rule here
455
- (dialect validity, document shape, duplicate relations, "no contract
456
- files found") still runs. The runtime
241
+ def load_contract_docs(
242
+ path: Path,
243
+ *,
244
+ dialect: str | None = None,
245
+ check_reads: bool = True,
246
+ service: str | None = None,
247
+ ) -> list[tuple[Node, Mapping[str, Any]]]:
248
+ """Load and check every ``*.odcs.yaml`` contract in ``path``, in file-name order.
249
+
250
+ Each node comes with the document it was built from, the one read from its
251
+ file and checked, so a caller that needs the documents does not read the
252
+ files again. ``service``, when given, is the service the contracts belong
253
+ to: continuo-contracts then refuses a contract whose authored ``service``
254
+ property names another one, as :func:`node_from_contract` says.
255
+
256
+ Any other file whose name ends in ``.yml`` or ``.yaml``, in any case
257
+ (``legacy.YML``, ``t.odcs.YAML``, ``t.odcs.yml``), is refused: one
258
+ :class:`ContractError` names every such file, one line each, with how to
259
+ convert it. An image pairs a runtime with its contracts, so a contract in
260
+ another format is a mistake, never a node to skip. Files with any other
261
+ extension are not read.
262
+
263
+ ``check_reads=False`` skips only the checks of the reads of a python-node:
264
+ that each parses as one read query and that each names its tables with
265
+ their schemas. Every other rule of :func:`node_from_contract` and every
266
+ rule here (the dialect name, the duplicate relations, the empty folder)
267
+ still runs. The harness
457
268
  (:func:`~continuo_python_runtime.harness.run_node`) passes it, because
458
- re-running the read-shape gate at container start can only introduce a
459
- disagreement, never catch a new problem:
460
-
461
- - CI already gated the reads (``continuo-runtime validate``), under the
462
- repo's own ``--dialect``, and Continuo gated them again with its own
463
- parser and bind-check before promoting the release.
464
- - The runtime has no ``--dialect`` of its own, so it would re-parse with
465
- the dialect-neutral grammar — a *different* and in places stricter
466
- grammar than CI used. Ordinary postgres (``a ~ 'x'``, ``data @>
467
- '{...}'``) parses under ``--dialect postgres`` and not under the
468
- neutral parser, so a team following the docs would get a green
469
- validate, a green merge, an accepted release, and a node that fails on
470
- every single run.
471
- - Nothing at run time consumes the parse: ``ctx.read`` resolves declared
472
- reads by name and hands the SQL to the adapter verbatim.
473
-
474
- ``dialect`` is validated once, up front, then forwarded to
475
- :func:`parse_node` for every node, so every declared read is checked
476
- against that sqlglot dialect (``None`` -- the default -- uses sqlglot's
477
- dialect-neutral parser). Validating it here rather than leaving it to
478
- the per-read ``ensure_single_read`` call matters: an unrecognized
479
- dialect name (e.g. a typo'd ``--dialect POSTGRES`` instead of
480
- ``postgres``) raises the same bare ``ValueError`` a genuinely
481
- unparseable read would, and would otherwise be misreported as a
482
- rejected read instead of a bad flag -- blaming an innocent, valid read.
483
-
484
- Raises `ContractError` if ``dialect`` is not a sqlglot dialect name, if
485
- no nodes are found, if any file's document is malformed, or if two nodes
486
- across files share the same `(schema, table)`.
269
+ checking the reads again at container start can only disagree with the
270
+ checks already passed, never catch a new problem:
271
+
272
+ - CI already checked the reads (``continuo-runtime validate``) under the
273
+ repository's ``--dialect``, and continuo checked them again with its own
274
+ parser before promoting the release.
275
+ - The harness has no ``--dialect`` of its own, so it would parse with
276
+ sqlglot's dialect-neutral grammar, which refuses ordinary postgres such
277
+ as ``a ~ 'x'`` that parses under ``--dialect postgres``.
278
+ - Nothing at run time reads the parse: ``ctx.read`` finds a read by name
279
+ and hands its SQL to the adapter as written.
280
+
281
+ ``dialect`` is checked once, before any file is read: sqlglot raises the
282
+ same ``ValueError`` for an unknown dialect name as for a read it cannot
283
+ parse, so a typo such as ``--dialect POSTGRES`` is reported as a bad flag
284
+ instead of blaming a valid read.
285
+
286
+ Raises ``ContractError`` for an unknown ``dialect``, a file in another
287
+ format, a folder with no contract, a contract that is refused (one that
288
+ names another service than ``service``, when given, included), and two
289
+ files that declare the same ``<schema>.<table>``, compared in lower case.
487
290
  """
488
291
  if dialect is not None:
489
292
  try:
@@ -491,43 +294,39 @@ def load_contract_dir(
491
294
  except ValueError as exc:
492
295
  raise ContractError(f"unknown --dialect {dialect!r}: {exc}") from exc
493
296
 
494
- files = sorted(path.glob("*.yml")) + sorted(path.glob("*.yaml"))
495
-
496
- nodes: list[Node] = []
497
- relation_sources: dict[str, str] = {}
297
+ entries = sorted(path.iterdir()) if path.is_dir() else []
298
+ yaml_files = [
299
+ entry for entry in entries if entry.name.lower().endswith(_YAML_SUFFIXES)
300
+ ]
301
+ files = [entry for entry in yaml_files if entry.name.endswith(CONTRACT_SUFFIX)]
302
+ others = [entry for entry in yaml_files if not entry.name.endswith(CONTRACT_SUFFIX)]
303
+ if others:
304
+ raise ContractError(
305
+ "\n".join(
306
+ f"{other}: runtime 0.13.0 reads only ODCS contracts named "
307
+ f"<table>.odcs.yaml; convert this file ({_CONVERSION_GUIDE})"
308
+ for other in others
309
+ )
310
+ )
311
+ if not files:
312
+ raise ContractError(f"no contract files found in {path}")
498
313
 
314
+ loaded: list[tuple[Node, Mapping[str, Any]]] = []
315
+ relation_files: dict[str, Path] = {}
499
316
  for file in files:
500
- text = file.read_text()
501
- try:
502
- document = yaml.load(text, Loader=_StrictLoader) # noqa: S506 — SafeLoader subclass
503
- except ContractError as exc:
504
- raise ContractError(f"{file.name}: {exc}") from None
505
- except yaml.YAMLError as exc:
506
- raise ContractError(f"{file.name}: invalid YAML: {exc}") from None
507
- if document is None:
508
- document = {}
509
- if not isinstance(document, dict):
317
+ doc = parse_contract(read_contract_text(file), file)
318
+ node = node_from_contract(
319
+ doc, file, dialect=dialect, check_reads=check_reads, service=service
320
+ )
321
+ # Relations are compared in lower case, as continuo compares them: a
322
+ # warehouse folds the case of an unquoted name, so two contracts whose
323
+ # tables differ only in case would build one table.
324
+ key = node.relation.lower()
325
+ existing = relation_files.get(key)
326
+ if existing is not None:
510
327
  raise ContractError(
511
- f"{file.name}: contract document must be a mapping, "
512
- f"got {type(document).__name__}"
328
+ f"duplicate node {node.relation} (in {existing} and {file})"
513
329
  )
514
- raw_nodes = document.get("nodes")
515
- if not isinstance(raw_nodes, list):
516
- raise ContractError(f"{file.name}: 'nodes' must be a list")
517
-
518
- for raw_node in raw_nodes:
519
- node = parse_node(
520
- raw_node, file.name, dialect=dialect, check_reads=check_reads
521
- )
522
- existing_source = relation_sources.get(node.relation)
523
- if existing_source is not None:
524
- raise ContractError(
525
- f"duplicate node {node.relation} (in {existing_source} and {file.name})"
526
- )
527
- relation_sources[node.relation] = file.name
528
- nodes.append(node)
529
-
530
- if not nodes:
531
- raise ContractError(f"no contract files found in {path}")
532
-
533
- return nodes
330
+ relation_files[key] = file
331
+ loaded.append((node, doc))
332
+ return loaded