askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
object_materialize.py · 58.6 KB · 1321 lines
| 1 | """Materialize block: declared generation jobs that CREATE new records. |
| 2 | |
| 3 | Implements ``plan/vocabulary/61-materialize-spec.md``. Sibling to |
| 4 | ``object_rollups.py`` (14-rollup-spec.md): both are declarative, |
| 5 | schema/config-parameterized, ride ``object_daemon.py``'s poll loop as one |
| 6 | more pass, and both write to a collection nothing else writes to. The |
| 7 | difference that makes this a distinct block rather than a rollup variant: |
| 8 | a rollup recompute REPLACES the whole answer every time (naturally |
| 9 | idempotent, disposable output); a materialize pass CREATES new records |
| 10 | other records come to depend on (a journal, a depreciation posting, a |
| 11 | seeded task), so a double-run is not "stale," it is a duplicate -- |
| 12 | genuinely destructive. Everything below exists to make "generate this |
| 13 | period's output" idempotent by construction rather than by discipline. |
| 14 | |
| 15 | **The three worked shapes, and how one mechanism spans them (61's Purpose |
| 16 | and Coverage):** |
| 17 | |
| 18 | 1. Recurring journals (``fin_recurring`` -> ``fin_journals`` + |
| 19 | ``fin_journal_lines``, ``trigger.mode: "scheduled"``): a header row per |
| 20 | due period, its child lines parsed VERBATIM from the source row's own |
| 21 | ``child_source_field`` JSON blob (already shaped like the child |
| 22 | schema's rows) -- see ``_build_child_rows_from_template``. |
| 23 | 2. Depreciation (``products`` -> ``fin_journals`` + ``fin_journal_lines``, |
| 24 | ``trigger.mode: "scheduled_fixed"``): 61's own Open Questions flags |
| 25 | this as genuinely underspecified ("this spec assumes a |
| 26 | debit_account_id/credit_account_id pair added to the definition |
| 27 | record... flagged as an implementation-time field, not fully specified |
| 28 | here"). This module's resolution, decided at implementation time: when |
| 29 | a definition declares ``child_collection`` but NO |
| 30 | ``child_source_field``, that absence IS the signal for the |
| 31 | "synthesized two-line depreciation shape" -- the definition MUST then |
| 32 | carry ``debit_account_id``/``credit_account_id`` plus a reserved |
| 33 | ``mapping.amount`` entry whose op is ``depreciation_amount``; exactly |
| 34 | two child lines are synthesized (debit the expense account, credit |
| 35 | accumulated depreciation, same amount both lines) rather than parsed |
| 36 | from source-row JSON. See ``_build_depreciation_child_rows``. Only |
| 37 | ``straight_line`` ships; a definition requesting ``declining`` is |
| 38 | rejected at parse time (``_validate_mapping_entry``), never silently |
| 39 | mis-computed -- 61's Purpose and Coverage names declining-balance as |
| 40 | the one worked case that brushes the escalate-to-custom-object line. |
| 41 | 3. Template execution / CreateWork (``tasks`` self-referential, |
| 42 | ``trigger.mode: "event"``, ``output_collection == source_collection``): |
| 43 | detected structurally (output equals source) rather than by a separate |
| 44 | flag. This is an UPDATE to the SAME row, gated by the fill-only-if-empty |
| 45 | rule (61's Events section: "must never clobber a field the record's |
| 46 | own creator already set explicitly"). 61's own worked example 3 |
| 47 | describes the CreateWork mechanism as a template-relation hop (fetch |
| 48 | the ``templates`` row a ``template_id``-shaped field points at, parse |
| 49 | its ``default_values`` JSON, fill empty fields) -- notably NOT |
| 50 | expressed through this block's ordinary ``mapping`` vocabulary, since |
| 51 | ``mapping`` is explicitly forbidden from cross-collection joins |
| 52 | (Out of Scope). This module supports BOTH: an ordinary |
| 53 | ``mapping``-driven fill (works for any CreateWork-shaped definition, |
| 54 | generic, no relation lookup) applied first, then an opportunistic |
| 55 | template-default-values hop (``_apply_template_defaults``, worked |
| 56 | example 3's exact mechanism) applied second -- both fill-only-if-empty, |
| 57 | so whichever gets there first for a given field wins and the other is |
| 58 | a no-op for that field. This is a deliberate interpretation of an |
| 59 | underspecified corner, documented here rather than by omission. |
| 60 | |
| 61 | **Crash-safety -- the honest, non-transactional sequencing (61's Storage |
| 62 | section, read literally, implemented literally):** |
| 63 | |
| 64 | 1. Compute the ENTIRE output in memory first, including the balance |
| 65 | check (exact integer cents, never float), BEFORE any write touches |
| 66 | disk. Unequal debit/credit sums -> abort, zero rows written, zero |
| 67 | risk of a half-posted journal (``BalanceCheckFailed``, raised |
| 68 | before ``_generate_new_record`` writes anything). |
| 69 | 2. Write child rows FIRST. Each child's own id is ALSO deterministic |
| 70 | (``{header_id}_line_{n}``), so a duplicate-id create from a |
| 71 | resumed partial run is a harmless, caught, skipped no-op |
| 72 | (``object_records.DuplicateRecordIdError``), never fatal. Before |
| 73 | any child, a header already stamped with this period's |
| 74 | generated_from marker (definition, source row, period) means the |
| 75 | period is generated, under whatever id: a re-keyed definition skips |
| 76 | rather than re-books, and a schema `unique` on the marker |
| 77 | (``UniqueConstraintError``) is answered the same way at the |
| 78 | header write. |
| 79 | 3. Write the header LAST, at its deterministic id |
| 80 | (``idempotency_key``). The header's EXISTENCE, not the children's, |
| 81 | is what "this period is generated" means -- the daemon's due-check |
| 82 | (``_record_exists``) queries ``output_collection`` (the header |
| 83 | collection) for that id, never the child collection. A crash |
| 84 | between the last child write and the header write leaves inert, |
| 85 | orphaned, headerless child rows -- an accepted, bounded, ACTUAL |
| 86 | failure mode (not swept under the rug): the next pass sees no |
| 87 | header, re-attempts, re-writes any still-missing children |
| 88 | (idempotent by id), and writes the header this time. This module |
| 89 | does NOT claim cross-collection atomicity, because there isn't |
| 90 | any -- see 61's Storage section for the full honest accounting of |
| 91 | why this ordering is what "detectably safe rather than silently |
| 92 | wrong" actually buys, and what it does not. |
| 93 | |
| 94 | **Scheduled due-set, recomputed from scratch every pass, same stance |
| 95 | 14-rollup-spec.md takes for its own scheduled recompute:** the daemon |
| 96 | pass does NOT trust a source row's own ``next_run``/``last_run`` (or this |
| 97 | definition's own ``last_run_at``) as the mechanism of truth. Every pass |
| 98 | recomputes which periods SHOULD exist between a row's anchor point and |
| 99 | now, and checks the deterministic header id's existence in |
| 100 | ``output_collection`` for each -- missing means generate, present means |
| 101 | skip, never an error. ``last_run_at``/a source row's own |
| 102 | ``next_run``/``last_run`` are stamped afterward purely as a freshness |
| 103 | DISPLAY, never read back as the correctness gate. |
| 104 | |
| 105 | **generated_from -- built, not left open.** 61's Open Questions flags this |
| 106 | as "arguably should just be built." When ``output_collection``'s schema |
| 107 | declares a plain ``generated_from`` field, every top-level generated |
| 108 | record (and CreateWork's in-place fill, fill-only-if-empty like every |
| 109 | other field) is stamped with a small JSON blob (``definition_id``, |
| 110 | ``source_id``, ``period_start``) -- additive, opt-in per output schema |
| 111 | (a schema that hasn't added the field simply never receives it, no |
| 112 | error), first-class provenance rather than only inferable from the |
| 113 | deterministic id's string shape. |
| 114 | """ |
| 115 | from __future__ import annotations |
| 116 | |
| 117 | import calendar |
| 118 | import json |
| 119 | import re |
| 120 | from dataclasses import dataclass |
| 121 | from datetime import date, datetime, timedelta, timezone |
| 122 | from typing import Any, Mapping |
| 123 | |
| 124 | import object_collections |
| 125 | import object_feature_flags |
| 126 | import object_records |
| 127 | import object_schemas |
| 128 | |
| 129 | MATERIALIZE_DEFINITIONS_COLLECTION = "materialize_definitions" |
| 130 | FEATURE_FLAGS_COLLECTION = "feature_flags" |
| 131 | MATERIALIZE_ENABLED_FLAG = "materialize_enabled" |
| 132 | DEFAULT_ACTOR = "daemon:materialize" |
| 133 | |
| 134 | _GRANULARITIES = frozenset({"daily", "weekly", "monthly", "quarterly", "yearly"}) |
| 135 | _TRIGGER_MODES = frozenset({"scheduled", "scheduled_fixed", "event"}) |
| 136 | _MAPPING_OP_KEYS = frozenset({"from", "from_period", "literal", "template", "if", "depreciation_amount"}) |
| 137 | _TEMPLATE_TOKEN_RE = re.compile(r"\{([a-zA-Z0-9_.]+)\}") |
| 138 | |
| 139 | # Safety valve against a malformed/huge span producing an unbounded period |
| 140 | # loop (e.g. an anchor_field decades in the past with a daily granularity). |
| 141 | # Not part of the spec; a defensive bound only. |
| 142 | _MAX_PERIODS_PER_ROW = 100_000 |
| 143 | |
| 144 | |
| 145 | class DefinitionError(ValueError): |
| 146 | """Raised when a materialize_definitions record cannot be generated as-is. |
| 147 | |
| 148 | Covers malformed JSON sub-fields, violations of 61's own doctrine (a |
| 149 | filter value that isn't a flat scalar, an unrecognized mapping op, |
| 150 | ``declining`` depreciation requested), and per-row generation problems |
| 151 | (unparseable child_source_field JSON, a missing anchor field). The |
| 152 | daemon pass (object_daemon.process_materializations) and |
| 153 | materialize_run both catch this per-definition or per-row, matching |
| 154 | object_rollups.DefinitionError's isolation posture. |
| 155 | """ |
| 156 | |
| 157 | |
| 158 | class MissingCollectionError(DefinitionError): |
| 159 | """A definition names a source/output/child collection that doesn't exist. |
| 160 | |
| 161 | Distinguished from a generic DefinitionError so the daemon can log it |
| 162 | exactly once per process (61's Degradation: "warned-once-per-process, |
| 163 | matching process_stale_transitions' _WARNED_UNKNOWN_AUTO_TRANSITION_ |
| 164 | COLLECTIONS pattern exactly") rather than re-logging every poll. |
| 165 | """ |
| 166 | |
| 167 | def __init__(self, collection: str, role: str): |
| 168 | super().__init__(f"{role} collection '{collection}' does not exist") |
| 169 | self.collection = collection |
| 170 | self.role = role |
| 171 | |
| 172 | |
| 173 | class BalanceCheckFailed(DefinitionError): |
| 174 | """A generation's computed child rows don't balance -- zero rows written. |
| 175 | |
| 176 | Raised BEFORE any write touches disk (see module docstring's |
| 177 | crash-safety section); the caller's per-row isolation logs this and |
| 178 | retries next pass, since nothing was written and the deterministic id |
| 179 | therefore never came to exist. |
| 180 | """ |
| 181 | |
| 182 | |
| 183 | @dataclass(frozen=True) |
| 184 | class Period: |
| 185 | """One computed generation period (scheduled/scheduled_fixed only). |
| 186 | |
| 187 | ``index``/``total`` are the 1-based period number and the definition's |
| 188 | total period cap -- present only for ``scheduled_fixed`` (depreciation's |
| 189 | "which month is this, out of how many"), None for ``scheduled``. |
| 190 | """ |
| 191 | |
| 192 | start: date |
| 193 | end: date |
| 194 | label: str |
| 195 | index: int | None |
| 196 | total: int | None |
| 197 | |
| 198 | |
| 199 | @dataclass(frozen=True) |
| 200 | class MaterializeConfig: |
| 201 | definition_id: str |
| 202 | name: str |
| 203 | source_collection: str |
| 204 | source_filter: dict[str, Any] |
| 205 | trigger_mode: str # "scheduled" | "scheduled_fixed" | "event" |
| 206 | trigger_interval_seconds: int | None |
| 207 | # scheduled mode |
| 208 | anchor_field: str | None |
| 209 | frequency_field: str | None # names a FIELD on the source row (e.g. "frequency") |
| 210 | # scheduled_fixed mode |
| 211 | start_field: str | None |
| 212 | granularity: str | None # a literal fixed granularity (e.g. "monthly") |
| 213 | periods_field: str | None # names a FIELD on the source row (e.g. "useful_life_months") |
| 214 | # output |
| 215 | output_collection: str |
| 216 | child_collection: str | None |
| 217 | child_source_field: str | None |
| 218 | child_link_field: str | None |
| 219 | idempotency_key: str |
| 220 | mapping: dict[str, Any] |
| 221 | balance_check: dict[str, str] | None |
| 222 | debit_account_id: str | None |
| 223 | credit_account_id: str | None |
| 224 | synthesized_amount_entry: dict[str, Any] | None |
| 225 | actor: str |
| 226 | enabled: bool |
| 227 | block: bool |
| 228 | stamp_generated_from: bool |
| 229 | |
| 230 | |
| 231 | # --- Feature flag / due gates ------------------------------------------------- |
| 232 | |
| 233 | def materialize_pass_enabled(*, base_dir: Any) -> bool: |
| 234 | """Block-wide kill switch, ``<block>_enabled`` convention, mirroring |
| 235 | object_rollups.rollup_pass_enabled exactly (same defaults, same |
| 236 | reasoning): default ON, a missing/unreadable feature_flags collection |
| 237 | or a blank value both resolve to "on"; only an explicit off/false/0/no |
| 238 | value turns the pass off. Unlike 14's posture (stale-but-valid reads |
| 239 | keep serving), 61's Degradation is explicit that here "off means off, |
| 240 | full stop, for BOTH the scheduled and manual paths" -- callers (the |
| 241 | daemon pass, materialize_run, materialize_seed's EVENT handler) are |
| 242 | each responsible for checking this before doing anything, since there |
| 243 | is no "serve what's on disk" fallback for a write-side block. |
| 244 | """ |
| 245 | return object_feature_flags.kill_switch_on(MATERIALIZE_ENABLED_FLAG, base_dir=base_dir) |
| 246 | |
| 247 | |
| 248 | def is_definition_enabled(record: Mapping[str, str]) -> bool: |
| 249 | """Per-definition pause -- independent of the block-wide flag. Blank |
| 250 | defaults to enabled, matching object_rollups.is_definition_enabled. |
| 251 | """ |
| 252 | return _truthy(record.get("enabled"), default=True) |
| 253 | |
| 254 | |
| 255 | def is_definition_blocked(record: Mapping[str, str]) -> bool: |
| 256 | """The harder stop (61's Degradation): ``block: true`` refuses even |
| 257 | ``materialize_run``'s manual path with a distinct error, unlike |
| 258 | ``enabled: false`` (pause, resume later without thinking). |
| 259 | """ |
| 260 | return _truthy(record.get("block"), default=False) |
| 261 | |
| 262 | |
| 263 | def is_definition_due(record: Mapping[str, str], *, now: datetime | None = None) -> bool: |
| 264 | """SCHEDULED/SCHEDULED_FIXED due gate: ``last_run_at`` + |
| 265 | ``trigger.interval_seconds``, both read straight off the raw record -- |
| 266 | mirrors object_rollups.is_definition_due's structure exactly. A |
| 267 | never-run definition (``last_run_at`` blank) is always due. This gate |
| 268 | only decides whether the daemon PASS attempts a definition this poll; |
| 269 | it is not the correctness mechanism (that's the deterministic header |
| 270 | id, see module docstring) -- a due-but-already-generated period is |
| 271 | simply reported as skipped, not an error. |
| 272 | """ |
| 273 | now = now or datetime.now(timezone.utc) |
| 274 | last_run_raw = (record.get("last_run_at") or "").strip() |
| 275 | if not last_run_raw: |
| 276 | return True |
| 277 | trigger = _json_field(record, "trigger", None, definition_id=record.get("id") or "<unknown>") |
| 278 | interval = _positive_int(trigger.get("interval_seconds")) if isinstance(trigger, dict) else None |
| 279 | if interval is None: |
| 280 | return True |
| 281 | last_run = _parse_iso(last_run_raw) |
| 282 | if last_run is None: |
| 283 | return True |
| 284 | return (now - last_run).total_seconds() >= interval |
| 285 | |
| 286 | |
| 287 | # --- Definition parsing ------------------------------------------------- |
| 288 | |
| 289 | def parse_definition( |
| 290 | record: Mapping[str, str], *, base_dir: Any, roots: Any = None |
| 291 | ) -> MaterializeConfig: |
| 292 | """Validate and normalize one ``materialize_definitions`` row. |
| 293 | |
| 294 | Raises ``DefinitionError``/``MissingCollectionError`` for anything |
| 295 | malformed or referencing a collection that doesn't exist yet -- the |
| 296 | daemon (object_daemon.process_materializations) and materialize_run |
| 297 | both isolate this per-definition, never letting one bad definition |
| 298 | stop any other (61's Events/Degradation). |
| 299 | """ |
| 300 | definition_id = (record.get("id") or "").strip() |
| 301 | if not definition_id: |
| 302 | raise DefinitionError("materialize definition is missing an id") |
| 303 | |
| 304 | name = (record.get("name") or "").strip() or definition_id |
| 305 | |
| 306 | source_collection = (record.get("source_collection") or "").strip() |
| 307 | if not source_collection or not object_collections.validate_collection_name(source_collection): |
| 308 | raise DefinitionError(f"{definition_id}: source_collection is required and must be a valid collection name") |
| 309 | try: |
| 310 | object_schemas.get_schema(source_collection, base_dir=base_dir, roots=roots) |
| 311 | except object_schemas.SchemaNotFoundError: |
| 312 | raise MissingCollectionError(source_collection, "source") from None |
| 313 | |
| 314 | source_filter = _parse_filter(record, definition_id=definition_id) |
| 315 | |
| 316 | trigger = _json_field(record, "trigger", None, definition_id=definition_id) |
| 317 | if not isinstance(trigger, dict) or not trigger: |
| 318 | raise DefinitionError(f"{definition_id}: trigger is required and must be a JSON object") |
| 319 | trigger_mode = str(trigger.get("mode") or "").strip() |
| 320 | if trigger_mode not in _TRIGGER_MODES: |
| 321 | raise DefinitionError(f"{definition_id}: trigger.mode must be one of {sorted(_TRIGGER_MODES)}") |
| 322 | |
| 323 | trigger_interval_seconds: int | None = None |
| 324 | anchor_field = frequency_field = start_field = granularity = periods_field = None |
| 325 | |
| 326 | if trigger_mode == "scheduled": |
| 327 | trigger_interval_seconds = _positive_int(trigger.get("interval_seconds")) |
| 328 | if trigger_interval_seconds is None: |
| 329 | raise DefinitionError(f"{definition_id}: trigger.interval_seconds is required and must be a positive integer") |
| 330 | frequency_field = str(trigger.get("period_field") or "").strip() |
| 331 | if not frequency_field: |
| 332 | raise DefinitionError( |
| 333 | f"{definition_id}: trigger.period_field (the source row field naming its own " |
| 334 | "frequency, e.g. \"frequency\") is required for scheduled mode" |
| 335 | ) |
| 336 | anchor_field = str(trigger.get("anchor_field") or "").strip() |
| 337 | if not anchor_field: |
| 338 | raise DefinitionError(f"{definition_id}: trigger.anchor_field is required for scheduled mode") |
| 339 | elif trigger_mode == "scheduled_fixed": |
| 340 | trigger_interval_seconds = _positive_int(trigger.get("interval_seconds")) |
| 341 | if trigger_interval_seconds is None: |
| 342 | raise DefinitionError(f"{definition_id}: trigger.interval_seconds is required and must be a positive integer") |
| 343 | granularity = str(trigger.get("period_field") or "").strip().lower() |
| 344 | if granularity not in _GRANULARITIES: |
| 345 | raise DefinitionError( |
| 346 | f"{definition_id}: trigger.period_field must be a fixed granularity, one of " |
| 347 | f"{sorted(_GRANULARITIES)}, for scheduled_fixed mode" |
| 348 | ) |
| 349 | start_field = str(trigger.get("start_field") or "").strip() |
| 350 | if not start_field: |
| 351 | raise DefinitionError(f"{definition_id}: trigger.start_field is required for scheduled_fixed mode") |
| 352 | end_condition = trigger.get("end_condition") |
| 353 | if not isinstance(end_condition, dict): |
| 354 | raise DefinitionError(f"{definition_id}: trigger.end_condition is required for scheduled_fixed mode") |
| 355 | periods_field = str(end_condition.get("periods_field") or "").strip() |
| 356 | if not periods_field: |
| 357 | raise DefinitionError(f"{definition_id}: trigger.end_condition.periods_field is required for scheduled_fixed mode") |
| 358 | else: # event |
| 359 | on = str(trigger.get("on") or "").strip() |
| 360 | if on != "record.created": |
| 361 | raise DefinitionError(f"{definition_id}: trigger.on must be 'record.created' for event mode") |
| 362 | |
| 363 | output_collection = (record.get("output_collection") or "").strip() |
| 364 | if not output_collection or not object_collections.validate_collection_name(output_collection): |
| 365 | raise DefinitionError(f"{definition_id}: output_collection is required and must be a valid collection name") |
| 366 | try: |
| 367 | object_schemas.get_schema(output_collection, base_dir=base_dir, roots=roots) |
| 368 | except object_schemas.SchemaNotFoundError: |
| 369 | raise MissingCollectionError(output_collection, "output") from None |
| 370 | |
| 371 | child_collection = (record.get("child_collection") or "").strip() or None |
| 372 | child_source_field = (record.get("child_source_field") or "").strip() or None |
| 373 | child_link_field = (record.get("child_link_field") or "").strip() or None |
| 374 | if child_collection: |
| 375 | if not object_collections.validate_collection_name(child_collection): |
| 376 | raise DefinitionError(f"{definition_id}: child_collection must be a valid collection name") |
| 377 | try: |
| 378 | object_schemas.get_schema(child_collection, base_dir=base_dir, roots=roots) |
| 379 | except object_schemas.SchemaNotFoundError: |
| 380 | raise MissingCollectionError(child_collection, "child") from None |
| 381 | if not child_link_field: |
| 382 | raise DefinitionError(f"{definition_id}: child_link_field is required when child_collection is set") |
| 383 | |
| 384 | idempotency_key = (record.get("idempotency_key") or "").strip() |
| 385 | if not idempotency_key: |
| 386 | raise DefinitionError(f"{definition_id}: idempotency_key is required") |
| 387 | |
| 388 | mapping_raw = _json_field(record, "mapping", {}, definition_id=definition_id) |
| 389 | if mapping_raw is None: |
| 390 | mapping_raw = {} |
| 391 | if not isinstance(mapping_raw, dict): |
| 392 | raise DefinitionError(f"{definition_id}: mapping must be a JSON object") |
| 393 | mapping = dict(mapping_raw) |
| 394 | for field_name, entry in mapping.items(): |
| 395 | _validate_mapping_entry(field_name, entry, definition_id=definition_id) |
| 396 | |
| 397 | balance_check_raw = _json_field(record, "balance_check", None, definition_id=definition_id) |
| 398 | balance_check: dict[str, str] | None = None |
| 399 | if balance_check_raw is not None: |
| 400 | if not isinstance(balance_check_raw, dict): |
| 401 | raise DefinitionError(f"{definition_id}: balance_check must be a JSON object") |
| 402 | debit_field = str(balance_check_raw.get("debit_field") or "").strip() |
| 403 | credit_field = str(balance_check_raw.get("credit_field") or "").strip() |
| 404 | if not debit_field or not credit_field: |
| 405 | raise DefinitionError(f"{definition_id}: balance_check requires debit_field and credit_field") |
| 406 | if not child_collection: |
| 407 | raise DefinitionError(f"{definition_id}: balance_check requires child_collection") |
| 408 | balance_check = {"debit_field": debit_field, "credit_field": credit_field} |
| 409 | |
| 410 | debit_account_id = (record.get("debit_account_id") or "").strip() or None |
| 411 | credit_account_id = (record.get("credit_account_id") or "").strip() or None |
| 412 | |
| 413 | synthesized_amount_entry: dict[str, Any] | None = None |
| 414 | if child_collection and not child_source_field: |
| 415 | # Absence of child_source_field alongside a present child_collection |
| 416 | # is the synthesized depreciation-lines shape's own signal -- see |
| 417 | # module docstring's worked example 2 discussion. |
| 418 | amount_entry = mapping.pop("amount", None) |
| 419 | if not isinstance(amount_entry, dict) or "depreciation_amount" not in amount_entry: |
| 420 | raise DefinitionError( |
| 421 | f"{definition_id}: a child_collection with no child_source_field is the " |
| 422 | "synthesized depreciation-lines shape and requires " |
| 423 | "mapping.amount = {'depreciation_amount': {...}}" |
| 424 | ) |
| 425 | if not debit_account_id or not credit_account_id: |
| 426 | raise DefinitionError( |
| 427 | f"{definition_id}: the synthesized depreciation-lines shape requires " |
| 428 | "debit_account_id and credit_account_id" |
| 429 | ) |
| 430 | if not balance_check: |
| 431 | raise DefinitionError( |
| 432 | f"{definition_id}: the synthesized depreciation-lines shape requires " |
| 433 | "balance_check (its debit_field/credit_field name the two generated " |
| 434 | "lines' amount fields)" |
| 435 | ) |
| 436 | synthesized_amount_entry = amount_entry |
| 437 | |
| 438 | actor = (record.get("actor") or "").strip() or DEFAULT_ACTOR |
| 439 | enabled = _truthy(record.get("enabled"), default=True) |
| 440 | block = _truthy(record.get("block"), default=False) |
| 441 | |
| 442 | stamp_generated_from = _schema_has_field(output_collection, "generated_from", base_dir=base_dir, roots=roots) |
| 443 | |
| 444 | return MaterializeConfig( |
| 445 | definition_id=definition_id, |
| 446 | name=name, |
| 447 | source_collection=source_collection, |
| 448 | source_filter=source_filter, |
| 449 | trigger_mode=trigger_mode, |
| 450 | trigger_interval_seconds=trigger_interval_seconds, |
| 451 | anchor_field=anchor_field, |
| 452 | frequency_field=frequency_field, |
| 453 | start_field=start_field, |
| 454 | granularity=granularity, |
| 455 | periods_field=periods_field, |
| 456 | output_collection=output_collection, |
| 457 | child_collection=child_collection, |
| 458 | child_source_field=child_source_field, |
| 459 | child_link_field=child_link_field, |
| 460 | idempotency_key=idempotency_key, |
| 461 | mapping=mapping, |
| 462 | balance_check=balance_check, |
| 463 | debit_account_id=debit_account_id, |
| 464 | credit_account_id=credit_account_id, |
| 465 | synthesized_amount_entry=synthesized_amount_entry, |
| 466 | actor=actor, |
| 467 | enabled=enabled, |
| 468 | block=block, |
| 469 | stamp_generated_from=stamp_generated_from, |
| 470 | ) |
| 471 | |
| 472 | |
| 473 | def _validate_mapping_entry(field_name: str, entry: Any, *, definition_id: str) -> None: |
| 474 | if not isinstance(entry, dict): |
| 475 | raise DefinitionError(f"{definition_id}: mapping.{field_name} must be a JSON object") |
| 476 | |
| 477 | if "if" in entry: |
| 478 | cond = entry.get("if") |
| 479 | if not isinstance(cond, dict) or not isinstance(cond.get("source_field"), str) or not cond.get("source_field"): |
| 480 | raise DefinitionError(f"{definition_id}: mapping.{field_name}.if requires a source_field") |
| 481 | if "equals" not in cond: |
| 482 | raise DefinitionError(f"{definition_id}: mapping.{field_name}.if requires 'equals'") |
| 483 | if "then" not in entry or "else" not in entry: |
| 484 | raise DefinitionError(f"{definition_id}: mapping.{field_name} with 'if' requires 'then' and 'else'") |
| 485 | return |
| 486 | |
| 487 | if "depreciation_amount" in entry: |
| 488 | op = entry["depreciation_amount"] |
| 489 | if not isinstance(op, dict): |
| 490 | raise DefinitionError(f"{definition_id}: mapping.{field_name}.depreciation_amount must be a JSON object") |
| 491 | method = str(op.get("method") or "").strip() |
| 492 | if method == "declining": |
| 493 | raise DefinitionError( |
| 494 | f"{definition_id}: mapping.{field_name} requests depreciation method 'declining', " |
| 495 | "which is out of scope for v1 (straight_line only) -- see " |
| 496 | "plan/vocabulary/61-materialize-spec.md's Open Questions" |
| 497 | ) |
| 498 | if method != "straight_line": |
| 499 | raise DefinitionError(f"{definition_id}: mapping.{field_name}.depreciation_amount.method must be 'straight_line'") |
| 500 | for key in ("cost_field", "salvage_field", "life_field"): |
| 501 | value = op.get(key) |
| 502 | if not isinstance(value, str) or not value: |
| 503 | raise DefinitionError(f"{definition_id}: mapping.{field_name}.depreciation_amount.{key} is required") |
| 504 | return |
| 505 | |
| 506 | if "from" in entry: |
| 507 | if not isinstance(entry["from"], str) or not entry["from"]: |
| 508 | raise DefinitionError(f"{definition_id}: mapping.{field_name}.from must name a source field") |
| 509 | return |
| 510 | |
| 511 | if "from_period" in entry: |
| 512 | if entry["from_period"] not in ("period_start", "period_end", "period_label"): |
| 513 | raise DefinitionError( |
| 514 | f"{definition_id}: mapping.{field_name}.from_period must be one of " |
| 515 | "period_start/period_end/period_label" |
| 516 | ) |
| 517 | return |
| 518 | |
| 519 | if "literal" in entry: |
| 520 | return |
| 521 | |
| 522 | if "template" in entry: |
| 523 | if not isinstance(entry["template"], str): |
| 524 | raise DefinitionError(f"{definition_id}: mapping.{field_name}.template must be a string") |
| 525 | return |
| 526 | |
| 527 | raise DefinitionError( |
| 528 | f"{definition_id}: mapping.{field_name} must use one of from/from_period/literal/" |
| 529 | "template/if/depreciation_amount" |
| 530 | ) |
| 531 | |
| 532 | |
| 533 | def _parse_filter(record: Mapping[str, str], *, definition_id: str) -> dict[str, Any]: |
| 534 | raw = _json_field(record, "source_filter", {}, definition_id=definition_id) |
| 535 | if raw is None: |
| 536 | return {} |
| 537 | if not isinstance(raw, dict): |
| 538 | raise DefinitionError(f"{definition_id}: source_filter must be a flat JSON object") |
| 539 | normalized: dict[str, Any] = {} |
| 540 | for key, value in raw.items(): |
| 541 | if isinstance(value, (dict, list)): |
| 542 | raise DefinitionError( |
| 543 | f"{definition_id}: source_filter.{key} must be a scalar -- materialize filters are " |
| 544 | "flat equality only, ANDed, same as 14-rollup-spec.md's filter language" |
| 545 | ) |
| 546 | if value is None: |
| 547 | raise DefinitionError(f"{definition_id}: source_filter.{key} must not be null") |
| 548 | if isinstance(value, bool): |
| 549 | value = "true" if value else "false" |
| 550 | normalized[key] = value |
| 551 | return normalized |
| 552 | |
| 553 | |
| 554 | def _schema_has_field(collection: str, field_name: str, *, base_dir: Any, roots: Any = None) -> bool: |
| 555 | try: |
| 556 | schema = object_schemas.get_schema(collection, base_dir=base_dir, roots=roots) |
| 557 | except object_schemas.SchemaNotFoundError: |
| 558 | return False |
| 559 | return any(field.get("name") == field_name for field in schema.get("fields", [])) |
| 560 | |
| 561 | |
| 562 | # --- Period computation ------------------------------------------------- |
| 563 | |
| 564 | def _compute_scheduled_periods( |
| 565 | source_row: Mapping[str, str], config: MaterializeConfig, *, now: date |
| 566 | ) -> list[Period]: |
| 567 | granularity = str(source_row.get(config.frequency_field) or "").strip().lower() |
| 568 | if granularity not in _GRANULARITIES: |
| 569 | raise DefinitionError( |
| 570 | f"source row has an invalid or missing '{config.frequency_field}' " |
| 571 | f"(must be one of {sorted(_GRANULARITIES)}); got {granularity!r}" |
| 572 | ) |
| 573 | anchor_raw = source_row.get(config.anchor_field) or "" |
| 574 | origin = _parse_date(anchor_raw) |
| 575 | if origin is None: |
| 576 | origin = _parse_date(source_row.get("created_at") or "") |
| 577 | if origin is None: |
| 578 | raise DefinitionError( |
| 579 | f"source row has no usable '{config.anchor_field}' (nor created_at) to anchor periods" |
| 580 | ) |
| 581 | return _step_periods(origin, granularity, now=now, cap=None) |
| 582 | |
| 583 | |
| 584 | def _compute_scheduled_fixed_periods( |
| 585 | source_row: Mapping[str, str], config: MaterializeConfig, *, now: date |
| 586 | ) -> list[Period]: |
| 587 | origin = _parse_date(source_row.get(config.start_field) or "") |
| 588 | if origin is None: |
| 589 | raise DefinitionError(f"source row has no usable '{config.start_field}' to anchor periods") |
| 590 | cap = _positive_int(source_row.get(config.periods_field)) |
| 591 | if cap is None: |
| 592 | raise DefinitionError(f"source row's '{config.periods_field}' must be a positive integer") |
| 593 | return _step_periods(origin, config.granularity, now=now, cap=cap) |
| 594 | |
| 595 | |
| 596 | def _step_periods(origin: date, granularity: str, *, now: date, cap: int | None) -> list[Period]: |
| 597 | periods: list[Period] = [] |
| 598 | cursor = origin |
| 599 | index = 0 |
| 600 | guard = 0 |
| 601 | while cursor <= now: |
| 602 | index += 1 |
| 603 | if cap is not None and index > cap: |
| 604 | break |
| 605 | period_end = _advance_date(cursor, granularity, 1) |
| 606 | periods.append( |
| 607 | Period( |
| 608 | start=cursor, |
| 609 | end=period_end, |
| 610 | label=_period_label(cursor, granularity), |
| 611 | index=index if cap is not None else None, |
| 612 | total=cap, |
| 613 | ) |
| 614 | ) |
| 615 | cursor = period_end |
| 616 | guard += 1 |
| 617 | if guard >= _MAX_PERIODS_PER_ROW: |
| 618 | break |
| 619 | return periods |
| 620 | |
| 621 | |
| 622 | def _due_periods_for_row( |
| 623 | config: MaterializeConfig, source_row: Mapping[str, str], *, now: date |
| 624 | ) -> list[Period | None]: |
| 625 | if config.trigger_mode == "event": |
| 626 | return [None] |
| 627 | if config.trigger_mode == "scheduled": |
| 628 | return _compute_scheduled_periods(source_row, config, now=now) |
| 629 | if config.trigger_mode == "scheduled_fixed": |
| 630 | return _compute_scheduled_fixed_periods(source_row, config, now=now) |
| 631 | raise DefinitionError(f"unknown trigger mode: {config.trigger_mode}") # pragma: no cover -- pre-validated |
| 632 | |
| 633 | |
| 634 | def _advance_date(d: date, granularity: str, steps: int = 1) -> date: |
| 635 | if granularity == "daily": |
| 636 | return d + timedelta(days=steps) |
| 637 | if granularity == "weekly": |
| 638 | return d + timedelta(weeks=steps) |
| 639 | if granularity == "monthly": |
| 640 | return _add_months(d, steps) |
| 641 | if granularity == "quarterly": |
| 642 | return _add_months(d, steps * 3) |
| 643 | if granularity == "yearly": |
| 644 | return _add_months(d, steps * 12) |
| 645 | raise DefinitionError(f"unknown granularity: {granularity}") # pragma: no cover -- pre-validated |
| 646 | |
| 647 | |
| 648 | def _add_months(d: date, months: int) -> date: |
| 649 | total = d.month - 1 + months |
| 650 | year = d.year + total // 12 |
| 651 | month = total % 12 + 1 |
| 652 | day = min(d.day, calendar.monthrange(year, month)[1]) |
| 653 | return date(year, month, day) |
| 654 | |
| 655 | |
| 656 | def _period_label(period_start: date, granularity: str) -> str: |
| 657 | if granularity == "daily": |
| 658 | return period_start.isoformat() |
| 659 | if granularity == "weekly": |
| 660 | iso_year, iso_week, _ = period_start.isocalendar() |
| 661 | return f"{iso_year}-W{iso_week:02d}" |
| 662 | if granularity == "monthly": |
| 663 | return f"{period_start.year:04d}-{period_start.month:02d}" |
| 664 | if granularity == "quarterly": |
| 665 | quarter = (period_start.month - 1) // 3 + 1 |
| 666 | return f"{period_start.year}-Q{quarter}" |
| 667 | if granularity == "yearly": |
| 668 | return str(period_start.year) |
| 669 | raise DefinitionError(f"unknown granularity: {granularity}") # pragma: no cover -- pre-validated |
| 670 | |
| 671 | |
| 672 | def _parse_date(value: Any) -> date | None: |
| 673 | text = (value or "").strip() if isinstance(value, str) else "" |
| 674 | if not text: |
| 675 | return None |
| 676 | try: |
| 677 | if "T" in text or " " in text: |
| 678 | return datetime.fromisoformat(text.replace("Z", "+00:00")).date() |
| 679 | return date.fromisoformat(text) |
| 680 | except ValueError: |
| 681 | return None |
| 682 | |
| 683 | |
| 684 | # --- Mapping vocabulary ------------------------------------------------- |
| 685 | |
| 686 | def _eval_entry( |
| 687 | field_name: str, entry: Mapping[str, Any], *, source_row: Mapping[str, str], |
| 688 | period: Period | None, definition_id: str, |
| 689 | ) -> str: |
| 690 | if "from" in entry: |
| 691 | return _stringify(source_row.get(entry["from"], "")) |
| 692 | |
| 693 | if "from_period" in entry: |
| 694 | if period is None: |
| 695 | raise DefinitionError( |
| 696 | f"{definition_id}: mapping.{field_name} uses from_period but this generation " |
| 697 | "has no period (event/manual single-shot/CreateWork)" |
| 698 | ) |
| 699 | key = entry["from_period"] |
| 700 | if key == "period_start": |
| 701 | return period.start.isoformat() |
| 702 | if key == "period_end": |
| 703 | return period.end.isoformat() |
| 704 | if key == "period_label": |
| 705 | return period.label |
| 706 | raise DefinitionError( # pragma: no cover -- pre-validated |
| 707 | f"{definition_id}: mapping.{field_name}.from_period must be period_start/period_end/period_label" |
| 708 | ) |
| 709 | |
| 710 | if "literal" in entry: |
| 711 | return _stringify(entry["literal"]) |
| 712 | |
| 713 | if "template" in entry: |
| 714 | return _render_template( |
| 715 | entry["template"], source_row=source_row, period=period, |
| 716 | definition_id=definition_id, field_name=field_name, |
| 717 | ) |
| 718 | |
| 719 | if "if" in entry: |
| 720 | cond = entry["if"] |
| 721 | actual = source_row.get(cond["source_field"]) |
| 722 | matches = _loose_equals(actual, cond["equals"]) |
| 723 | return _stringify(entry["then"] if matches else entry["else"]) |
| 724 | |
| 725 | if "depreciation_amount" in entry: |
| 726 | return _eval_depreciation( |
| 727 | entry["depreciation_amount"], source_row, period, |
| 728 | definition_id=definition_id, field_name=field_name, |
| 729 | ) |
| 730 | |
| 731 | raise DefinitionError(f"{definition_id}: mapping.{field_name} uses an unrecognized op") # pragma: no cover |
| 732 | |
| 733 | |
| 734 | def _loose_equals(actual: Any, expected: Any) -> bool: |
| 735 | if isinstance(expected, bool): |
| 736 | expected_str = "true" if expected else "false" |
| 737 | else: |
| 738 | expected_str = str(expected) |
| 739 | return str(actual if actual is not None else "") == expected_str |
| 740 | |
| 741 | |
| 742 | def _render_template( |
| 743 | template: str, *, source_row: Mapping[str, str], period: Period | None, |
| 744 | definition_id: str, field_name: str, |
| 745 | ) -> str: |
| 746 | def replace(match: re.Match[str]) -> str: |
| 747 | token = match.group(1) |
| 748 | if token == "period_label": |
| 749 | if period is None: |
| 750 | raise DefinitionError( |
| 751 | f"{definition_id}: mapping.{field_name} template uses {{period_label}} but " |
| 752 | "this generation has no period" |
| 753 | ) |
| 754 | return period.label |
| 755 | if token.startswith("source."): |
| 756 | field = token[len("source."):] |
| 757 | return _stringify(source_row.get(field, "")) |
| 758 | raise DefinitionError( |
| 759 | f"{definition_id}: mapping.{field_name} template references unknown placeholder '{{{token}}}'" |
| 760 | ) |
| 761 | |
| 762 | return _TEMPLATE_TOKEN_RE.sub(replace, template) |
| 763 | |
| 764 | |
| 765 | def _eval_depreciation( |
| 766 | op: Mapping[str, Any], source_row: Mapping[str, str], period: Period | None, |
| 767 | *, definition_id: str, field_name: str, |
| 768 | ) -> str: |
| 769 | if period is None or period.total is None or period.index is None: |
| 770 | raise DefinitionError( |
| 771 | f"{definition_id}: mapping.{field_name} uses depreciation_amount, which requires a " |
| 772 | "scheduled_fixed trigger with an end_condition.periods_field cap" |
| 773 | ) |
| 774 | monthly, remainder = _straight_line_split(op, source_row, definition_id=definition_id, field_name=field_name) |
| 775 | if period.index == period.total: |
| 776 | return str(monthly + remainder) |
| 777 | return str(monthly) |
| 778 | |
| 779 | |
| 780 | def _straight_line_split( |
| 781 | op: Mapping[str, Any], source_row: Mapping[str, str], *, definition_id: str, field_name: str, |
| 782 | ) -> tuple[int, int]: |
| 783 | cost = _to_cents(source_row.get(op["cost_field"])) |
| 784 | salvage = _to_cents(source_row.get(op["salvage_field"])) |
| 785 | life = _positive_int(source_row.get(op["life_field"])) |
| 786 | if life is None: |
| 787 | raise DefinitionError( |
| 788 | f"{definition_id}: mapping.{field_name}.depreciation_amount.life_field must be a " |
| 789 | "positive integer on the source row" |
| 790 | ) |
| 791 | depreciable = cost - salvage |
| 792 | monthly = depreciable // life |
| 793 | remainder = depreciable - (monthly * life) |
| 794 | return monthly, remainder |
| 795 | |
| 796 | |
| 797 | # --- Generation orchestration ------------------------------------------------- |
| 798 | |
| 799 | def generate_definition( |
| 800 | record: Mapping[str, str], *, base_dir: Any, roots: Any = None, now: datetime | None = None, |
| 801 | ) -> dict[str, Any]: |
| 802 | """Parse ``record`` and run its full due-set generation. |
| 803 | |
| 804 | The SAME function the daemon's scheduled pass and ``materialize_run``'s |
| 805 | manual path both call (61's Events: "the exact same idempotent, |
| 806 | per-source-row function") -- for scheduled/scheduled_fixed this |
| 807 | iterates every matching source row and every due period; for event |
| 808 | mode (when called manually, since the daemon's scheduled pass never |
| 809 | calls this on an event-mode definition -- see object_daemon. |
| 810 | process_materializations) this iterates every matching source row |
| 811 | once each, no period. Returns {"definition_id", "checked", "generated", |
| 812 | "skipped_already_generated", "errors": [{"source_id", "period_start", |
| 813 | "error"}, ...]}. Raises DefinitionError/MissingCollectionError for a |
| 814 | malformed definition -- the caller isolates that per-definition; every |
| 815 | per-row/per-period failure INSIDE a valid definition is instead |
| 816 | captured in the returned "errors" list, never raised, so one bad row |
| 817 | never stops any other (61's two-level isolation, mirroring |
| 818 | process_stale_transitions). |
| 819 | """ |
| 820 | config = parse_definition(record, base_dir=base_dir, roots=roots) |
| 821 | return generate_config(config, base_dir=base_dir, roots=roots, now=now) |
| 822 | |
| 823 | |
| 824 | def generate_config( |
| 825 | config: MaterializeConfig, *, base_dir: Any, roots: Any = None, now: datetime | None = None, |
| 826 | ) -> dict[str, Any]: |
| 827 | now_dt = now or datetime.now(timezone.utc) |
| 828 | now_date = now_dt.date() |
| 829 | |
| 830 | source_rows = object_records.read_collection_records(config.source_collection, base_dir=base_dir, roots=roots) |
| 831 | if config.source_filter: |
| 832 | source_rows = object_records.filter_records(source_rows, config.source_filter) |
| 833 | |
| 834 | checked = generated = skipped = 0 |
| 835 | errors: list[dict[str, Any]] = [] |
| 836 | |
| 837 | for row in source_rows: |
| 838 | source_id = row.get("id") or "<unknown>" |
| 839 | try: |
| 840 | periods = _due_periods_for_row(config, row, now=now_date) |
| 841 | except Exception as exc: |
| 842 | errors.append({"source_id": source_id, "period_start": None, "error": str(exc)}) |
| 843 | continue |
| 844 | |
| 845 | for period in periods: |
| 846 | checked += 1 |
| 847 | try: |
| 848 | result = generate_one(config, row, period, base_dir=base_dir, roots=roots) |
| 849 | except Exception as exc: |
| 850 | errors.append({ |
| 851 | "source_id": source_id, |
| 852 | "period_start": period.start.isoformat() if period is not None else None, |
| 853 | "error": str(exc), |
| 854 | }) |
| 855 | continue |
| 856 | |
| 857 | if result["status"] == "generated": |
| 858 | generated += 1 |
| 859 | elif result["status"] == "skipped_already_generated": |
| 860 | skipped += 1 |
| 861 | else: # pragma: no cover -- defensive, generate_one only returns these two |
| 862 | errors.append({ |
| 863 | "source_id": source_id, |
| 864 | "period_start": period.start.isoformat() if period is not None else None, |
| 865 | "error": f"unexpected status: {result['status']}", |
| 866 | }) |
| 867 | |
| 868 | return { |
| 869 | "definition_id": config.definition_id, |
| 870 | "checked": checked, |
| 871 | "generated": generated, |
| 872 | "skipped_already_generated": skipped, |
| 873 | "errors": errors, |
| 874 | } |
| 875 | |
| 876 | |
| 877 | def generate_one( |
| 878 | config: MaterializeConfig, source_row: Mapping[str, str], period: Period | None, |
| 879 | *, base_dir: Any, roots: Any = None, |
| 880 | ) -> dict[str, Any]: |
| 881 | """Generate (or confirm-already-generated) ONE (source row, period) pair. |
| 882 | |
| 883 | Branches structurally on ``output_collection == source_collection`` |
| 884 | (CreateWork: an in-place update, no new record) vs. every other shape |
| 885 | (a new header record, optionally with children) -- see module |
| 886 | docstring. |
| 887 | """ |
| 888 | if config.output_collection == config.source_collection: |
| 889 | return _generate_creatework(config, source_row, base_dir=base_dir, roots=roots) |
| 890 | return _generate_new_record(config, source_row, period, base_dir=base_dir, roots=roots) |
| 891 | |
| 892 | |
| 893 | def _generate_new_record( |
| 894 | config: MaterializeConfig, source_row: Mapping[str, str], period: Period | None, |
| 895 | *, base_dir: Any, roots: Any = None, |
| 896 | ) -> dict[str, Any]: |
| 897 | header_id = _render_idempotency_key(config, source_row=source_row, period=period) |
| 898 | |
| 899 | # The ONLY due-check: does the header already exist? (module docstring) |
| 900 | if _record_exists(config.output_collection, header_id, base_dir=base_dir, roots=roots): |
| 901 | return {"status": "skipped_already_generated", "header_id": header_id} |
| 902 | |
| 903 | header_fields: dict[str, Any] = {"id": header_id} |
| 904 | for field_name, entry in config.mapping.items(): |
| 905 | header_fields[field_name] = _eval_entry( |
| 906 | field_name, entry, source_row=source_row, period=period, definition_id=config.definition_id, |
| 907 | ) |
| 908 | if config.stamp_generated_from: |
| 909 | header_fields["generated_from"] = _generated_from_value(config, source_row=source_row, period=period) |
| 910 | # The marker names (definition, source row, period), so a header |
| 911 | # that already carries it IS this generation, under whatever id it |
| 912 | # was written (the id moves only when idempotency_key is edited). |
| 913 | # Asked before any child is written, so a re-keyed definition does |
| 914 | # not leave a period's lines under an id no header will ever have. |
| 915 | holder = _marker_holder(config.output_collection, header_fields["generated_from"], |
| 916 | base_dir=base_dir, roots=roots) |
| 917 | if holder is not None: |
| 918 | return {"status": "skipped_already_generated", "header_id": holder} |
| 919 | |
| 920 | child_rows = _build_child_rows(config, source_row=source_row, header_id=header_id, period=period) |
| 921 | |
| 922 | if config.balance_check: |
| 923 | debit_total, credit_total = _sum_balance(config, child_rows) |
| 924 | if debit_total != credit_total: |
| 925 | raise BalanceCheckFailed( |
| 926 | f"{config.definition_id}: unbalanced generation for source " |
| 927 | f"{source_row.get('id')} period {period.start.isoformat() if period else '-'}: " |
| 928 | f"debits={debit_total} credits={credit_total} cents -- aborted before any write" |
| 929 | ) |
| 930 | |
| 931 | # Crash-safe ordering: children first (idempotent by id), header last |
| 932 | # (the commit signal) -- see module docstring's Storage section. |
| 933 | for child in child_rows: |
| 934 | try: |
| 935 | object_records.create_collection_record( |
| 936 | config.child_collection, child, base_dir=base_dir, roots=roots, actor=config.actor, |
| 937 | ) |
| 938 | except object_records.DuplicateRecordIdError: |
| 939 | pass # a prior partial run already wrote this line -- harmless |
| 940 | |
| 941 | try: |
| 942 | object_records.create_collection_record( |
| 943 | config.output_collection, header_fields, base_dir=base_dir, roots=roots, actor=config.actor, |
| 944 | ) |
| 945 | except object_records.DuplicateRecordIdError: |
| 946 | # Raced with another pass/process between our existence-check and |
| 947 | # now -- the other writer's header is the real one; ours is a |
| 948 | # no-op, not a failure. |
| 949 | return {"status": "skipped_already_generated", "header_id": header_id} |
| 950 | except object_records.UniqueConstraintError as exc: |
| 951 | # The same race, decided by the schema's `unique` on the marker |
| 952 | # (fin_journals: one journal per generated_from) inside the write |
| 953 | # lock: whoever holds this marker generated this period. Any OTHER |
| 954 | # unique key is a real conflict and stays an error for the pass. |
| 955 | if config.stamp_generated_from and exc.fields == ["generated_from"]: |
| 956 | return {"status": "skipped_already_generated", "header_id": exc.existing_id} |
| 957 | raise |
| 958 | |
| 959 | return {"status": "generated", "header_id": header_id} |
| 960 | |
| 961 | |
| 962 | def _generate_creatework( |
| 963 | config: MaterializeConfig, source_row: Mapping[str, str], *, base_dir: Any, roots: Any = None, |
| 964 | ) -> dict[str, Any]: |
| 965 | """CreateWork shape: fill empty fields on the SAME row, never create. |
| 966 | |
| 967 | Two independent fill mechanisms, both fill-only-if-empty (61's Events |
| 968 | "correctness rule, not a nicety"), applied in order so a field either |
| 969 | mechanism has already filled is left alone by the other: |
| 970 | 1. this definition's own ``mapping`` (generic, works for any |
| 971 | CreateWork-shaped definition). |
| 972 | 2. an opportunistic hop through a ``templates`` relation field, per |
| 973 | 61's worked example 3 exactly (``_apply_template_defaults``). |
| 974 | The whole ``changes`` dict is built in memory and written in ONE |
| 975 | ``update_collection_record`` call -- a malformed template blob aborts |
| 976 | the row cleanly with nothing written, same "compute fully, then write |
| 977 | once" discipline as the header+children path, at a smaller scale. |
| 978 | """ |
| 979 | source_id = source_row.get("id") or "" |
| 980 | if not source_id: |
| 981 | return {"status": "skipped_already_generated"} |
| 982 | |
| 983 | changes: dict[str, str] = {} |
| 984 | for field_name, entry in config.mapping.items(): |
| 985 | current = source_row.get(field_name) |
| 986 | if current not in (None, ""): |
| 987 | continue # fill-only-if-empty |
| 988 | value = _eval_entry(field_name, entry, source_row=source_row, period=None, definition_id=config.definition_id) |
| 989 | if value in (None, ""): |
| 990 | continue |
| 991 | changes[field_name] = value |
| 992 | |
| 993 | _apply_template_defaults(config, source_row, changes, base_dir=base_dir, roots=roots) |
| 994 | |
| 995 | if config.stamp_generated_from and "generated_from" not in changes and ( |
| 996 | source_row.get("generated_from") in (None, "") |
| 997 | ): |
| 998 | changes["generated_from"] = _generated_from_value(config, source_row=source_row, period=None) |
| 999 | |
| 1000 | if not changes: |
| 1001 | return {"status": "skipped_already_generated", "header_id": source_id} |
| 1002 | |
| 1003 | object_records.update_collection_record( |
| 1004 | config.output_collection, source_id, changes, base_dir=base_dir, roots=roots, actor=config.actor, |
| 1005 | ) |
| 1006 | return {"status": "generated", "header_id": source_id} |
| 1007 | |
| 1008 | |
| 1009 | def _apply_template_defaults( |
| 1010 | config: MaterializeConfig, source_row: Mapping[str, str], changes: dict[str, str], |
| 1011 | *, base_dir: Any, roots: Any = None, |
| 1012 | ) -> None: |
| 1013 | """61's worked example 3, literally: find a relation field on the |
| 1014 | OUTPUT schema pointing at ``templates``, follow it, parse that |
| 1015 | template's ``default_values`` JSON, fill-only-if-empty. Best-effort in |
| 1016 | the sense that "no such field," "no id set," "row not found" are all |
| 1017 | quiet no-ops (this definition simply isn't the templates-relation |
| 1018 | shape, or the reference is dangling) -- but a malformed |
| 1019 | ``default_values`` JSON blob is allowed to raise, surfacing as a |
| 1020 | logged per-row error rather than silently doing nothing, since that |
| 1021 | is a real data problem worth an operator's attention. |
| 1022 | """ |
| 1023 | try: |
| 1024 | schema = object_schemas.get_schema(config.output_collection, base_dir=base_dir, roots=roots) |
| 1025 | except object_schemas.SchemaNotFoundError: |
| 1026 | return |
| 1027 | |
| 1028 | template_field = None |
| 1029 | for field in schema.get("fields", []): |
| 1030 | relation = field.get("relation") or {} |
| 1031 | if relation.get("collection") == "templates": |
| 1032 | template_field = field.get("name") |
| 1033 | break |
| 1034 | if not template_field: |
| 1035 | return |
| 1036 | |
| 1037 | template_id = source_row.get(template_field) |
| 1038 | if not template_id: |
| 1039 | return |
| 1040 | |
| 1041 | try: |
| 1042 | template_row = object_records.get_collection_record("templates", template_id, base_dir=base_dir, roots=roots) |
| 1043 | except ( |
| 1044 | object_records.RecordNotFoundError, |
| 1045 | object_records.InvalidRecordIdError, |
| 1046 | object_collections.CollectionNotFoundError, |
| 1047 | object_collections.InvalidCollectionNameError, |
| 1048 | ): |
| 1049 | return |
| 1050 | |
| 1051 | raw_defaults = (template_row.get("default_values") or "").strip() |
| 1052 | if not raw_defaults: |
| 1053 | return |
| 1054 | |
| 1055 | defaults = json.loads(raw_defaults) # malformed JSON deliberately propagates -- see docstring |
| 1056 | if not isinstance(defaults, dict): |
| 1057 | return |
| 1058 | |
| 1059 | for field_name, value in defaults.items(): |
| 1060 | if field_name in changes: |
| 1061 | continue |
| 1062 | current = source_row.get(field_name) |
| 1063 | if current not in (None, ""): |
| 1064 | continue |
| 1065 | changes[field_name] = _stringify(value) |
| 1066 | |
| 1067 | |
| 1068 | def _marker_holder(collection: str, marker: str, *, base_dir: Any, roots: Any = None) -> str | None: |
| 1069 | """The id of the record in ``collection`` already stamped with this |
| 1070 | generated_from marker, or None. A read that fails raises: an unknown |
| 1071 | is not "not generated" (the caller records it as this period's error |
| 1072 | and the next pass asks again).""" |
| 1073 | for row in object_records.read_collection_records(collection, base_dir=base_dir, roots=roots): |
| 1074 | if row.get("generated_from") == marker: |
| 1075 | return row.get("id") or "" |
| 1076 | return None |
| 1077 | |
| 1078 | |
| 1079 | def _record_exists(collection: str, record_id: str, *, base_dir: Any, roots: Any = None) -> bool: |
| 1080 | try: |
| 1081 | object_records.get_collection_record(collection, record_id, base_dir=base_dir, roots=roots) |
| 1082 | return True |
| 1083 | except object_records.RecordNotFoundError: |
| 1084 | return False |
| 1085 | |
| 1086 | |
| 1087 | def _build_child_rows( |
| 1088 | config: MaterializeConfig, *, source_row: Mapping[str, str], header_id: str, period: Period | None, |
| 1089 | ) -> list[dict[str, str]]: |
| 1090 | if not config.child_collection: |
| 1091 | return [] |
| 1092 | if config.child_source_field: |
| 1093 | return _build_child_rows_from_template(config, source_row=source_row, header_id=header_id) |
| 1094 | if config.synthesized_amount_entry is not None: |
| 1095 | return _build_depreciation_child_rows(config, source_row=source_row, header_id=header_id, period=period) |
| 1096 | return [] # pragma: no cover -- parse_definition already requires one of the above |
| 1097 | |
| 1098 | |
| 1099 | def _build_child_rows_from_template( |
| 1100 | config: MaterializeConfig, *, source_row: Mapping[str, str], header_id: str, |
| 1101 | ) -> list[dict[str, str]]: |
| 1102 | raw = (source_row.get(config.child_source_field) or "").strip() |
| 1103 | if not raw: |
| 1104 | return [] |
| 1105 | try: |
| 1106 | lines = json.loads(raw) |
| 1107 | except json.JSONDecodeError as exc: |
| 1108 | raise DefinitionError(f"{config.definition_id}: {config.child_source_field} is not valid JSON: {exc}") from exc |
| 1109 | if not isinstance(lines, list): |
| 1110 | raise DefinitionError(f"{config.definition_id}: {config.child_source_field} must be a JSON list of line objects") |
| 1111 | |
| 1112 | rows: list[dict[str, str]] = [] |
| 1113 | for index, line in enumerate(lines): |
| 1114 | if not isinstance(line, dict): |
| 1115 | raise DefinitionError(f"{config.definition_id}: {config.child_source_field}[{index}] must be a JSON object") |
| 1116 | child = {str(key): _stringify(value) for key, value in line.items()} |
| 1117 | child["id"] = f"{header_id}_line_{index}" |
| 1118 | child[config.child_link_field] = header_id |
| 1119 | rows.append(child) |
| 1120 | return rows |
| 1121 | |
| 1122 | |
| 1123 | def _build_depreciation_child_rows( |
| 1124 | config: MaterializeConfig, *, source_row: Mapping[str, str], header_id: str, period: Period | None, |
| 1125 | ) -> list[dict[str, str]]: |
| 1126 | amount = _eval_entry( |
| 1127 | "amount", config.synthesized_amount_entry, source_row=source_row, period=period, |
| 1128 | definition_id=config.definition_id, |
| 1129 | ) |
| 1130 | debit_field = config.balance_check["debit_field"] |
| 1131 | credit_field = config.balance_check["credit_field"] |
| 1132 | return [ |
| 1133 | { |
| 1134 | "id": f"{header_id}_line_0", config.child_link_field: header_id, |
| 1135 | "account_id": config.debit_account_id, debit_field: amount, credit_field: "0", |
| 1136 | }, |
| 1137 | { |
| 1138 | "id": f"{header_id}_line_1", config.child_link_field: header_id, |
| 1139 | "account_id": config.credit_account_id, debit_field: "0", credit_field: amount, |
| 1140 | }, |
| 1141 | ] |
| 1142 | |
| 1143 | |
| 1144 | def _sum_balance(config: MaterializeConfig, child_rows: list[dict[str, str]]) -> tuple[int, int]: |
| 1145 | debit_field = config.balance_check["debit_field"] |
| 1146 | credit_field = config.balance_check["credit_field"] |
| 1147 | debit_total = sum(_to_cents(row.get(debit_field)) for row in child_rows) |
| 1148 | credit_total = sum(_to_cents(row.get(credit_field)) for row in child_rows) |
| 1149 | return debit_total, credit_total |
| 1150 | |
| 1151 | |
| 1152 | def _render_idempotency_key(config: MaterializeConfig, *, source_row: Mapping[str, str], period: Period | None) -> str: |
| 1153 | available: dict[str, str] = { |
| 1154 | "definition_id": config.definition_id, |
| 1155 | "source_id": source_row.get("id") or "", |
| 1156 | } |
| 1157 | if period is not None: |
| 1158 | available["period_start"] = period.start.isoformat() |
| 1159 | try: |
| 1160 | return config.idempotency_key.format(**available) |
| 1161 | except KeyError as exc: |
| 1162 | raise DefinitionError( |
| 1163 | f"{config.definition_id}: idempotency_key references {exc} which is not available " |
| 1164 | "for this generation (period_start only applies to scheduled/scheduled_fixed)" |
| 1165 | ) from exc |
| 1166 | |
| 1167 | |
| 1168 | def _generated_from_value(config: MaterializeConfig, *, source_row: Mapping[str, str], period: Period | None) -> str: |
| 1169 | payload = { |
| 1170 | "definition_id": config.definition_id, |
| 1171 | "source_id": source_row.get("id") or "", |
| 1172 | "period_start": period.start.isoformat() if period is not None else None, |
| 1173 | } |
| 1174 | return json.dumps(payload, separators=(",", ":")) |
| 1175 | |
| 1176 | |
| 1177 | # --- Event mode (CreateWork dispatch) ------------------------------------------------- |
| 1178 | |
| 1179 | def event_definitions_for_collection( |
| 1180 | collection: str, *, base_dir: Any, roots: Any = None, |
| 1181 | ) -> list[dict[str, str]]: |
| 1182 | """Return every enabled, non-blocked, event-mode definition whose |
| 1183 | ``source_collection`` is ``collection`` -- the raw records (not |
| 1184 | parsed), cheap enough to call on every dispatch (one collection read, |
| 1185 | one JSON parse per row); the full ``parse_definition`` validation |
| 1186 | happens once ``generate_one_event`` actually attempts a generation. |
| 1187 | """ |
| 1188 | try: |
| 1189 | definitions = object_records.read_collection_records( |
| 1190 | MATERIALIZE_DEFINITIONS_COLLECTION, base_dir=base_dir, roots=roots |
| 1191 | ) |
| 1192 | except (object_collections.CollectionNotFoundError, object_collections.InvalidCollectionNameError): |
| 1193 | return [] |
| 1194 | |
| 1195 | matches = [] |
| 1196 | for definition in definitions: |
| 1197 | if is_definition_blocked(definition) or not is_definition_enabled(definition): |
| 1198 | continue |
| 1199 | if (definition.get("source_collection") or "").strip() != collection: |
| 1200 | continue |
| 1201 | trigger = _json_field(definition, "trigger", None, definition_id=definition.get("id") or "<unknown>") |
| 1202 | if not isinstance(trigger, dict) or trigger.get("mode") != "event": |
| 1203 | continue |
| 1204 | matches.append(definition) |
| 1205 | return matches |
| 1206 | |
| 1207 | |
| 1208 | def generate_one_event( |
| 1209 | definition_record: Mapping[str, str], source_row: Mapping[str, str], *, base_dir: Any, roots: Any = None, |
| 1210 | ) -> dict[str, Any]: |
| 1211 | """Apply ONE event-mode definition to ONE just-created source row -- |
| 1212 | what ``materialize_seed``'s ``EVENT`` handler calls per dispatched |
| 1213 | record.created event, per definition matching that collection. |
| 1214 | """ |
| 1215 | config = parse_definition(definition_record, base_dir=base_dir, roots=roots) |
| 1216 | if config.trigger_mode != "event": |
| 1217 | raise DefinitionError(f"{config.definition_id} is not an event-mode definition") |
| 1218 | return generate_one(config, source_row, None, base_dir=base_dir, roots=roots) |
| 1219 | |
| 1220 | |
| 1221 | def compute_event_handles(*, base_dir: Any, roots: Any = None) -> list[str]: |
| 1222 | """Return the sorted, de-duplicated ``<collection>.record.created`` |
| 1223 | event list every currently enabled, non-blocked, event-mode definition |
| 1224 | implies -- i.e. what ``materialize_seed``'s static ``HANDLES`` literal |
| 1225 | WOULD need to contain for automatic on-create dispatch. |
| 1226 | |
| 1227 | Pure computation, no side effects. In v1 nothing wires this into the |
| 1228 | object's source at runtime (we do NOT rewrite installed objects under |
| 1229 | the poll loop -- see object_daemon.process_materializations); it exists |
| 1230 | for inspection/tests and as the input a future *deliberate, scheduled* |
| 1231 | HANDLES-sync mechanism (with its own tests and a real performance |
| 1232 | rationale) would use. Event-mode definitions run via the manual path |
| 1233 | (materialize_run) until then. |
| 1234 | """ |
| 1235 | try: |
| 1236 | definitions = object_records.read_collection_records( |
| 1237 | MATERIALIZE_DEFINITIONS_COLLECTION, base_dir=base_dir, roots=roots |
| 1238 | ) |
| 1239 | except (object_collections.CollectionNotFoundError, object_collections.InvalidCollectionNameError): |
| 1240 | return [] |
| 1241 | |
| 1242 | events: set[str] = set() |
| 1243 | for definition in definitions: |
| 1244 | if is_definition_blocked(definition) or not is_definition_enabled(definition): |
| 1245 | continue |
| 1246 | trigger = _json_field(definition, "trigger", None, definition_id=definition.get("id") or "<unknown>") |
| 1247 | if not isinstance(trigger, dict) or trigger.get("mode") != "event": |
| 1248 | continue |
| 1249 | source_collection = (definition.get("source_collection") or "").strip() |
| 1250 | if source_collection: |
| 1251 | events.add(f"{source_collection}.record.created") |
| 1252 | return sorted(events) |
| 1253 | |
| 1254 | |
| 1255 | # NOTE: there is deliberately no runtime "sync HANDLES by rewriting the |
| 1256 | # installed materialize_seed.py" function here. Rewriting an existing |
| 1257 | # object's source under the daemon poll loop is the wrong shape (expensive, |
| 1258 | # surprising, self-modifying). materialize_seed ships inert (HANDLES == []) |
| 1259 | # and event-mode runs manually (materialize_run). If automatic on-create |
| 1260 | # dispatch is ever worth wiring, compute_event_handles above is the input a |
| 1261 | # separate, scheduled, tested job would consume -- not this module at import |
| 1262 | # or the poll loop at runtime. |
| 1263 | |
| 1264 | |
| 1265 | # --- Small shared helpers ------------------------------------------------- |
| 1266 | |
| 1267 | def _stringify(value: Any) -> str: |
| 1268 | if value is None: |
| 1269 | return "" |
| 1270 | if isinstance(value, bool): |
| 1271 | return "true" if value else "false" |
| 1272 | return str(value) |
| 1273 | |
| 1274 | |
| 1275 | def _to_cents(value: Any) -> int: |
| 1276 | text = str(value if value is not None else "").strip() |
| 1277 | if not text: |
| 1278 | return 0 |
| 1279 | try: |
| 1280 | return int(text) |
| 1281 | except ValueError as exc: |
| 1282 | raise DefinitionError(f"expected an integer cents value, got {value!r}") from exc |
| 1283 | |
| 1284 | |
| 1285 | def _truthy(value: Any, *, default: bool) -> bool: |
| 1286 | if value is None or value == "": |
| 1287 | return default |
| 1288 | return str(value).strip().lower() in {"true", "1", "yes", "on"} |
| 1289 | |
| 1290 | |
| 1291 | def _positive_int(value: Any) -> int | None: |
| 1292 | try: |
| 1293 | parsed = int(str(value).strip()) |
| 1294 | except (TypeError, ValueError): |
| 1295 | return None |
| 1296 | return parsed if parsed > 0 else None |
| 1297 | |
| 1298 | |
| 1299 | def _parse_iso(value: str) -> datetime | None: |
| 1300 | try: |
| 1301 | parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) |
| 1302 | except ValueError: |
| 1303 | return None |
| 1304 | if parsed.tzinfo is None: |
| 1305 | parsed = parsed.replace(tzinfo=timezone.utc) |
| 1306 | return parsed |
| 1307 | |
| 1308 | |
| 1309 | def _json_field(record: Mapping[str, str], name: str, default: Any, *, definition_id: str) -> Any: |
| 1310 | raw = record.get(name) |
| 1311 | if raw is None: |
| 1312 | return default |
| 1313 | if not isinstance(raw, str): |
| 1314 | return raw |
| 1315 | raw = raw.strip() |
| 1316 | if not raw: |
| 1317 | return default |
| 1318 | try: |
| 1319 | return json.loads(raw) |
| 1320 | except json.JSONDecodeError as exc: |
| 1321 | raise DefinitionError(f"{definition_id}: {name} is not valid JSON: {exc}") from exc |