datadouble 0.0.3__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.
datadouble/run.py ADDED
@@ -0,0 +1,1075 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Running the build stages, with manifests and resume.
5
+
6
+ A run belongs to a generation, and keeps its work under
7
+ ``<work dir>/<spec>/<generation>/``. Every stage writes its artifact and then
8
+ a manifest recording a hash of its inputs. Resuming a generation skips each
9
+ stage whose recorded input hash still matches, so a killed run picks up where
10
+ it stopped and a changed anonymization rule re-runs from ``transform``.
11
+
12
+ The work directory holds real personal data from ``extract`` until
13
+ ``transform`` has run: it is production scratch space and never leaves
14
+ production. Only verified images reach a store.
15
+ """
16
+
17
+ import datetime as dt
18
+ import hashlib
19
+ import hmac
20
+ import json
21
+ import os
22
+ import shutil
23
+ import time
24
+ from collections.abc import Callable, Iterable, Mapping
25
+ from contextlib import ExitStack
26
+ from dataclasses import dataclass, field
27
+ from enum import StrEnum
28
+ from pathlib import Path
29
+
30
+ from pydantic import AwareDatetime, BaseModel, ConfigDict, JsonValue, TypeAdapter
31
+
32
+ from datadouble import __version__
33
+ from datadouble.anonymize import Anonymizer, new_key
34
+ from datadouble.boundary import require_inside
35
+ from datadouble.catalog import CatalogLock
36
+ from datadouble.closure import pulled_rows
37
+ from datadouble.engine import (
38
+ Account,
39
+ Accounts,
40
+ EngineAdapter,
41
+ EngineError,
42
+ ExtractResult,
43
+ Mapper,
44
+ RequirementError,
45
+ Snapshot,
46
+ SourceSession,
47
+ TableCount,
48
+ Tooling,
49
+ Transformation,
50
+ WorkingDatabases,
51
+ check_owner,
52
+ group_extract_path,
53
+ unmet,
54
+ )
55
+ from datadouble.images import (
56
+ ImageArchive,
57
+ ImageError,
58
+ ImageIdentity,
59
+ ImageSummary,
60
+ Verification,
61
+ new_generation,
62
+ pack,
63
+ unpack,
64
+ version_line,
65
+ )
66
+ from datadouble.names import ColumnName, EngineName, Generation, GroupName, SourceName, TableName
67
+ from datadouble.planner import (
68
+ Plan,
69
+ PlannedGroup,
70
+ PlannedPaths,
71
+ PlannedRule,
72
+ PlanOptions,
73
+ SourceCatalog,
74
+ plan,
75
+ )
76
+ from datadouble.registry import Registry
77
+ from datadouble.secrets import resolve_secret
78
+ from datadouble.signing import bundle_key, sign
79
+ from datadouble.spec import (
80
+ FakerRule,
81
+ FormatPreservingRule,
82
+ HashRule,
83
+ ImageFormat,
84
+ Spec,
85
+ Strict,
86
+ )
87
+ from datadouble.storage import Store
88
+ from datadouble.subset import (
89
+ AnyOf,
90
+ Condition,
91
+ Graph,
92
+ KeyReader,
93
+ KeyTuple,
94
+ ValuesIn,
95
+ key_conditions,
96
+ nested_conditions,
97
+ )
98
+ from datadouble.verify import FormatReport, VerificationReport, check_image, restore_failed
99
+ from datadouble.versions import newest
100
+
101
+
102
+ class Stage(StrEnum):
103
+ """The build stages, in pipeline order."""
104
+
105
+ PLAN = "plan"
106
+ EXTRACT = "extract"
107
+ LOAD = "load"
108
+ TRANSFORM = "transform"
109
+ PACKAGE = "package"
110
+ VERIFY = "verify"
111
+ STORE = "store"
112
+
113
+
114
+ class RunError(Exception):
115
+ """A run that cannot continue."""
116
+
117
+
118
+ class _Model(BaseModel):
119
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
120
+
121
+
122
+ class RunRecord(_Model):
123
+ """What a generation was started with; read back when resuming."""
124
+
125
+ generation: Generation
126
+ spec: str
127
+ created_at: AwareDatetime
128
+ retry_key: str | None = None
129
+ """The CI system's ID for the run that started the generation (``RunOptions.retry_key``)."""
130
+
131
+
132
+ class StageManifest(_Model):
133
+ """A completed stage: what went in, how long it took and what came out."""
134
+
135
+ stage: Stage
136
+ group: GroupName | None
137
+ inputs: str
138
+ finished_at: AwareDatetime
139
+ seconds: float
140
+ outputs: dict[str, JsonValue]
141
+
142
+
143
+ class StageStatus(StrEnum):
144
+ """Whether a stage did its work this time."""
145
+
146
+ RAN = "ran"
147
+ REUSED = "reused"
148
+
149
+
150
+ class StageRecord(_Model):
151
+ """One stage's part in a run."""
152
+
153
+ stage: Stage
154
+ group: GroupName | None
155
+ status: StageStatus
156
+ seconds: float
157
+ engine: EngineName | None = None
158
+ """The engine of a second source, such as ``files``; None for the spec's source."""
159
+
160
+
161
+ class RunResult(_Model):
162
+ """The outcome of a run, returned in the JSON response."""
163
+
164
+ generation: Generation
165
+ work: str
166
+ stages: tuple[StageRecord, ...]
167
+ verification: tuple[VerificationReport, ...]
168
+ images: tuple[ImageSummary, ...]
169
+ stored: tuple[str, ...]
170
+ warnings: tuple[str, ...]
171
+
172
+ def failed(self) -> bool:
173
+ """Whether any verification failed."""
174
+ return any(not report.passed() for report in self.verification)
175
+
176
+
177
+ class SourceExtract(_Model):
178
+ """What one source's snapshot read, and when it was opened."""
179
+
180
+ source: SourceName
181
+ opened_at: AwareDatetime
182
+ """When its snapshot was opened: each source is its own point in time."""
183
+ result: ExtractResult
184
+
185
+
186
+ class RunOptions(_Model):
187
+ """How to run: which stages, where, and overrides over the spec."""
188
+
189
+ stages: tuple[Stage, ...]
190
+ work: Path
191
+ resume: Generation | None = None
192
+ retry_key: str | None = None
193
+ """The CI system's ID for this run, the same when it is retried: a retry resumes
194
+ the generation started under the same key, and anything else starts a new one."""
195
+ plan: PlanOptions = PlanOptions()
196
+ within: Path | None = None
197
+ """The generation directory of the run whose spec's second source, such as its
198
+ ``files``, this run builds."""
199
+
200
+
201
+ _JSON = TypeAdapter(JsonValue)
202
+ _MANIFEST = "manifest.json"
203
+ _PATHS = "paths.json"
204
+ """The extract's file of the values of ``files.paths_from`` for the chosen rows."""
205
+ _PATH_LIST: TypeAdapter[list[str]] = TypeAdapter(list[str])
206
+ _VALUE_RULES = (FakerRule, HashRule, FormatPreservingRule)
207
+
208
+
209
+ def fingerprint(value: object) -> str:
210
+ """A SHA-256 over a value's canonical JSON form."""
211
+ data = TypeAdapter(object).dump_python(value, mode="json")
212
+ text = json.dumps(data, sort_keys=True, separators=(",", ":"))
213
+ return "sha256:" + hashlib.sha256(text.encode()).hexdigest()
214
+
215
+
216
+ def value_mapper(anonymizer: Anonymizer) -> Mapper:
217
+ """Replacements for value rules; other rules are applied by the engine."""
218
+
219
+ def mapper(rule: PlannedRule, values: Iterable[str]) -> dict[str, str]:
220
+ value_rule = rule.rule
221
+ if not isinstance(value_rule, _VALUE_RULES):
222
+ message = f"{rule.column}: {type(value_rule).__name__} is applied by the engine"
223
+ raise RunError(message)
224
+ unique = isinstance(value_rule, FakerRule) and value_rule.unique
225
+ return anonymizer.mapping(value_rule, rule.kind, values, unique=unique)
226
+
227
+ return mapper
228
+
229
+
230
+ def _now() -> dt.datetime:
231
+ return dt.datetime.now(tz=dt.UTC)
232
+
233
+
234
+ class Run:
235
+ """One generation's work directory and the stages that fill it."""
236
+
237
+ def __init__(
238
+ self,
239
+ spec: Spec,
240
+ lock: CatalogLock | None,
241
+ registry: Registry,
242
+ options: RunOptions,
243
+ clock: Callable[[], dt.datetime] = _now,
244
+ ) -> None:
245
+ """Open a new generation or the one being resumed, or join one (``options.within``)."""
246
+ self.spec = spec
247
+ self.lock = lock
248
+ self.registry = registry
249
+ self.options = options
250
+ self.clock = clock
251
+ self.engine: EngineAdapter = registry.engine(spec.engine)
252
+ self.resumed = False
253
+ if options.within is None:
254
+ self.record = self._record()
255
+ self.root = (options.work / spec.name / self.record.generation).resolve()
256
+ else:
257
+ self.record = RunRecord.model_validate_json((options.within / "run.json").read_bytes())
258
+ self.root = options.within / spec.engine
259
+ self.root.mkdir(exist_ok=True)
260
+ self.records: list[StageRecord] = []
261
+ self.warnings: list[str] = []
262
+ self._sessions: dict[SourceName, SourceSession] | None = None
263
+ self._tooling: Tooling | None = None
264
+ self._exits = ExitStack()
265
+ self._accounts: tuple[Account, ...] | None = None
266
+
267
+ # The generation
268
+
269
+ def _retried(self) -> Generation | None:
270
+ """The generation an earlier attempt with this run's retry key started."""
271
+ key = self.options.retry_key
272
+ if key is None:
273
+ return None
274
+ for path in sorted((self.options.work / self.spec.name).glob("*/run.json"), reverse=True):
275
+ record = RunRecord.model_validate_json(path.read_bytes())
276
+ if record.retry_key == key:
277
+ return record.generation
278
+ return None
279
+
280
+ def _record(self) -> RunRecord:
281
+ resume = self.options.resume or self._retried()
282
+ if resume is None:
283
+ created = self.clock()
284
+ generation = new_generation(int(created.timestamp() * 1000))
285
+ record = RunRecord(
286
+ generation=generation,
287
+ spec=self.spec.name,
288
+ created_at=created,
289
+ retry_key=self.options.retry_key,
290
+ )
291
+ root = self.options.work / self.spec.name / generation
292
+ try:
293
+ root.mkdir(parents=True, exist_ok=False)
294
+ (root / "run.json").write_text(record.model_dump_json(indent=2), encoding="utf-8")
295
+ except OSError as error:
296
+ message = f"cannot start a generation in {self.options.work}: {error.strerror}"
297
+ raise RunError(message) from None
298
+ return record
299
+ path = self.options.work / self.spec.name / resume / "run.json"
300
+ if not path.is_file():
301
+ message = f"there is no generation {resume} of {self.spec.name} to resume"
302
+ raise RunError(message)
303
+ self.resumed = True
304
+ return RunRecord.model_validate_json(path.read_bytes())
305
+
306
+ def key(self) -> bytes:
307
+ """The anonymization key: from the spec, or generated once per generation."""
308
+ ref = self.spec.secrets.anonymization_key
309
+ if ref is not None:
310
+ return resolve_secret(ref).encode()
311
+ path = self.root / "key"
312
+ if not path.is_file():
313
+ descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
314
+ with os.fdopen(descriptor, "wb") as handle:
315
+ handle.write(new_key())
316
+ return path.read_bytes()
317
+
318
+ # Stage bookkeeping
319
+
320
+ def _dir(self, stage: Stage, group: GroupName | None = None) -> Path:
321
+ return self.root / stage if group is None else self.root / stage / group
322
+
323
+ def manifest(self, stage: Stage, group: GroupName | None = None) -> StageManifest | None:
324
+ """A completed stage's manifest, if there is one."""
325
+ path = self._dir(stage, group) / _MANIFEST
326
+ return StageManifest.model_validate_json(path.read_bytes()) if path.is_file() else None
327
+
328
+ def required(self, stage: Stage, group: GroupName | None = None) -> StageManifest:
329
+ """A completed stage's manifest; raises if the stage has not completed."""
330
+ found = self.manifest(stage, group)
331
+ if found is None:
332
+ message = (
333
+ f"stage {stage} has not completed in generation {self.record.generation}; "
334
+ "include it in the stages to run"
335
+ )
336
+ raise RunError(message)
337
+ return found
338
+
339
+ def _discard(self, directory: Path) -> None:
340
+ """Clear an earlier attempt's directory.
341
+
342
+ It is moved aside first: a process the interrupted attempt started may
343
+ still be writing into it, and must not get in the way of the new attempt.
344
+ """
345
+ if self._tooling is not None:
346
+ self._tooling.runtime.release(directory)
347
+ stale = self.root / ".stale" / f"{directory.name}-{time.time_ns()}"
348
+ stale.parent.mkdir(exist_ok=True)
349
+ directory.rename(stale)
350
+ shutil.rmtree(stale, ignore_errors=True)
351
+
352
+ def _wanted(self, stage: Stage) -> bool:
353
+ return stage in self.options.stages
354
+
355
+ def _stage(
356
+ self,
357
+ stage: Stage,
358
+ group: GroupName | None,
359
+ inputs: object,
360
+ work: Callable[[Path], dict[str, JsonValue]],
361
+ ) -> StageManifest:
362
+ """Run ``work`` in a fresh directory unless a manifest with these inputs exists."""
363
+ digest = fingerprint(inputs)
364
+ existing = self.manifest(stage, group)
365
+ if existing is not None and existing.inputs == digest:
366
+ self.records.append(
367
+ StageRecord(
368
+ stage=stage,
369
+ group=group,
370
+ status=StageStatus.REUSED,
371
+ seconds=0.0,
372
+ engine=self._second(),
373
+ )
374
+ )
375
+ return existing
376
+ if not self._wanted(stage):
377
+ message = (
378
+ f"stage {stage} has to run (its inputs changed or it never ran) but was "
379
+ "not requested; include it in the stages to run"
380
+ )
381
+ raise RunError(message)
382
+ directory = self._dir(stage, group)
383
+ if directory.exists():
384
+ self._discard(directory)
385
+ directory.mkdir(parents=True)
386
+ started = time.monotonic()
387
+ outputs = work(directory)
388
+ seconds = round(time.monotonic() - started, 3)
389
+ manifest = StageManifest(
390
+ stage=stage,
391
+ group=group,
392
+ inputs=digest,
393
+ finished_at=self.clock(),
394
+ seconds=seconds,
395
+ outputs=outputs,
396
+ )
397
+ (directory / _MANIFEST).write_text(manifest.model_dump_json(indent=2), encoding="utf-8")
398
+ self.records.append(
399
+ StageRecord(
400
+ stage=stage,
401
+ group=group,
402
+ status=StageStatus.RAN,
403
+ seconds=seconds,
404
+ engine=self._second(),
405
+ )
406
+ )
407
+ return manifest
408
+
409
+ def _second(self) -> EngineName | None:
410
+ """The engine, if this run builds a second source."""
411
+ return None if self.options.within is None else self.engine.name
412
+
413
+ # Stages
414
+
415
+ def tooling(self) -> Tooling:
416
+ """The container runtime engine software runs in, built on first use."""
417
+ if self._tooling is None:
418
+ if self.spec.runtime is None:
419
+ message = (
420
+ "the spec has no `runtime`; extract and the stages after it run engine "
421
+ "software in containers (`runtime: {docker: {}}` or `{kubernetes: ...}`)"
422
+ )
423
+ raise RunError(message)
424
+ ((kind, settings),) = self.spec.runtime.items()
425
+ self._tooling = Tooling(
426
+ runtime=self.registry.runtime(kind, settings),
427
+ image=self.spec.working.image,
428
+ server=self.spec.working.server,
429
+ )
430
+ return self._tooling
431
+
432
+ def sessions(self) -> dict[SourceName, SourceSession]:
433
+ """A connection to every source, in the spec's order, opened on first use."""
434
+ if self._sessions is None:
435
+ require_inside("reading the source", self.registry)
436
+ self._sessions = {
437
+ name: self._exits.enter_context(self.engine.connect(source.connection))
438
+ for name, source in self.spec.sources.items()
439
+ }
440
+ return self._sessions
441
+
442
+ def plan(self) -> Plan:
443
+ """Plan against the live catalog, or reuse the generation's plan."""
444
+ path = self._dir(Stage.PLAN) / "plan.json"
445
+ if not self._wanted(Stage.PLAN):
446
+ if not path.is_file() or self.manifest(Stage.PLAN) is None:
447
+ message = f"generation {self.record.generation} has no plan; include plan"
448
+ raise RunError(message)
449
+ return Plan.model_validate_json(path.read_bytes())
450
+ sources = catalogs(self.sessions())
451
+ options = self.options.plan.model_copy(update={"now": self.record.created_at})
452
+ planned = plan(self.spec, sources, self.lock, self.engine.capabilities(), options)
453
+ inputs = {
454
+ "spec": self.spec,
455
+ "sources": [(s.name, s.catalog.fingerprint(), s.server_version) for s in sources],
456
+ "lock": None if self.lock is None else self.lock.fingerprint,
457
+ "options": options,
458
+ }
459
+
460
+ def work(directory: Path) -> dict[str, JsonValue]:
461
+ (directory / "plan.json").write_text(planned.model_dump_json(indent=2), "utf-8")
462
+ return {"strategy": planned.strategy.value, "tables": len(planned.extracted())}
463
+
464
+ self._stage(Stage.PLAN, None, inputs, work)
465
+ self.warnings.extend(planned.warnings)
466
+ return Plan.model_validate_json(path.read_bytes())
467
+
468
+ def extract(self, planned: Plan) -> tuple[SourceExtract, ...]:
469
+ """Read the chosen rows of every source, each under its own snapshot.
470
+
471
+ The snapshots are opened one after another before anything is read,
472
+ so they are as close together as the sources allow.
473
+ """
474
+ inputs = {
475
+ "tables": planned.tables,
476
+ "edges": planned.edges,
477
+ "strategy": planned.strategy,
478
+ "as_of": planned.as_of,
479
+ "excludes": planned.excludes,
480
+ "catalog": planned.catalog_fingerprint,
481
+ "pulled": [(g.name, g.tables, g.pulled) for g in planned.groups if g.standalone],
482
+ "sources": planned.sources,
483
+ "followed": None
484
+ if self.options.within is None
485
+ else fingerprint((self.options.within / Stage.EXTRACT / _MANIFEST).read_bytes()),
486
+ }
487
+
488
+ def work(directory: Path) -> dict[str, JsonValue]:
489
+ graph = planned.graph()
490
+ sessions = self.sessions()
491
+ with ExitStack() as stack:
492
+ snapshots: dict[SourceName, Snapshot] = {}
493
+ opened: dict[SourceName, dt.datetime] = {}
494
+ for source in planned.sources:
495
+ snapshots[source.name] = stack.enter_context(
496
+ sessions[source.name].snapshot(planned.as_of)
497
+ )
498
+ opened[source.name] = self.clock()
499
+ reader = _Routed(planned, snapshots)
500
+ selections = (
501
+ nested_conditions(graph)
502
+ if planned.strategy == "nested"
503
+ else key_conditions(graph, reader)
504
+ )
505
+ selections = self._followed(planned, selections)
506
+ results: list[JsonValue] = []
507
+ for source in planned.sources:
508
+ result = snapshots[source.name].extract(
509
+ planned.of_source(source.name),
510
+ selections,
511
+ directory / "data" / source.name,
512
+ self.tooling(),
513
+ )
514
+ read = SourceExtract(
515
+ source=source.name, opened_at=opened[source.name], result=result
516
+ )
517
+ results.append(_JSON.validate_python(read.model_dump(mode="json")))
518
+ self._pull(planned, graph, reader, selections, directory)
519
+ unmatched = 0
520
+ if planned.paths_from is not None:
521
+ paths, unmatched = self._paths(
522
+ planned, planned.paths_from, graph, reader, selections
523
+ )
524
+ (directory / _PATHS).write_text(json.dumps(paths), "utf-8")
525
+ return {"sources": results, "unmatched_paths": unmatched}
526
+
527
+ manifest = self._stage(Stage.EXTRACT, None, inputs, work)
528
+ unmatched = manifest.outputs.get("unmatched_paths")
529
+ if unmatched:
530
+ self.warnings.append(
531
+ f"files.paths_from: {unmatched} value(s) did not match the pattern, so their"
532
+ " files were not copied; check `match`"
533
+ )
534
+ return _load(tuple[SourceExtract, ...], manifest.outputs["sources"])
535
+
536
+ def _pull(
537
+ self,
538
+ planned: Plan,
539
+ graph: Graph,
540
+ reader: "_Routed",
541
+ selections: dict[TableName, Condition],
542
+ directory: Path,
543
+ ) -> None:
544
+ """Read, under each source's snapshot, the rows standalone groups pull in.
545
+
546
+ Each standalone group's pulled-in tables, and its own tables that gain
547
+ rows they reference, are extracted again with only the rows its image
548
+ holds, each by the source it belongs to, into that source's group
549
+ extract (:func:`~datadouble.engine.group_extract_path`); ``load``
550
+ takes them from there.
551
+ """
552
+ keyed: Mapping[TableName, Condition] | None = None
553
+ for group in planned.groups:
554
+ if not group.standalone or not group.pulled:
555
+ continue
556
+ if keyed is None:
557
+ # Nested conditions refer to other tables' selections, which a
558
+ # projection cannot see; the keys strategy's stand alone. Under
559
+ # the nested strategy this reads every table's keys once more,
560
+ # the cost that strategy otherwise avoids, and only when a
561
+ # standalone group pulls something in.
562
+ # A followed spec's rows (``_followed``) join them, as they
563
+ # joined the shared selections.
564
+ keyed = (
565
+ self._followed(planned, key_conditions(graph, reader))
566
+ if planned.strategy == "nested"
567
+ else selections
568
+ )
569
+ conditions = pulled_rows(
570
+ planned.edges, frozenset(group.tables), group.rows(), keyed, reader
571
+ )
572
+ for source in planned.sources:
573
+ own = planned.of_source(source.name)
574
+ tables = tuple(r for r in own.tables if r.table in conditions)
575
+ if not tables:
576
+ continue
577
+ target = group_extract_path(directory / "data" / source.name, group.name)
578
+ part = own.model_copy(update={"tables": tables})
579
+ reader.snapshots[source.name].extract(part, conditions, target, self.tooling())
580
+
581
+ @staticmethod
582
+ def _paths(
583
+ planned: Plan,
584
+ wanted: PlannedPaths,
585
+ graph: Graph,
586
+ snapshot: KeyReader,
587
+ selections: Mapping[TableName, Condition],
588
+ ) -> tuple[list[str], int]:
589
+ """The paths the chosen rows name, and how many values the pattern did not match.
590
+
591
+ The rows are read through the snapshot.
592
+ """
593
+ # A nested condition refers to other tables' selections, which a projection
594
+ # cannot see; the keys strategy's conditions stand alone.
595
+ keyed = key_conditions(graph, snapshot) if planned.strategy == "nested" else selections
596
+ rows = snapshot.project(wanted.table, keyed[wanted.table], wanted.columns)
597
+ paths: set[str] = set()
598
+ unmatched = 0
599
+ for row in rows:
600
+ path = wanted.path(row)
601
+ if path is not None:
602
+ paths.add(path)
603
+ elif all(value is not None for value in row):
604
+ unmatched += 1
605
+ return sorted(paths), unmatched
606
+
607
+ def _followed(
608
+ self, planned: Plan, selections: dict[TableName, Condition]
609
+ ) -> dict[TableName, Condition]:
610
+ """A second source's selections, with the rows the parent's ``paths_from`` names.
611
+
612
+ Each of the second source's tables also gets the rows whose key is one
613
+ of the paths; the adapter keeps those that are its own.
614
+ """
615
+ if self.options.within is None:
616
+ return selections
617
+ file = self.options.within / Stage.EXTRACT / _PATHS
618
+ if not file.is_file():
619
+ return selections
620
+ paths = frozenset((path,) for path in _PATH_LIST.validate_json(file.read_bytes()))
621
+ followed = dict(selections)
622
+ # The plan's catalog holds exactly the extracted tables.
623
+ for table in planned.catalog.tables:
624
+ followed[table.name] = AnyOf(
625
+ (selections[table.name], ValuesIn(table.primary_key, paths))
626
+ )
627
+ return followed
628
+
629
+ def load(self, working: WorkingDatabases, planned: Plan, group: PlannedGroup) -> None:
630
+ """Build the group's working database."""
631
+ inputs = {
632
+ "extract": fingerprint(self.required(Stage.EXTRACT)),
633
+ "group": group,
634
+ "hooks": self.spec.hooks.before_load,
635
+ }
636
+
637
+ def work(directory: Path) -> dict[str, JsonValue]:
638
+ counts = working.load(
639
+ planned,
640
+ group,
641
+ tuple(self._dir(Stage.EXTRACT) / "data" / s.name for s in planned.sources),
642
+ directory / "db",
643
+ self.spec.hooks.before_load,
644
+ )
645
+ return {"counts": _counts(counts)}
646
+
647
+ self._stage(Stage.LOAD, group.name, inputs, work)
648
+
649
+ def transform(
650
+ self, working: WorkingDatabases, planned: Plan, group: PlannedGroup, key: bytes
651
+ ) -> None:
652
+ """Anonymize a copy of the group's working database."""
653
+ members = set(group.packaged())
654
+ rules = tuple(rule for rule in planned.anonymization if rule.column.table in members)
655
+ anonymizer = Anonymizer(key)
656
+ key_id = hmac.new(key, b"datadouble key id", hashlib.sha256).hexdigest()[:16]
657
+ inputs = {
658
+ "load": fingerprint(self.required(Stage.LOAD, group.name)),
659
+ "rules": rules,
660
+ "hooks": self.spec.hooks.after_transform,
661
+ "key": key_id,
662
+ }
663
+
664
+ def work(directory: Path) -> dict[str, JsonValue]:
665
+ counts = working.transform(
666
+ group,
667
+ self._dir(Stage.LOAD, group.name) / "db",
668
+ directory / "db",
669
+ Transformation(rules, value_mapper(anonymizer), self.spec.hooks.after_transform),
670
+ )
671
+ return {
672
+ "counts": _counts(counts),
673
+ "rules": {str(r.column): fingerprint(r.rule) for r in rules},
674
+ "rewrites": [str(c) for c in planned.rewrites if c.table in members],
675
+ }
676
+
677
+ self._stage(Stage.TRANSFORM, group.name, inputs, work)
678
+
679
+ def identity(self, group: PlannedGroup, version: str) -> ImageIdentity:
680
+ """The identity of the group's image in this generation."""
681
+ return ImageIdentity(
682
+ spec=self.spec.name,
683
+ group=group.name,
684
+ engine=self.engine.name,
685
+ engine_version=version,
686
+ generation=self.record.generation,
687
+ )
688
+
689
+ def package(
690
+ self,
691
+ working: WorkingDatabases,
692
+ planned: Plan,
693
+ group: PlannedGroup,
694
+ context: "_Context",
695
+ ) -> None:
696
+ """Package every requested format of the group's image."""
697
+ extracts = context.extract
698
+ version = working.server_version()
699
+ identity = self.identity(
700
+ group, version_line(version, self.engine.capabilities().version_line)
701
+ )
702
+ accounts = self.accounts()
703
+ inputs = {
704
+ "transform": fingerprint(self.required(Stage.TRANSFORM, group.name)),
705
+ "formats": planned.formats,
706
+ "version": version,
707
+ "line": identity.engine_version,
708
+ # Keyed, so a changed password packages again without the inputs revealing it.
709
+ "accounts": [_account_digest(context.key, account) for account in accounts],
710
+ }
711
+
712
+ def work(directory: Path) -> dict[str, JsonValue]:
713
+ transformed = self.required(Stage.TRANSFORM, group.name)
714
+ build = {
715
+ "identity": identity,
716
+ "datadouble": __version__,
717
+ "sources": {
718
+ read.source: {
719
+ "server_version": read.result.server_version,
720
+ "snapshot": read.result.snapshot,
721
+ "snapshots": read.result.snapshots,
722
+ "snapshot_at": read.opened_at,
723
+ "snapshot_seconds": read.result.snapshot_seconds,
724
+ }
725
+ for read in extracts
726
+ },
727
+ "between_sources": planned.between_sources,
728
+ "spec_layers": planned.spec_layers,
729
+ "working_server_version": version,
730
+ "requirements": planned.catalog.requirements,
731
+ "omitted": planned.omitted,
732
+ "as_of": planned.as_of,
733
+ "strategy": planned.strategy,
734
+ "strict": planned.strict,
735
+ "excludes": planned.excludes,
736
+ "seeds": planned.seeds,
737
+ "unselected": planned.unselected,
738
+ "accounts": [
739
+ {"user": account.user, "privileges": account.privileges} for account in accounts
740
+ ],
741
+ "group": group,
742
+ "transform": transformed.outputs,
743
+ "stages": {r.stage.value: r.status.value for r in self.records},
744
+ }
745
+ manifest = json.dumps(
746
+ TypeAdapter(object).dump_python(build, mode="json"), indent=2, sort_keys=True
747
+ ).encode()
748
+ archives: list[JsonValue] = []
749
+ for image_format in planned.formats:
750
+ files = directory / str(image_format)
751
+ files.mkdir()
752
+ working.package(self._dir(Stage.TRANSFORM, group.name) / "db", image_format, files)
753
+ if accounts and image_format is ImageFormat.PHYSICAL:
754
+ _adding_accounts(working).add_accounts(files, accounts)
755
+ archive = directory / identity.archive_key(image_format).rsplit("/", 1)[1]
756
+ found = pack(files, manifest, archive)
757
+ shutil.rmtree(files)
758
+ entry = ImageArchive(
759
+ format=image_format, key=identity.archive_key(image_format), digest=found
760
+ )
761
+ archives.append(_JSON.validate_python(entry.model_dump(mode="json")))
762
+ return {
763
+ "identity": _JSON.validate_python(identity.model_dump(mode="json")),
764
+ "archives": archives,
765
+ "manifest_sha256": hashlib.sha256(manifest).hexdigest(),
766
+ "server_version": version,
767
+ }
768
+
769
+ self._stage(Stage.PACKAGE, group.name, inputs, work)
770
+
771
+ def verify(
772
+ self, working: WorkingDatabases, planned: Plan, group: PlannedGroup
773
+ ) -> VerificationReport:
774
+ """Restore every format and check it."""
775
+ packaged = self.required(Stage.PACKAGE, group.name)
776
+ transformed = self.required(Stage.TRANSFORM, group.name)
777
+ inputs = {
778
+ "package": fingerprint(packaged),
779
+ "edges": planned.edges,
780
+ "pii_allow": planned.pii_allow,
781
+ "assertions": planned.assertions,
782
+ }
783
+ expected = _load(tuple[TableCount, ...], transformed.outputs["counts"])
784
+
785
+ def work(directory: Path) -> dict[str, JsonValue]:
786
+ reports: list[FormatReport] = []
787
+ for archive in _load(tuple[ImageArchive, ...], packaged.outputs["archives"]):
788
+ file = self._dir(Stage.PACKAGE, group.name) / archive.key.rsplit("/", 1)[1]
789
+ scratch = directory / str(archive.format)
790
+ try:
791
+ image, _ = unpack(file, scratch / "archive")
792
+ with working.restore(image, archive.format, scratch / "restored") as restored:
793
+ reports.append(
794
+ check_image(planned, group, archive.format, restored, expected)
795
+ )
796
+ except (EngineError, ImageError, OSError) as error:
797
+ reports.append(restore_failed(archive.format, str(error)))
798
+ shutil.rmtree(scratch, ignore_errors=True)
799
+ report = VerificationReport(group=group.name, formats=tuple(reports))
800
+ return {"report": _JSON.validate_python(report.model_dump(mode="json"))}
801
+
802
+ manifest = self._stage(Stage.VERIFY, group.name, inputs, work)
803
+ return _load(VerificationReport, manifest.outputs["report"])
804
+
805
+ def summary(
806
+ self, planned: Plan, group: PlannedGroup, report: VerificationReport
807
+ ) -> ImageSummary:
808
+ """The image summary for the group's image."""
809
+ packaged = self.required(Stage.PACKAGE, group.name)
810
+ checks = report.checks()
811
+ return ImageSummary(
812
+ identity=_load(ImageIdentity, packaged.outputs["identity"]),
813
+ built_at=packaged.finished_at,
814
+ archives=_load(tuple[ImageArchive, ...], packaged.outputs["archives"]),
815
+ manifest_sha256=str(packaged.outputs["manifest_sha256"]),
816
+ strict=Strict.lowest() if planned.strict is None else planned.strict.strict,
817
+ server_version=str(packaged.outputs["server_version"]),
818
+ accounts=tuple(account.user for account in self.spec.package.accounts),
819
+ verification=Verification(
820
+ passed=report.passed(),
821
+ checks=len(checks),
822
+ failed=sum(not check.passed for check in checks),
823
+ ),
824
+ )
825
+
826
+ def accounts(self) -> tuple[Account, ...]:
827
+ """``package.accounts``, with their passwords resolved once, on first use."""
828
+ if self._accounts is None:
829
+ self._accounts = tuple(
830
+ Account(
831
+ user=account.user,
832
+ password=account.password
833
+ if isinstance(account.password, str)
834
+ else resolve_secret(account.password),
835
+ privileges=account.privileges,
836
+ )
837
+ for account in self.spec.package.accounts
838
+ )
839
+ return self._accounts
840
+
841
+ def stores(self) -> list[Store]:
842
+ """The spec's stores."""
843
+ return [
844
+ self.registry.store(kind, settings)
845
+ for entry in self.spec.store
846
+ for kind, settings in entry.items()
847
+ ]
848
+
849
+ def store(
850
+ self, group: PlannedGroup, summary: ImageSummary, report: VerificationReport
851
+ ) -> list[str]:
852
+ """Write a verified image, its summary and its verification report to every store."""
853
+ stores = self.stores()
854
+ if not stores:
855
+ message = "the spec lists no stores"
856
+ raise RunError(message)
857
+ inputs = {
858
+ "verify": fingerprint(self.required(Stage.VERIFY, group.name)),
859
+ "stores": self.spec.store,
860
+ # How to sign, never the key: a key reference names where the key lives.
861
+ "signing": self.spec.signing,
862
+ }
863
+
864
+ def work(_directory: Path) -> dict[str, JsonValue]:
865
+ written: list[JsonValue] = []
866
+ signed, bundle = summary, None
867
+ if self.spec.signing is not None:
868
+ bundle = sign(summary, self.spec.signing.cosign)
869
+ signed = summary.model_copy(update={"signature": bundle_key(summary)})
870
+ for store in stores:
871
+ for archive in summary.archives:
872
+ name = archive.key.rsplit("/", 1)[1]
873
+ store.put_file(archive.key, self._dir(Stage.PACKAGE, group.name) / name)
874
+ report_key = summary.identity.summary_key().replace(".summary.json", ".verify.json")
875
+ store.put_bytes(report_key, report.model_dump_json(indent=2).encode())
876
+ if bundle is not None:
877
+ store.put_bytes(bundle_key(summary), bundle)
878
+ # The summary goes last: its presence means the image is complete.
879
+ store.put_bytes(
880
+ summary.identity.summary_key(), signed.model_dump_json(indent=2).encode()
881
+ )
882
+ written.append(f"{store.describe()}/{summary.identity.summary_key()}")
883
+ return {"stored": written}
884
+
885
+ manifest = self._stage(Stage.STORE, group.name, inputs, work)
886
+ return _load(list[str], manifest.outputs["stored"])
887
+
888
+ # The whole run
889
+
890
+ def execute(self) -> RunResult:
891
+ """Run the requested stages, reusing completed ones.
892
+
893
+ A spec with ``files`` builds them as a second source in the same
894
+ generation: their extract follows the source's, and their groups' images
895
+ come after the source's.
896
+ """
897
+ with self._exits:
898
+ # An unresolvable password fails the run before it reads anything.
899
+ self.accounts()
900
+ files = self._files()
901
+ if files is not None:
902
+ self._exits.enter_context(files.exits)
903
+ planned = self.plan()
904
+ files_planned = files.plan() if files is not None else None
905
+ outputs = _Outputs()
906
+ if self._needs(Stage.EXTRACT):
907
+ with ExitStack() as opened:
908
+ builds: list[tuple[Run, _Context]] = [(self, self.extracted(planned))]
909
+ opened.callback(builds[0][1].working.close)
910
+ if files is not None and files_planned is not None:
911
+ builds.append((files, files.extracted(files_planned)))
912
+ opened.callback(builds[1][1].working.close)
913
+ for run, context in builds:
914
+ for group in context.planned.groups:
915
+ run.build(context, group, outputs)
916
+ if self.resumed:
917
+ # The interrupted attempt may have started a server after this one
918
+ # released its stage; every server of this run has stopped by now.
919
+ self.tooling().runtime.release(self.root)
920
+ records = [*self.records, *(files.records if files is not None else [])]
921
+ warnings = [*self.warnings, *(files.warnings if files is not None else [])]
922
+ return RunResult(
923
+ generation=self.record.generation,
924
+ work=str(self.root),
925
+ stages=tuple(records),
926
+ verification=tuple(outputs.reports),
927
+ images=tuple(outputs.summaries),
928
+ stored=tuple(outputs.stored),
929
+ warnings=tuple(warnings),
930
+ )
931
+
932
+ def _files(self) -> "Run | None":
933
+ """The run of the spec's ``files``, if it has them."""
934
+ spec = self.spec.files_spec()
935
+ if spec is None:
936
+ return None
937
+ # The spec's strict mode and formats are its source's; the files' have their own.
938
+ options = self.options.model_copy(
939
+ update={"plan": PlanOptions(layers=self.options.plan.layers), "within": self.root}
940
+ )
941
+ return Run(spec, None, self.registry, options, self.clock)
942
+
943
+ @property
944
+ def exits(self) -> ExitStack:
945
+ """What closes this run's connections."""
946
+ return self._exits
947
+
948
+ def extracted(self, planned: Plan) -> "_Context":
949
+ """Extract, and open the working databases the groups are built in."""
950
+ check_owner(self.engine)
951
+ scratch = self.root / "scratch"
952
+ # Check the image before reading the snapshot, which can take hours.
953
+ checked = bool(planned.catalog.requirements) and self._wanted(Stage.EXTRACT)
954
+ if checked:
955
+ version = newest(tuple(source.server_version for source in planned.sources))
956
+ checking = self.engine.working(scratch, self.tooling(), version)
957
+ try:
958
+ _require(checking, planned)
959
+ finally:
960
+ checking.close()
961
+ extracted = self.extract(planned)
962
+ # The sources share a version line (the plan checks), so the newest reads them all.
963
+ version = newest(tuple(read.result.server_version for read in extracted))
964
+ working = self.engine.working(scratch, self.tooling(), version)
965
+ if planned.catalog.requirements and not checked:
966
+ _require(working, planned)
967
+ return _Context(
968
+ working=working,
969
+ planned=planned,
970
+ extract=extracted,
971
+ key=self.key() if self._needs(Stage.TRANSFORM) else b"",
972
+ )
973
+
974
+ def _needs(self, stage: Stage) -> bool:
975
+ """Whether ``stage`` or a later one was requested."""
976
+ order = list(Stage)
977
+ return any(self._wanted(s) for s in order[order.index(stage) :])
978
+
979
+ def build(self, context: "_Context", group: PlannedGroup, outputs: "_Outputs") -> None:
980
+ """Build, check and store one group's image."""
981
+ working, planned = context.working, context.planned
982
+ if self._needs(Stage.LOAD):
983
+ self.load(working, planned, group)
984
+ if self._needs(Stage.TRANSFORM):
985
+ self.transform(working, planned, group, context.key)
986
+ if self._needs(Stage.PACKAGE):
987
+ self.package(working, planned, group, context)
988
+ if self._needs(Stage.VERIFY):
989
+ report = self.verify(working, planned, group)
990
+ outputs.reports.append(report)
991
+ summary = self.summary(planned, group, report)
992
+ outputs.summaries.append(summary)
993
+ # Only verified images are stored; a failed one makes the run fail.
994
+ if self._wanted(Stage.STORE) and report.passed():
995
+ outputs.stored.extend(self.store(group, summary, report))
996
+
997
+
998
+ @dataclass(frozen=True, slots=True)
999
+ class _Context:
1000
+ working: WorkingDatabases
1001
+ planned: Plan
1002
+ extract: tuple[SourceExtract, ...]
1003
+ key: bytes
1004
+
1005
+
1006
+ @dataclass(slots=True)
1007
+ class _Outputs:
1008
+ reports: list[VerificationReport] = field(default_factory=list[VerificationReport])
1009
+ summaries: list[ImageSummary] = field(default_factory=list[ImageSummary])
1010
+ stored: list[str] = field(default_factory=list[str])
1011
+
1012
+
1013
+ def catalogs(sessions: Mapping[SourceName, SourceSession]) -> tuple[SourceCatalog, ...]:
1014
+ """Every source's live catalog and server version, in the spec's order."""
1015
+ several = len(sessions) > 1
1016
+ return tuple(
1017
+ SourceCatalog(
1018
+ name=name,
1019
+ catalog=session.catalog(),
1020
+ server_version=session.server_version(),
1021
+ # Only several sources can collide on a database without tables.
1022
+ namespaces=session.namespaces() if several else (),
1023
+ )
1024
+ for name, session in sessions.items()
1025
+ )
1026
+
1027
+
1028
+ @dataclass(frozen=True, slots=True)
1029
+ class _Routed:
1030
+ """Reads each table's keys through the snapshot of the source that holds it."""
1031
+
1032
+ planned: Plan
1033
+ snapshots: Mapping[SourceName, Snapshot]
1034
+
1035
+ def project(
1036
+ self, table: TableName, condition: Condition, columns: tuple[ColumnName, ...]
1037
+ ) -> Iterable[KeyTuple]:
1038
+ return self.snapshots[self.planned.source_of(table)].project(table, condition, columns)
1039
+
1040
+
1041
+ def _counts(counts: tuple[TableCount, ...]) -> list[JsonValue]:
1042
+ return [_JSON.validate_python(count.model_dump(mode="json")) for count in counts]
1043
+
1044
+
1045
+ def _load[T](kind: type[T], value: JsonValue) -> T:
1046
+ """Read a manifest field back into its model, through JSON so enums parse."""
1047
+ return TypeAdapter(kind).validate_json(json.dumps(value))
1048
+
1049
+
1050
+ def _require(working: WorkingDatabases, planned: Plan) -> None:
1051
+ """Fail unless the working image provides every requirement the copies keep."""
1052
+ available = working.available()
1053
+ if available is None:
1054
+ return
1055
+ problems = tuple(
1056
+ (source.name, problem)
1057
+ for source in planned.sources
1058
+ for problem in unmet(source.requirements, available)
1059
+ )
1060
+ if problems:
1061
+ raise RequirementError(problems)
1062
+
1063
+
1064
+ def _account_digest(key: bytes, account: Account) -> str:
1065
+ """An HMAC of the account under the run's anonymization key, for the package inputs."""
1066
+ text = json.dumps([account.user, account.password, account.privileges.value])
1067
+ return hmac.new(key, b"datadouble account\0" + text.encode(), hashlib.sha256).hexdigest()
1068
+
1069
+
1070
+ def _adding_accounts(working: WorkingDatabases) -> Accounts:
1071
+ """``working``, as working databases that can add accounts (planning checked)."""
1072
+ if not isinstance(working, Accounts):
1073
+ message = "these working databases cannot give images accounts"
1074
+ raise EngineError(message)
1075
+ return working