continuo-python-runtime 0.13.0__py3-none-any.whl → 0.15.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.
@@ -0,0 +1,265 @@
1
+ """The ``dependents_check`` validation op.
2
+
3
+ ``dependents_check`` asks the warehouse which objects a reload of a seed's
4
+ production table would destroy or leave reading a missing table, and compares
5
+ them with the objects the operator has allowed or acknowledged. ``check`` stops
6
+ a reload that would hit an object outside that set; ``report`` prints the same
7
+ conclusion and never stops (exit 0). The block and the exit codes follow
8
+ :mod:`~continuo_python_runtime.validation.warehouse_read`.
9
+
10
+ The decision is the pure function :func:`decide`; the rest of the module reads
11
+ the inputs, drives the adapter and prints.
12
+ """
13
+ import logging
14
+ from collections.abc import Mapping
15
+ from dataclasses import dataclass
16
+ from enum import Enum
17
+ from typing import Any, cast
18
+
19
+ from continuo_engine_contract.port import ( # type: ignore[import-untyped]
20
+ DependentsIntrospection,
21
+ discover_adapter,
22
+ )
23
+
24
+ from continuo_python_runtime.validation.warehouse_read import (
25
+ Discover,
26
+ InputError,
27
+ close_quietly,
28
+ discover_and_check_env,
29
+ emit,
30
+ first_line,
31
+ json_list,
32
+ )
33
+
34
+ logger = logging.getLogger("validation_dependents_check")
35
+
36
+ # The adapter's ``drop_semantics`` mapped to the engine family the release plan declares.
37
+ _FAMILY_OF_DROP_SEMANTICS = {"cascade": "schema_bound", "late_binding": "late_binding"}
38
+ _MODES = ("check", "report")
39
+ _FAMILIES = ("schema_bound", "late_binding")
40
+
41
+
42
+ class Situation(Enum):
43
+ """How far ``dependents_check`` got, which is what decides its verdict."""
44
+
45
+ BAD_INPUT = "bad_input"
46
+ ENGINE_MISMATCH = "engine_mismatch"
47
+ NO_CAPABILITY = "no_capability"
48
+ UNREACHABLE = "unreachable"
49
+ LISTING_FAILED = "listing_failed"
50
+ LISTED = "listed"
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class Verdict:
55
+ """What ``dependents_check`` concludes: the block's status, reason, message and the exit code."""
56
+
57
+ status: str
58
+ reason: str
59
+ exit_code: int
60
+ checked: bool
61
+ completeness: str
62
+ message: str
63
+
64
+
65
+ def decide(
66
+ mode: str,
67
+ family: str,
68
+ situation: Situation,
69
+ *,
70
+ detail: str = "",
71
+ completeness: str = "none",
72
+ has_unowned: bool = False,
73
+ ) -> Verdict:
74
+ """The decision table of ``dependents_check``.
75
+
76
+ *family* is the engine family the release expects (``schema_bound`` or
77
+ ``late_binding``), *detail* the text that explains the situation, *completeness*
78
+ the adapter's own and *has_unowned* whether a listed object is outside the
79
+ allowed set. A situation that a ``check`` stops on gives ``error`` and exit 1;
80
+ ``report`` mode gives the same ``reason`` on a ``success`` block and exit 0. A
81
+ bad input is exit 2 in both modes. A ``reason`` prefixes the message.
82
+ """
83
+ if situation is Situation.BAD_INPUT:
84
+ return Verdict("error", "", 2, False, "none", detail)
85
+ reason, stops = _conclusion(family, situation, has_unowned)
86
+ failed = stops and mode == "check"
87
+ return Verdict(
88
+ status="error" if failed else "success",
89
+ reason=reason,
90
+ exit_code=1 if failed else 0,
91
+ checked=situation is Situation.LISTED,
92
+ completeness=completeness if situation is Situation.LISTED else "none",
93
+ message=f"{reason}: {detail}" if reason else detail,
94
+ )
95
+
96
+
97
+ def _conclusion(family: str, situation: Situation, has_unowned: bool) -> tuple[str, bool]:
98
+ """The ``reason`` a situation carries and whether a ``check`` stops on it."""
99
+ schema_bound = family == "schema_bound"
100
+ if situation is Situation.ENGINE_MISMATCH:
101
+ return "engine_mismatch", True
102
+ if situation is Situation.UNREACHABLE:
103
+ return "warehouse_unreachable", True
104
+ if situation is Situation.NO_CAPABILITY:
105
+ return ("unowned_dependents", True) if schema_bound else ("", False)
106
+ if situation is Situation.LISTING_FAILED:
107
+ return "", schema_bound
108
+ if schema_bound and has_unowned:
109
+ return "unowned_dependents", True
110
+ return "", False
111
+
112
+
113
+
114
+
115
+ @dataclass(frozen=True)
116
+ class _SeedInputs:
117
+ mode: str
118
+ family: str
119
+ schema: str
120
+ table: str
121
+ allowed: frozenset[str]
122
+
123
+
124
+ def _seed_node_id(env: Mapping[str, str]) -> str:
125
+ """``NODE_ID``, else ``<PROD_SCHEMA>.<TABLE_NAME>`` when both are set, else ``""``."""
126
+ schema, table = env.get("PROD_SCHEMA", ""), env.get("TABLE_NAME", "")
127
+ return env.get("NODE_ID") or (f"{schema}.{table}" if schema and table else "")
128
+
129
+
130
+ def _seed_inputs(env: Mapping[str, str]) -> _SeedInputs:
131
+ mode = env.get("DEPENDENTS_CHECK_MODE", "")
132
+ if mode not in _MODES:
133
+ raise InputError(f"DEPENDENTS_CHECK_MODE must be one of {', '.join(_MODES)}, got {mode!r}")
134
+ family = env.get("DEPENDENTS_CHECK_ENGINE_FAMILY", "")
135
+ if family not in _FAMILIES:
136
+ raise InputError(
137
+ f"DEPENDENTS_CHECK_ENGINE_FAMILY must be one of {', '.join(_FAMILIES)}, got {family!r}"
138
+ )
139
+ for name in ("PROD_SCHEMA", "TABLE_NAME"):
140
+ if not env.get(name):
141
+ raise InputError(f"missing required env var {name}")
142
+ allowed = json_list(env, "DEPENDENTS_CHECK_ALLOWED", required=False)
143
+ acknowledged = json_list(env, "DEPENDENTS_CHECK_ACKNOWLEDGED", required=False)
144
+ return _SeedInputs(
145
+ mode=mode,
146
+ family=family,
147
+ schema=env["PROD_SCHEMA"],
148
+ table=env["TABLE_NAME"],
149
+ allowed=frozenset(entry.strip().lower() for entry in [*allowed, *acknowledged]),
150
+ )
151
+
152
+
153
+ def _seed_fields(
154
+ env: Mapping[str, str], drop_semantics: str, verdict: Verdict, dependents: list[dict[str, Any]]
155
+ ) -> dict[str, Any]:
156
+ return {
157
+ "op": "dependents_check",
158
+ "mode": env.get("DEPENDENTS_CHECK_MODE", ""),
159
+ "checked": verdict.checked,
160
+ "engine_family": env.get("DEPENDENTS_CHECK_ENGINE_FAMILY", ""),
161
+ "drop_semantics": drop_semantics,
162
+ "completeness": verdict.completeness,
163
+ "dependents": dependents,
164
+ }
165
+
166
+
167
+ def _finish_seed(
168
+ env: Mapping[str, str], drop_semantics: str, verdict: Verdict,
169
+ dependents: list[dict[str, Any]] | None = None,
170
+ ) -> int:
171
+ node_id = _seed_node_id(env)
172
+ if verdict.exit_code == 2:
173
+ logger.error("dependents_check %s: %s", node_id, verdict.message)
174
+ elif verdict.reason or verdict.exit_code:
175
+ logger.warning("dependents_check %s: %s", node_id, verdict.message)
176
+ emit(
177
+ verdict.status, verdict.message, node_id, verdict.reason,
178
+ _seed_fields(env, drop_semantics, verdict, dependents or []),
179
+ )
180
+ return verdict.exit_code
181
+
182
+
183
+ def run_dependents_check(
184
+ env: Mapping[str, str], discover: Discover = discover_adapter
185
+ ) -> int:
186
+ """Run ``dependents_check`` against *env*; print its one block and return the exit code.
187
+
188
+ Reads the op's inputs and the adapter's ``required_env()`` from *env* (adapters
189
+ connect from ``os.environ``, so the runner passes that). An unexpected error
190
+ still prints one ``error`` block and returns 2.
191
+ """
192
+ try:
193
+ return _dependents_check(env, discover)
194
+ except Exception as exc:
195
+ logger.exception("dependents_check %s failed unexpectedly", _seed_node_id(env))
196
+ verdict = Verdict("error", "", 2, False, "none", f"unexpected error: {first_line(exc)}")
197
+ return _finish_seed(env, "", verdict)
198
+
199
+
200
+ def _dependents_check(env: Mapping[str, str], discover: Discover) -> int:
201
+ try:
202
+ inputs = _seed_inputs(env)
203
+ engine, adapter_cls = discover_and_check_env(env, discover)
204
+ except InputError as exc:
205
+ return _finish_seed(env, "", decide("", "", Situation.BAD_INPUT, detail=str(exc)))
206
+
207
+ declared = getattr(adapter_cls, "drop_semantics", "")
208
+ drop_semantics = declared if isinstance(declared, str) else ""
209
+ adapter_family = _FAMILY_OF_DROP_SEMANTICS.get(drop_semantics)
210
+
211
+ def finish(
212
+ situation: Situation, detail: str = "", *, completeness: str = "none",
213
+ has_unowned: bool = False, dependents: list[dict[str, Any]] | None = None,
214
+ ) -> int:
215
+ verdict = decide(
216
+ inputs.mode, inputs.family, situation,
217
+ detail=detail, completeness=completeness, has_unowned=has_unowned,
218
+ )
219
+ return _finish_seed(env, drop_semantics, verdict, dependents)
220
+
221
+ if adapter_family != inputs.family:
222
+ return finish(
223
+ Situation.ENGINE_MISMATCH,
224
+ f"engine {engine!r} is {adapter_family or 'of no known family'}, "
225
+ f"but the release expects {inputs.family}",
226
+ )
227
+ if not issubclass(adapter_cls, DependentsIntrospection):
228
+ return finish(Situation.NO_CAPABILITY, f"engine {engine!r} cannot list the objects that read a table")
229
+
230
+ try:
231
+ adapter = adapter_cls.from_env()
232
+ except Exception as exc:
233
+ return finish(Situation.UNREACHABLE, first_line(exc))
234
+ try:
235
+ try:
236
+ listing = cast(DependentsIntrospection, adapter).dependents(inputs.schema, inputs.table)
237
+ except Exception as exc:
238
+ return finish(
239
+ Situation.LISTING_FAILED,
240
+ f"listing the objects that read {inputs.schema}.{inputs.table} failed: {first_line(exc)}",
241
+ )
242
+ dependents = [
243
+ {
244
+ "schema": found.schema, "name": found.name, "kind": found.kind, "owner": found.owner,
245
+ "depth": found.depth,
246
+ "allowed": f"{found.schema}.{found.name}".lower() in inputs.allowed,
247
+ }
248
+ for found in sorted(listing.objects, key=lambda d: (d.depth, d.schema, d.name))
249
+ ]
250
+ finally:
251
+ close_quietly(adapter)
252
+ outside = [d for d in dependents if not d["allowed"]]
253
+ if inputs.family == "schema_bound":
254
+ detail = "the reload would drop objects continuo does not own: " + ", ".join(
255
+ f"{d['schema']}.{d['name']} ({d['kind']}, owner {d['owner']})" for d in outside
256
+ )
257
+ else:
258
+ detail = (
259
+ f"{len(outside)} external view(s) may go stale; recreate them after the reload: "
260
+ + ", ".join(f"{d['schema']}.{d['name']}" for d in outside)
261
+ )
262
+ return finish(
263
+ Situation.LISTED, detail if outside else "",
264
+ completeness=listing.completeness, has_unowned=bool(outside), dependents=dependents,
265
+ )
@@ -0,0 +1,99 @@
1
+ """The ``probe_views`` validation op.
2
+
3
+ ``probe_views`` tries each view of ``PROBE_VIEWS`` with a zero-row read and
4
+ reports which ones no longer bind, and never fails the op for a view that does
5
+ not. The block and the exit codes follow
6
+ :mod:`~continuo_python_runtime.validation.warehouse_read`: a failed probe or an
7
+ unreachable warehouse is exit 0, an input or adapter problem or an unexpected
8
+ error is exit 2.
9
+ """
10
+ import logging
11
+ from collections.abc import Mapping
12
+ from typing import Any
13
+
14
+ from continuo_engine_contract.port import discover_adapter # type: ignore[import-untyped]
15
+
16
+ from continuo_python_runtime.validation.warehouse_read import (
17
+ Discover,
18
+ InputError,
19
+ close_quietly,
20
+ discover_and_check_env,
21
+ emit,
22
+ first_line,
23
+ json_list,
24
+ )
25
+
26
+ logger = logging.getLogger("validation_probe_views")
27
+
28
+
29
+ def _probe_views_input(env: Mapping[str, str]) -> list[tuple[str, str]]:
30
+ """``PROBE_VIEWS`` as ``(schema, name)`` pairs, split on the first dot, each once, in order."""
31
+ pairs: list[tuple[str, str]] = []
32
+ for entry in json_list(env, "PROBE_VIEWS", required=True):
33
+ schema, dot, name = entry.partition(".")
34
+ if not dot or not schema or not name:
35
+ raise InputError(f"PROBE_VIEWS entry {entry!r} is not <schema>.<name>")
36
+ if (schema, name) not in pairs:
37
+ pairs.append((schema, name))
38
+ return pairs
39
+
40
+
41
+ def _quote(identifier: str) -> str:
42
+ return '"' + identifier.replace('"', '""') + '"'
43
+
44
+
45
+ def _finish_probe(
46
+ env: Mapping[str, str], status: str, message: str, reason: str, checked: bool,
47
+ views: list[dict[str, Any]],
48
+ ) -> int:
49
+ node_id = env.get("NODE_ID") or "probe_views"
50
+ if status == "error":
51
+ logger.error("probe_views %s: %s", node_id, message)
52
+ elif reason:
53
+ logger.warning("probe_views %s: %s", node_id, message)
54
+ emit(status, message, node_id, reason, {"op": "probe_views", "checked": checked, "views": views})
55
+ return 2 if status == "error" else 0
56
+
57
+
58
+ def run_probe_views(env: Mapping[str, str], discover: Discover = discover_adapter) -> int:
59
+ """Run ``probe_views`` against *env*; print its one block and return the exit code.
60
+
61
+ Reads ``PROBE_VIEWS`` and the adapter's ``required_env()`` from *env*. A view
62
+ that fails its probe, or a warehouse that cannot be reached, still ends with
63
+ exit 0; only an input or adapter problem or an unexpected error is exit 2.
64
+ """
65
+ try:
66
+ return _probe_views(env, discover)
67
+ except Exception as exc:
68
+ logger.exception("probe_views failed unexpectedly")
69
+ return _finish_probe(env, "error", f"unexpected error: {first_line(exc)}", "", False, [])
70
+
71
+
72
+ def _probe_views(env: Mapping[str, str], discover: Discover) -> int:
73
+ try:
74
+ pairs = _probe_views_input(env)
75
+ _, adapter_cls = discover_and_check_env(env, discover)
76
+ except InputError as exc:
77
+ return _finish_probe(env, "error", str(exc), "", False, [])
78
+ try:
79
+ adapter = adapter_cls.from_env()
80
+ except Exception as exc:
81
+ return _finish_probe(
82
+ env, "success", f"warehouse_unreachable: {first_line(exc)}", "warehouse_unreachable", False, []
83
+ )
84
+ views: list[dict[str, Any]] = []
85
+ try:
86
+ for schema, name in pairs:
87
+ error = ""
88
+ try:
89
+ adapter.fetch(f"SELECT * FROM {_quote(schema)}.{_quote(name)} LIMIT 0")
90
+ except Exception as exc:
91
+ error = first_line(exc)
92
+ views.append({"schema": schema, "name": name, "ok": not error, "error": error})
93
+ finally:
94
+ close_quietly(adapter)
95
+ broken = [f"{v['schema']}.{v['name']}" for v in views if not v["ok"]]
96
+ for name in broken:
97
+ logger.warning("probe_views: %s does not bind", name)
98
+ message = f"{len(broken)} of {len(views)} views failed: {', '.join(broken)}" if broken else ""
99
+ return _finish_probe(env, "success", message, "", True, views)
@@ -3,7 +3,7 @@
3
3
  Dispatches on ``VALIDATION_OP`` env var (default ``build_from_sql``):
4
4
  - ``build_from_sql``: fetch the node's compiled SQL from S3 (``CANDIDATE_SQL_URI``) and
5
5
  materialize it empty (models/snapshots).
6
- - ``clone_from_prod``: clone an existing prod table's shape empty from ``PROD_SCHEMA``
6
+ - ``build_from_prod``: build the table empty, shaped like the prod table in ``PROD_SCHEMA``
7
7
  (unchanged upstreams, including seeds).
8
8
  - ``build_from_columns``: for python nodes, which have no SELECT to shape their output
9
9
  from. Fetch the node's validation spec JSON from S3 (``CANDIDATE_SPEC_URI`` —
@@ -23,12 +23,12 @@ Dispatches on ``VALIDATION_OP`` env var (default ``build_from_sql``):
23
23
  via the engine adapter and creates nothing — a test whose compiled SQL names
24
24
  a column a candidate change dropped or renamed fails the release at its
25
25
  source, before any table is built.
26
- - ``seed_preflight``: before a seed's production table is reloaded, list the objects
26
+ - ``dependents_check``: before a seed's production table is reloaded, list the objects
27
27
  (``PROD_SCHEMA``.``TABLE_NAME``) that read it and compare them with the operator's
28
28
  allowed and acknowledged lists. Needs no ``DBT_TARGET_SCHEMA`` and creates nothing.
29
29
  - ``probe_views``: try each view of ``PROBE_VIEWS`` with a zero-row read and report
30
30
  which ones no longer bind. Needs no ``DBT_TARGET_SCHEMA`` and creates nothing.
31
- The inputs and the result block of both ops are in ``preflight``.
31
+ The inputs and the result block of each op are in its own module.
32
32
 
33
33
  The engine adapter is discovered from the single installed
34
34
  ``continuo_engine.adapters`` entry point — each runner image installs exactly one.
@@ -49,7 +49,7 @@ from continuo_engine_contract.port import ( # type: ignore[import-untyped]
49
49
  )
50
50
  from continuo_python_runtime.csv_readers import reader_for
51
51
  from continuo_python_runtime.csv_source import check_header, parse_csv_uri
52
- from continuo_python_runtime.validation import preflight, s3
52
+ from continuo_python_runtime.validation import dependents_check, probe_views, s3
53
53
 
54
54
  logger = logging.getLogger("validation_runner")
55
55
 
@@ -119,15 +119,15 @@ def load_candidate_spec() -> dict:
119
119
  return spec
120
120
 
121
121
 
122
- _NODE_OPS = ("build_from_sql", "clone_from_prod", "build_from_columns", "check_binds")
122
+ _NODE_OPS = ("build_from_sql", "build_from_prod", "build_from_columns", "check_binds")
123
123
  _SCHEMA_OPS = ("ensure_schema", "drop_schema")
124
- _PREFLIGHT_OPS = ("seed_preflight", "probe_views")
124
+ _WAREHOUSE_READ_OPS = ("dependents_check", "probe_views")
125
125
 
126
126
 
127
127
  def main() -> None:
128
128
  """Run one validation op end to end; exits non-zero on failure.
129
129
 
130
- Node ops (``build_from_sql``/``clone_from_prod``/``build_from_columns``)
130
+ Node ops (``build_from_sql``/``build_from_prod``/``build_from_columns``)
131
131
  materialize one empty node table and require ``TABLE_NAME``. ``check_binds``
132
132
  is also a node op and requires ``TABLE_NAME`` (for identity only, in the
133
133
  result block's ``unique_id``) but creates nothing: it bind-checks a dbt
@@ -135,19 +135,27 @@ def main() -> None:
135
135
  Schema ops (``ensure_schema``/``drop_schema``) act on the whole candidate
136
136
  schema — the executor schedules them as one-shot engine-image Jobs to own
137
137
  the candidate-schema lifecycle without connecting to the warehouse itself —
138
- and take no table. The preflight ops (``seed_preflight``/``probe_views``) read
139
- their own inputs, need no candidate schema and exit with the code ``preflight``
140
- returns.
138
+ and take no table. The warehouse-read ops (``dependents_check``/``probe_views``)
139
+ read the warehouse and change nothing; they read their own inputs, need no
140
+ candidate schema and exit with the code their own module's function
141
+ returns. An unknown op is refused before any input is read.
141
142
  """
142
143
  logging.basicConfig(
143
144
  level=logging.INFO, stream=sys.stderr, format="%(levelname)s %(name)s: %(message)s"
144
145
  )
145
146
  op = os.environ.get("VALIDATION_OP", "build_from_sql")
146
- if op in _PREFLIGHT_OPS:
147
- if op == "seed_preflight":
148
- code = preflight.run_seed_preflight(os.environ)
147
+ if op not in (*_NODE_OPS, *_SCHEMA_OPS, *_WAREHOUSE_READ_OPS):
148
+ target_schema = os.environ.get("DBT_TARGET_SCHEMA", "")
149
+ unique_id = _node_id() or (f"schema.{target_schema}" if target_schema else "")
150
+ logger.error("unknown VALIDATION_OP %r", op)
151
+ print(result.result_block("error", f"unknown VALIDATION_OP {op!r}",
152
+ unique_id=unique_id), flush=True)
153
+ sys.exit(2)
154
+ if op in _WAREHOUSE_READ_OPS:
155
+ if op == "dependents_check":
156
+ code = dependents_check.run_dependents_check(os.environ)
149
157
  else:
150
- code = preflight.run_probe_views(os.environ)
158
+ code = probe_views.run_probe_views(os.environ)
151
159
  if code:
152
160
  sys.exit(code)
153
161
  return
@@ -222,14 +230,8 @@ def main() -> None:
222
230
  sys.exit(2)
223
231
  else:
224
232
  prod_schema = _require("PROD_SCHEMA")
225
- elif op in _SCHEMA_OPS:
226
- unique_id = _node_id() or f"schema.{schema}"
227
233
  else:
228
234
  unique_id = _node_id() or f"schema.{schema}"
229
- logger.error("unknown VALIDATION_OP %r", op)
230
- print(result.result_block("error", f"unknown VALIDATION_OP {op!r}",
231
- unique_id=unique_id), flush=True)
232
- sys.exit(2)
233
235
 
234
236
  # Engine selection is discovery, not configuration: the image installs one adapter.
235
237
  try:
@@ -290,8 +292,8 @@ def main() -> None:
290
292
  adapter.check_binds(read_sql)
291
293
  adapter.build_empty_from_columns(schema, table, spec["output_columns"], config)
292
294
  else:
293
- assert prod_schema is not None, "prod_schema must be set for clone_from_prod"
294
- adapter.clone_empty_from_prod(schema, prod_schema, table)
295
+ assert prod_schema is not None, "prod_schema must be set for build_from_prod"
296
+ adapter.build_empty_from_prod(schema, prod_schema, table)
295
297
  except Exception as exc:
296
298
  logger.error("ERROR op=%s on schema %s: %s", op, schema, exc)
297
299
  print(result.result_block("error", str(exc), unique_id=unique_id), flush=True)
@@ -0,0 +1,89 @@
1
+ """What the warehouse-read validation ops share: their inputs, their one block and their adapter.
2
+
3
+ The ops ``dependents_check`` (:mod:`~continuo_python_runtime.validation.dependents_check`)
4
+ and ``probe_views`` (:mod:`~continuo_python_runtime.validation.probe_views`) read the
5
+ warehouse and change nothing. Each prints exactly one structured result block as
6
+ the last line on stdout (``continuo_engine_contract.result``) and returns the
7
+ process exit code: 0 when the op ran to its conclusion, 1 when a ``check`` stops,
8
+ 2 when the op could not run (a bad input, no adapter, missing adapter env, an
9
+ unexpected error). The block's ``status`` is ``error`` for exit codes 1 and 2.
10
+ Diagnostics go to stderr through ``logging``; stdout carries only the block.
11
+ """
12
+ import json
13
+ import logging
14
+ from collections.abc import Callable, Mapping
15
+ from typing import Any, cast
16
+
17
+ from continuo_engine_contract import result # type: ignore[import-untyped]
18
+ from continuo_engine_contract.port import ( # type: ignore[import-untyped]
19
+ AdapterDiscoveryError,
20
+ WarehouseAdapter,
21
+ )
22
+
23
+ logger = logging.getLogger("validation_warehouse_read")
24
+
25
+ Discover = Callable[[], tuple[str, type[WarehouseAdapter]]]
26
+
27
+ # Longest driver text kept in a block; the first line only, so a block stays small.
28
+ MAX_TEXT = 500
29
+
30
+
31
+ class InputError(Exception):
32
+ """An input of the op is missing or malformed."""
33
+
34
+
35
+ def first_line(exc: BaseException) -> str:
36
+ """The first line of an exception's text, at most ``MAX_TEXT`` characters, never empty."""
37
+ text = str(exc).strip()
38
+ line = text.splitlines()[0] if text else ""
39
+ return (line or type(exc).__name__)[:MAX_TEXT]
40
+
41
+
42
+ def json_list(env: Mapping[str, str], name: str, *, required: bool) -> list[str]:
43
+ """The env var *name* as a JSON array of strings; unset or empty is ``[]`` unless *required*."""
44
+ raw = env.get(name, "")
45
+ if not raw.strip():
46
+ if required:
47
+ raise InputError(f"missing required env var {name}")
48
+ return []
49
+ try:
50
+ value = json.loads(raw)
51
+ except json.JSONDecodeError as exc:
52
+ raise InputError(f"{name} is not valid JSON: {exc}") from exc
53
+ if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
54
+ raise InputError(f"{name} must be a JSON array of strings")
55
+ return cast(list[str], value)
56
+
57
+
58
+ def emit(
59
+ status: str, message: str, unique_id: str, reason: str, fields: dict[str, Any]
60
+ ) -> None:
61
+ """Print the op's one result block, the last line on stdout."""
62
+ print(
63
+ result.result_block(
64
+ status, message, 1 if status == "error" else 0, unique_id, reason=reason, fields=fields
65
+ ),
66
+ flush=True,
67
+ )
68
+
69
+
70
+ def discover_and_check_env(
71
+ env: Mapping[str, str], discover: Discover
72
+ ) -> tuple[str, type[WarehouseAdapter]]:
73
+ """The installed adapter, after checking its required env is present in *env*."""
74
+ try:
75
+ engine, adapter_cls = discover()
76
+ except AdapterDiscoveryError as exc:
77
+ raise InputError(str(exc)) from exc
78
+ missing = [name for name in adapter_cls.required_env() if not env.get(name)]
79
+ if missing:
80
+ raise InputError(f"missing required env for engine {engine!r}: {', '.join(missing)}")
81
+ return engine, adapter_cls
82
+
83
+
84
+ def close_quietly(adapter: Any) -> None:
85
+ """Close the adapter; a failure only logs, so it never masks the op's outcome."""
86
+ try:
87
+ adapter.close()
88
+ except Exception as exc:
89
+ logger.error("adapter close failed: %s", exc)