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/closure.py ADDED
@@ -0,0 +1,712 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Package planning: what each image needs to work on its own.
5
+
6
+ Subset planning decides which rows to read. Package planning then asks, for
7
+ each image group, what the group's tables and declared objects need to work
8
+ in its image. It starts from the group's tables, its **roots** (the objects
9
+ ``objects:`` in the spec and the group declare, which code outside Datadouble
10
+ expects) and the objects that come with its tables (triggers on them, views
11
+ over them alone), and follows, transitively and across namespaces:
12
+
13
+ - references from a table up to its parents, where the reference is followed
14
+ (a fallback such as ``on_missing: null`` says the parent may be missing),
15
+ and down to its children where the spec follows them (``follow.down``);
16
+ - what a table's definition uses: a default's sequence or function, a
17
+ column's user-defined type;
18
+ - every object's dependency edges, exact and inferred.
19
+
20
+ The result is the group's **closure**. A ``standalone`` group starts from
21
+ the objects its ``include`` patterns match too, and pulls everything reached
22
+ that it does not include into its image: objects with their definitions, and
23
+ tables with the rows ``rows:`` asks for (by default those its rows
24
+ reference; :func:`pulled_rows` reads them). Other groups pull nothing in, so
25
+ they follow only what their tables and roots need of objects; references
26
+ between groups stay with ``requires:`` and fallbacks, and so do objects
27
+ another group's patterns place.
28
+
29
+ What an image cannot have fails the plan, naming the object and the path to
30
+ it: an excluded table an object needs (copies leave such an object out), or
31
+ an object the catalog does not list. When an inferred edge is on the path the
32
+ problem only warns, since inferred edges never fail a plan on their own.
33
+
34
+ The core knows nothing of how an engine creates an object; it records each
35
+ group's objects in dependency order, and the adapters create them from their
36
+ definitions.
37
+ """
38
+
39
+ from collections import deque
40
+ from collections.abc import Iterable, Mapping
41
+ from dataclasses import dataclass, field
42
+
43
+ from pydantic import BaseModel, ConfigDict, model_validator
44
+
45
+ from datadouble.catalog import Catalog, ObjectKind, ObjectRef, SourceObject
46
+ from datadouble.names import GroupName, TableName
47
+ from datadouble.spec import PulledRows
48
+ from datadouble.subset import (
49
+ AllRows,
50
+ AnyNull,
51
+ Condition,
52
+ Edge,
53
+ EdgeMode,
54
+ KeyReader,
55
+ KeyTuple,
56
+ NoRows,
57
+ Predicate,
58
+ ValuesIn,
59
+ all_of,
60
+ any_of,
61
+ )
62
+
63
+ type Node = TableName | ObjectRef
64
+
65
+
66
+ class _Model(BaseModel):
67
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
68
+
69
+
70
+ class Pulled(_Model):
71
+ """A table or object a standalone group's closure pulled into its image."""
72
+
73
+ table: TableName | None = None
74
+ object: ObjectRef | None = None
75
+ path: tuple[str, ...]
76
+ """How the closure reached it: the group's table or root it started from,
77
+ each table or object after that, and it."""
78
+ inferred: bool = False
79
+ """Whether an inferred edge is on the path, so a person should check it."""
80
+ rows: PulledRows | None = None
81
+ """For a table, which of its rows come with it."""
82
+
83
+ @model_validator(mode="after")
84
+ def _one_target(self) -> "Pulled":
85
+ if (self.table is None) == (self.object is None):
86
+ message = "a pulled-in item is either a table or an object"
87
+ raise ValueError(message)
88
+ return self
89
+
90
+ def __str__(self) -> str:
91
+ """``table shop.public.users (rows: referenced) from ...``."""
92
+ target = f"table {self.table}" if self.object is None else str(self.object)
93
+ rows = "" if self.rows is None else f" (rows: {self.rows})"
94
+ hint = ", by an inferred dependency" if self.inferred else ""
95
+ return f"{target}{rows}, reached by {' -> '.join(self.path)}{hint}"
96
+
97
+
98
+ @dataclass(frozen=True, slots=True)
99
+ class Packaging:
100
+ """What package planning reads: the live catalog and the subset plan's choices."""
101
+
102
+ catalog: Catalog
103
+ excluded: frozenset[TableName]
104
+ structure_only: frozenset[TableName]
105
+ edges: tuple[Edge, ...]
106
+ placement: dict[ObjectRef, tuple[GroupName, ...]] = field(
107
+ default_factory=dict[ObjectRef, tuple[GroupName, ...]]
108
+ )
109
+ """The groups whose ``include`` patterns match each object."""
110
+
111
+
112
+ @dataclass(frozen=True, slots=True)
113
+ class RowsRule:
114
+ """One ``rows`` override of a standalone group, resolved."""
115
+
116
+ key: str
117
+ """As the spec wrote it."""
118
+ rows: PulledRows
119
+ tables: frozenset[TableName] = frozenset()
120
+ """The tables a table key or glob matches."""
121
+ edge: Edge | None = None
122
+ """The reference a ``child.column -> parent`` key names."""
123
+
124
+
125
+ @dataclass(frozen=True, slots=True)
126
+ class GroupInput:
127
+ """One image group, as package planning sees it."""
128
+
129
+ name: GroupName
130
+ tables: frozenset[TableName]
131
+ roots: tuple[ObjectRef, ...] = ()
132
+ standalone: bool = False
133
+ allowed: frozenset[GroupName] = frozenset()
134
+ """The group and the groups it requires, whose objects it may need."""
135
+ elsewhere: frozenset[TableName] = frozenset()
136
+ """The tables of the groups it requires, provisioned alongside its image."""
137
+ rows: tuple[RowsRule, ...] = ()
138
+
139
+
140
+ @dataclass(frozen=True, slots=True)
141
+ class _Step:
142
+ path: tuple[Node, ...]
143
+ inferred: bool
144
+
145
+
146
+ @dataclass(slots=True)
147
+ class Closure:
148
+ """One group's closure, and what it found that an image cannot have."""
149
+
150
+ objects: tuple[ObjectRef, ...] = ()
151
+ """Every object the image needs, dependencies first."""
152
+ pulled: tuple[Pulled, ...] = ()
153
+ """What a standalone group pulls in that it does not include."""
154
+ tables: frozenset[TableName] = frozenset()
155
+ """The tables the image holds: the group's own, and those a standalone group pulls in."""
156
+ nodes: frozenset[Node] = frozenset()
157
+ """Every table and object reached, the group's own tables included."""
158
+ problems: list[str] = field(default_factory=list[str])
159
+ warnings: list[str] = field(default_factory=list[str])
160
+ broken: dict[ObjectRef, str] = field(default_factory=dict[ObjectRef, str])
161
+ """Objects on a failing path, with the problem; strict mode names them."""
162
+
163
+
164
+ def label(node: Node) -> str:
165
+ """``table shop.public.users`` or ``function shop.public.total(integer)``."""
166
+ return f"table {node}" if isinstance(node, TableName) else str(node)
167
+
168
+
169
+ _ROUTINES = frozenset({ObjectKind.FUNCTION, ObjectKind.PROCEDURE, ObjectKind.PACKAGE})
170
+ _PULLS_PARENTS = frozenset({EdgeMode.FOLLOW, EdgeMode.ALL})
171
+ _VIEWS = frozenset({ObjectKind.VIEW, ObjectKind.MATERIALIZED_VIEW})
172
+
173
+
174
+ class _Walk:
175
+ """One group's walk over the catalog's tables, references and objects."""
176
+
177
+ def __init__(self, packaging: Packaging, group: GroupInput) -> None:
178
+ self.packaging = packaging
179
+ self.group = group
180
+ self.name = group.name
181
+ self.own = group.tables
182
+ self.standalone = group.standalone
183
+ self.objects = {item.ref: item for item in packaging.catalog.objects}
184
+ self.included = frozenset(
185
+ ref for ref, groups in packaging.placement.items() if group.name in groups
186
+ )
187
+ self.tables = {
188
+ table.name: table
189
+ for table in packaging.catalog.tables
190
+ if table.name not in packaging.excluded
191
+ }
192
+ self.reached: dict[Node, _Step] = {}
193
+ self.present: set[TableName] = set(group.tables)
194
+ self.queue: deque[Node] = deque()
195
+ self.closure = Closure()
196
+ self.attaching: dict[TableName, list[SourceObject]] = {}
197
+ self.on_views: dict[ObjectRef, list[SourceObject]] = {}
198
+ """Triggers on each view, which come with it."""
199
+ for item in packaging.catalog.objects:
200
+ for table in _exact_tables(item):
201
+ self.attaching.setdefault(table, []).append(item)
202
+ if item.ref.kind is ObjectKind.TRIGGER:
203
+ for need in item.depends_on:
204
+ if need.object is not None and need.object.kind in _VIEWS and not need.inferred:
205
+ self.on_views.setdefault(need.object, []).append(item)
206
+ self.related: dict[TableName, list[tuple[TableName, Edge]]] = {}
207
+ for edge in packaging.edges:
208
+ # A reference to a table that is excluded, or not in the catalog,
209
+ # already fails the subset plan.
210
+ if edge.mode in _PULLS_PARENTS and edge.parent in self.tables:
211
+ self.related.setdefault(edge.child, []).append((edge.parent, edge))
212
+ if edge.down and edge.child in self.tables:
213
+ self.related.setdefault(edge.parent, []).append((edge.child, edge))
214
+ self.outside: list[tuple[ObjectRef, TableName, bool]] = []
215
+ """Tables outside a group that is not standalone, the objects needing them,
216
+ and whether by inferred edges."""
217
+ self.reaching: dict[TableName, list[Edge]] = {}
218
+ """The followed references that reach each table from the image."""
219
+
220
+ def run(self) -> Closure:
221
+ for table in sorted(self.own, key=str):
222
+ self.reach(table, _Step((table,), inferred=False))
223
+ for root in self.group.roots:
224
+ self.reach(root, _Step((root,), inferred=False))
225
+ if self.standalone:
226
+ # A standalone image holds the objects its patterns include.
227
+ for ref in sorted(self.included, key=str):
228
+ self.reach(ref, _Step((ref,), inferred=False))
229
+ while self.queue:
230
+ node = self.queue.popleft()
231
+ if isinstance(node, TableName):
232
+ self.visit_table(node)
233
+ else:
234
+ self.visit_object(node)
235
+ found = [n for n in self.reached if isinstance(n, ObjectRef) and n in self.objects]
236
+ self.closure.objects = _ordered(found, self.objects)
237
+ self.closure.nodes = frozenset(self.reached)
238
+ self.closure.tables = frozenset(self.present)
239
+ self.closure.pulled = self.pulled()
240
+ if not self.standalone:
241
+ self.placed(found)
242
+ self.unheld()
243
+ return self.closure
244
+
245
+ def placed(self, found: list[ObjectRef]) -> None:
246
+ """Fail objects the group needs that only groups it does not require include.
247
+
248
+ Objects that come with the group's own tables (a trigger on one, a
249
+ view over them alone) and its declared objects are its own, whatever
250
+ the patterns say.
251
+ """
252
+ for ref in found:
253
+ groups = self.packaging.placement.get(ref, ())
254
+ if not groups or set(groups) & self.group.allowed or not self.is_pulled(ref):
255
+ continue
256
+ path = " -> ".join(label(node) for node in self.reached[ref].path)
257
+ others = ", ".join(repr(g) for g in groups)
258
+ self.closure.problems.append(
259
+ f"group {self.name!r}: {ref} is in group {others}; add `requires:` for it, "
260
+ f"or make this group standalone; reached by {path}"
261
+ )
262
+
263
+ def reach(self, node: Node, step: _Step) -> None:
264
+ if node in self.reached:
265
+ return
266
+ self.reached[node] = step
267
+ if isinstance(node, TableName) and node not in self.own:
268
+ if not self.standalone:
269
+ return # Another group's, reached through requires or a fallback.
270
+ self.present.add(node)
271
+ self.queue.append(node)
272
+
273
+ def through(self, node: Node, target: Node, *, inferred: bool) -> _Step:
274
+ step = self.reached[node]
275
+ return _Step((*step.path, target), inferred=step.inferred or inferred)
276
+
277
+ def visit_table(self, name: TableName) -> None:
278
+ if self.standalone:
279
+ for related, reference in self.related.get(name, []):
280
+ self.reaching.setdefault(related, []).append(reference)
281
+ self.reach(related, self.through(name, related, inferred=False))
282
+ for edge in self.tables[name].depends_on:
283
+ target = edge.target
284
+ if isinstance(target, TableName) and target not in self.tables:
285
+ # A policy or check reading a table copies leave out.
286
+ self.closure.warnings.append(
287
+ f"group {self.name!r}: {label(name)} has a policy or check that reads "
288
+ f"{label(target)}, which is excluded or not in the catalog, so the image "
289
+ "may lack it"
290
+ )
291
+ continue
292
+ self.reach(target, self.through(name, target, inferred=edge.inferred))
293
+ for item in self.attaching.get(name, []):
294
+ if set(_exact_tables(item)) <= self.present:
295
+ self.reach(item.ref, self.through(name, item.ref, inferred=False))
296
+
297
+ def visit_object(self, ref: ObjectRef) -> None:
298
+ item = self.objects.get(ref)
299
+ if item is None:
300
+ self.unresolved(ref, ref, "is not in the catalog", inferred=False)
301
+ return
302
+ for edge in item.depends_on:
303
+ target = edge.target
304
+ if isinstance(target, TableName):
305
+ self.needs_table(ref, target, inferred=edge.inferred)
306
+ else:
307
+ self.reach(target, self.through(ref, target, inferred=edge.inferred))
308
+ for trigger in self.on_views.get(ref, []):
309
+ self.reach(trigger.ref, self.through(ref, trigger.ref, inferred=False))
310
+ if self.standalone and self.is_pulled(ref) and _inferred(item):
311
+ self.closure.warnings.append(
312
+ f"group {self.name!r}: {ref}'s dependencies are inferred from its body; "
313
+ "check that the image has what it uses, or declare that in objects"
314
+ )
315
+
316
+ def needs_table(self, ref: ObjectRef, table: TableName, *, inferred: bool) -> None:
317
+ if table in self.packaging.excluded:
318
+ how = "may need" if inferred else "needs"
319
+ reason = f"{how} {label(table)}, which is excluded, so copies leave it out"
320
+ self.unresolved(ref, ref, reason, inferred=inferred)
321
+ elif table not in self.tables:
322
+ self.unresolved(
323
+ ref, ref, f"needs {label(table)}, which is not in the catalog", inferred=inferred
324
+ )
325
+ else:
326
+ if not self.standalone and table not in self.own and table not in self.group.elsewhere:
327
+ self.outside.append((ref, table, inferred))
328
+ self.reach(table, self.through(ref, table, inferred=inferred))
329
+
330
+ def unheld(self) -> None:
331
+ """Fail declared objects, and objects they need, that need a table no image has.
332
+
333
+ A group that is not standalone pulls nothing in, so such an object
334
+ would be missing from its image. An object counts as declared when
335
+ any declared object reaches it, whatever reached it first.
336
+ """
337
+ rooted = self.rooted()
338
+ for ref, table, inferred in self.outside:
339
+ if ref not in rooted:
340
+ continue
341
+ nodes: tuple[Node, ...] = (*rooted[ref], table)
342
+ path = " -> ".join(label(node) for node in nodes)
343
+ text = (
344
+ f"group {self.name!r}: {label(ref)} needs {label(table)}, which group "
345
+ f"{self.name!r} does not hold; include it, or add `requires:` for a group "
346
+ f"holding it; reached by {path}"
347
+ )
348
+ if inferred:
349
+ self.closure.warnings.append(f"{text} (an inferred dependency: check it)")
350
+ else:
351
+ self.closure.problems.append(text)
352
+ self.closure.broken.setdefault(ref, text)
353
+
354
+ def rooted(self) -> dict[ObjectRef, tuple[ObjectRef, ...]]:
355
+ """Each object a declared object reaches through objects, with a path from it."""
356
+ found: dict[ObjectRef, tuple[ObjectRef, ...]] = {}
357
+ pending: deque[tuple[ObjectRef, tuple[ObjectRef, ...]]] = deque(
358
+ (root, (root,)) for root in self.group.roots
359
+ )
360
+ while pending:
361
+ ref, path = pending.popleft()
362
+ if ref in found:
363
+ continue
364
+ found[ref] = path
365
+ item = self.objects.get(ref)
366
+ for edge in item.depends_on if item is not None else ():
367
+ if edge.object is not None and edge.object not in found:
368
+ pending.append((edge.object, (*path, edge.object)))
369
+ return found
370
+
371
+ def unresolved(self, ref: ObjectRef, subject: Node, reason: str, *, inferred: bool) -> None:
372
+ step = self.reached[ref]
373
+ text = (
374
+ f"group {self.name!r}: {label(subject)} {reason}; reached by "
375
+ f"{' -> '.join(label(node) for node in step.path)}"
376
+ )
377
+ if inferred or step.inferred:
378
+ self.closure.warnings.append(f"{text} (an inferred dependency: check it)")
379
+ return
380
+ self.closure.problems.append(text)
381
+ for node in step.path:
382
+ if isinstance(node, ObjectRef):
383
+ self.closure.broken.setdefault(node, text)
384
+
385
+ def is_pulled(self, ref: ObjectRef) -> bool:
386
+ """Whether an object reached is pulled in.
387
+
388
+ Roots are not, nor objects that come with the group's own tables (a
389
+ trigger on one, a view over them alone, a trigger on such a view).
390
+ """
391
+ if len(self.reached[ref].path) == 1 or ref in self.included:
392
+ return False
393
+ item = self.objects[ref]
394
+ tables = set(_exact_tables(item))
395
+ if tables:
396
+ return not tables <= self.own
397
+ views = [
398
+ e.object
399
+ for e in item.depends_on
400
+ if ref.kind is ObjectKind.TRIGGER
401
+ and e.object is not None
402
+ and e.object.kind in _VIEWS
403
+ and e.object in self.reached
404
+ ]
405
+ return not views or any(self.is_pulled(view) for view in views)
406
+
407
+ def pulled(self) -> tuple[Pulled, ...]:
408
+ if not self.standalone:
409
+ return ()
410
+ pulled: list[Pulled] = []
411
+ used: set[str] = set()
412
+ for node, step in self.reached.items():
413
+ path = tuple(label(n) for n in step.path)
414
+ if isinstance(node, TableName):
415
+ if node in self.own:
416
+ continue
417
+ rows = self.rows(node, used)
418
+ pulled.append(Pulled(table=node, path=path, inferred=step.inferred, rows=rows))
419
+ elif node in self.objects and self.is_pulled(node):
420
+ pulled.append(Pulled(object=node, path=path, inferred=step.inferred))
421
+ self.closure.problems.extend(
422
+ f"group {self.name!r}: rows: {rule.key!r} matches no table its closure pulls in"
423
+ for rule in self.group.rows
424
+ if rule.key not in used
425
+ )
426
+ return tuple(pulled)
427
+
428
+ def rows(self, table: TableName, used: set[str]) -> PulledRows:
429
+ """Which rows of a pulled-in table come with it.
430
+
431
+ A reference key wins over a table key; with neither, a table a
432
+ reference reaches comes with the rows referenced, and one reached only
433
+ through objects comes without rows.
434
+ """
435
+ reaching = self.reaching.get(table, [])
436
+ by_edge = [r for r in self.group.rows if r.edge is not None and r.edge in reaching]
437
+ by_table = [r for r in self.group.rows if table in r.tables]
438
+ chosen = by_edge or by_table
439
+ used.update(rule.key for rule in (*by_edge, *by_table))
440
+ modes = {rule.rows for rule in chosen}
441
+ if len(modes) > 1:
442
+ keys = ", ".join(repr(rule.key) for rule in chosen)
443
+ self.closure.problems.append(
444
+ f"group {self.name!r}: rows {keys} disagree about {label(table)}"
445
+ )
446
+ wanted = (
447
+ chosen[0].rows if chosen else PulledRows.REFERENCED if reaching else PulledRows.NONE
448
+ )
449
+ if table in self.packaging.structure_only:
450
+ if wanted is not PulledRows.NONE and chosen:
451
+ self.closure.problems.append(
452
+ f"group {self.name!r}: rows asks for rows of {label(table)}, "
453
+ "which is structure-only"
454
+ )
455
+ return PulledRows.NONE
456
+ if not chosen and not reaching:
457
+ self.closure.warnings.append(
458
+ f"group {self.name!r}: {label(table)} is reached only through objects or "
459
+ "policies, not references, so it comes without rows; set `rows` for it to "
460
+ "copy some"
461
+ )
462
+ return wanted
463
+
464
+
465
+ def _exact_tables(item: SourceObject) -> tuple[TableName, ...]:
466
+ """The tables an object's exact edges name: those it comes with in a copy."""
467
+ return tuple(e.table for e in item.depends_on if e.table is not None and not e.inferred)
468
+
469
+
470
+ def _inferred(item: SourceObject) -> bool:
471
+ """Whether a routine has dependencies inferred from its body."""
472
+ return item.ref.kind in _ROUTINES and any(e.inferred for e in item.depends_on)
473
+
474
+
475
+ def ordered(found: Iterable[ObjectRef], catalog: Iterable[SourceObject]) -> tuple[ObjectRef, ...]:
476
+ """Objects in dependency order: each after those it needs, cycles broken by name.
477
+
478
+ Adapters create objects in this order, and drop them in its reverse.
479
+ """
480
+ return _ordered(list(found), {item.ref: item for item in catalog})
481
+
482
+
483
+ def _ordered(
484
+ found: list[ObjectRef], objects: dict[ObjectRef, SourceObject]
485
+ ) -> tuple[ObjectRef, ...]:
486
+ """``found`` in dependency order: each object after those it needs, cycles broken by name."""
487
+ members = set(found)
488
+ done: dict[ObjectRef, None] = {}
489
+ visiting: set[ObjectRef] = set()
490
+
491
+ def visit(ref: ObjectRef) -> None:
492
+ if ref in done or ref in visiting:
493
+ return
494
+ visiting.add(ref)
495
+ needs = [e.object for e in objects[ref].depends_on if e.object is not None]
496
+ for need in sorted(dict.fromkeys(n for n in needs if n in members), key=str):
497
+ visit(need)
498
+ visiting.discard(ref)
499
+ done[ref] = None
500
+
501
+ for ref in sorted(found, key=str):
502
+ visit(ref)
503
+ return tuple(done)
504
+
505
+
506
+ def close(packaging: Packaging, group: GroupInput) -> Closure:
507
+ """The closure of one group: its tables, its roots and everything they need."""
508
+ return _Walk(packaging, group).run()
509
+
510
+
511
+ _KEEPS_PARENTS = frozenset({EdgeMode.FOLLOW, EdgeMode.ALL, EdgeMode.DROP})
512
+ """Edges whose child rows need their parents in the image: followed ones, and
513
+ ``drop`` ones, whose child rows were kept because their parents were chosen."""
514
+
515
+
516
+ class _Rows:
517
+ """The rows of a standalone image beyond the shared extract, read by keys.
518
+
519
+ An own table's rows are its shared ones (``baseline``) and the extra rows
520
+ references bring to it. Only the extra rows lead anywhere new between own
521
+ tables, since the shared extract already holds what the shared rows need.
522
+ """
523
+
524
+ def __init__(
525
+ self,
526
+ edges: Iterable[Edge],
527
+ own: frozenset[TableName],
528
+ modes: Mapping[TableName, PulledRows],
529
+ baseline: Mapping[TableName, Condition],
530
+ ) -> None:
531
+ self.own, self.modes, self.baseline = own, modes, baseline
532
+ # Own tables the subset keeps without rows (structure-only) never gain any.
533
+ self.rowless = frozenset(t for t in own if isinstance(baseline[t], NoRows))
534
+ self.up: list[Edge] = []
535
+ self.down: list[Edge] = []
536
+ self.drops: list[Edge] = []
537
+ """``drop`` references to parents that gain no rows: the rows a table
538
+ gains keep them null, as the shared extract keeps its own."""
539
+ for edge in edges:
540
+ if edge.mode in _KEEPS_PARENTS and self.fills(edge.child) and self.takes(edge.parent):
541
+ self.up.append(edge)
542
+ elif edge.mode is EdgeMode.DROP and self.fills(edge.child):
543
+ self.drops.append(edge)
544
+ if edge.down and self.fills(edge.parent) and self.takes(edge.child):
545
+ self.down.append(edge)
546
+ self.values: dict[tuple[Edge, bool], set[KeyTuple]] = {}
547
+ """Values read along each edge, upward (False) or downward (True)."""
548
+ self.parents: dict[Edge, set[KeyTuple]] = {}
549
+ """The parent keys each reference may hold, once rows are dropped."""
550
+
551
+ def fills(self, table: TableName) -> bool:
552
+ """Whether ``table`` is in the image with rows that can reference others."""
553
+ if table in self.own:
554
+ return table not in self.rowless
555
+ return self.modes.get(table) in {PulledRows.REFERENCED, PulledRows.ALL}
556
+
557
+ def takes(self, table: TableName) -> bool:
558
+ """Whether ``table`` gains the rows references bring.
559
+
560
+ Own tables with rows do, and ``referenced`` pulled-in ones.
561
+ """
562
+ if table in self.own:
563
+ return table not in self.rowless
564
+ return self.modes.get(table) is PulledRows.REFERENCED
565
+
566
+ def kept(self, table: TableName, condition: Condition) -> Condition:
567
+ """``condition`` without the rows the image cannot keep.
568
+
569
+ A ``drop`` reference to a parent without rows drops a row, as the
570
+ shared extract does; so does a reference to a parent row dropped so.
571
+ """
572
+ return all_of(
573
+ [
574
+ condition,
575
+ *(AnyNull(e.columns) for e in self.drops if e.child == table),
576
+ *(
577
+ any_of([AnyNull(e.columns), ValuesIn(e.columns, frozenset(keys))])
578
+ for e, keys in self.parents.items()
579
+ if e.child == table
580
+ ),
581
+ ]
582
+ )
583
+
584
+ def prune(self, reader: KeyReader) -> None:
585
+ """Drop the rows whose parent rows were dropped, until nothing changes.
586
+
587
+ Only a ``drop`` reference to a parent without rows drops a row the
588
+ image gained, so without one there is nothing to do. Parent rows only
589
+ leave, so the loop ends.
590
+ """
591
+ if not self.drops:
592
+ return
593
+ references = list(dict.fromkeys((*self.up, *self.down)))
594
+ changed = True
595
+ while changed:
596
+ changed = False
597
+ for edge in references:
598
+ parent = self.condition(edge.parent)
599
+ keys = {
600
+ row
601
+ for row in reader.project(edge.parent, parent, edge.parent_columns)
602
+ if all(value is not None for value in row)
603
+ }
604
+ if self.parents.get(edge) != keys:
605
+ self.parents[edge] = keys
606
+ changed = True
607
+
608
+ def brought(self, table: TableName) -> Condition:
609
+ """The rows references bring to ``table``, beyond the shared ones."""
610
+ return any_of(
611
+ [
612
+ *(
613
+ ValuesIn(e.parent_columns, frozenset(self.values.get((e, False), ())))
614
+ for e in self.up
615
+ if e.parent == table
616
+ ),
617
+ *(
618
+ _when(e, ValuesIn(e.columns, frozenset(self.values.get((e, True), ()))))
619
+ for e in self.down
620
+ if e.child == table
621
+ ),
622
+ ]
623
+ )
624
+
625
+ def condition(self, table: TableName) -> Condition:
626
+ if table in self.own:
627
+ return any_of([self.baseline[table], self.gains(table)])
628
+ if self.modes[table] is PulledRows.ALL or any(
629
+ e.parent == table and e.mode is EdgeMode.ALL for e in self.up
630
+ ):
631
+ return self.kept(table, AllRows())
632
+ return self.gains(table)
633
+
634
+ def gains(self, table: TableName) -> Condition:
635
+ """The rows references bring to ``table`` that it keeps."""
636
+ return self.kept(table, self.brought(table))
637
+
638
+ def gained(self, table: TableName) -> bool:
639
+ """Whether references brought ``table`` any rows."""
640
+ return any(self.values.get((e, False)) for e in self.up if e.parent == table) or any(
641
+ self.values.get((e, True)) for e in self.down if e.child == table
642
+ )
643
+
644
+ def step(self, table: TableName, reader: KeyReader) -> set[TableName]:
645
+ """Re-read what ``table``'s rows reference; the tables that gained rows."""
646
+ full = self.condition(table)
647
+ extra = self.gains(table) if table in self.own else full
648
+ grown: set[TableName] = set()
649
+ outgoing = [(e, False, e.columns, e.when, e.parent) for e in self.up if e.child == table]
650
+ outgoing += [
651
+ (e, True, e.parent_columns, None, e.child) for e in self.down if e.parent == table
652
+ ]
653
+ for edge, downward, columns, when, target in outgoing:
654
+ # Between own tables, the shared rows' references are already in place.
655
+ condition = extra if target in self.own else full
656
+ if isinstance(condition, NoRows):
657
+ continue
658
+ narrowed = all_of([condition, Predicate(when)]) if when else condition
659
+ fresh = {
660
+ row
661
+ for row in reader.project(table, narrowed, columns)
662
+ if all(value is not None for value in row)
663
+ }
664
+ known = self.values.setdefault((edge, downward), set())
665
+ if not fresh <= known:
666
+ known |= fresh
667
+ grown.add(target)
668
+ return grown
669
+
670
+
671
+ def _when(edge: Edge, condition: Condition) -> Condition:
672
+ return all_of([condition, Predicate(edge.when)]) if edge.when else condition
673
+
674
+
675
+ def pulled_rows(
676
+ edges: Iterable[Edge],
677
+ own: frozenset[TableName],
678
+ modes: Mapping[TableName, PulledRows],
679
+ baseline: Mapping[TableName, Condition],
680
+ reader: KeyReader,
681
+ ) -> dict[TableName, Condition]:
682
+ """The rows a standalone group's image needs beyond the shared extract.
683
+
684
+ ``modes`` gives each pulled-in table's rows, and ``baseline`` the
685
+ extract's conditions of the group's own tables, standing alone (as the
686
+ keys strategy computes them). Starting from those rows, references are
687
+ followed up to parents and down where the spec follows them, reading
688
+ keys through ``reader`` until nothing changes, as the keys strategy does.
689
+ The result holds a condition for each pulled-in table with rows, and for
690
+ each own table that gained rows, so every reference in the image keeps
691
+ its parent: a gained row's own references are followed too, up to
692
+ parents along followed and ``drop`` references and down where the spec
693
+ follows them, among own tables as well.
694
+ """
695
+ state = _Rows(edges, own, modes, baseline)
696
+ pending = sorted(own | frozenset(modes), key=str)
697
+ queued = set(pending)
698
+ while pending:
699
+ table = pending.pop(0)
700
+ queued.discard(table)
701
+ for grown in sorted(state.step(table, reader), key=str):
702
+ if grown not in queued:
703
+ queued.add(grown)
704
+ pending.append(grown)
705
+ state.prune(reader)
706
+ result = {
707
+ table: state.condition(table)
708
+ for table, mode in modes.items()
709
+ if mode is not PulledRows.NONE
710
+ }
711
+ result.update((table, state.condition(table)) for table in own if state.gained(table))
712
+ return result