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_records.py · 264.4 KB · 6067 lines
| 1 | """TSV-backed collection records. |
| 2 | |
| 3 | Collection records are the simple data surface Scroll can point generated |
| 4 | tables and forms at. Records live in |
| 5 | ``data/collections/{collection}/records.tsv``. |
| 6 | """ |
| 7 | |
| 8 | from __future__ import annotations |
| 9 | |
| 10 | import csv |
| 11 | import hashlib |
| 12 | import hmac |
| 13 | import io |
| 14 | import json |
| 15 | import math |
| 16 | import os |
| 17 | import re |
| 18 | import stat |
| 19 | import threading |
| 20 | import time |
| 21 | from array import array |
| 22 | from collections import OrderedDict |
| 23 | from contextlib import contextmanager |
| 24 | from datetime import date, datetime, timezone |
| 25 | from decimal import Decimal, InvalidOperation |
| 26 | from pathlib import Path |
| 27 | from typing import Any, Callable, Iterable, Mapping, Sequence |
| 28 | |
| 29 | import object_collections |
| 30 | import object_computed |
| 31 | import object_correlation |
| 32 | import object_ids |
| 33 | import object_permissions |
| 34 | import object_record_changes |
| 35 | import object_schemas |
| 36 | from object_versions import DEFAULT_DATA_DIR |
| 37 | |
| 38 | COLLECTIONS_DIR = "collections" |
| 39 | RECORDS_FILE = "records.tsv" |
| 40 | DEFAULT_RECORD_LIMIT = 100 |
| 41 | MAX_RECORD_LIMIT = 1000 |
| 42 | EXTRA_FIELD = "extra" |
| 43 | |
| 44 | # Maximum bytes for a single TSV field value. Python's csv module defaults |
| 45 | # csv.field_size_limit() to 128 KiB; a single record field can legitimately |
| 46 | # exceed that (a long article body, a big template JSON, the embedded-items |
| 47 | # array of plan/vocabulary/66). Left unraised, a cell over 128 KiB is a |
| 48 | # silent data-loss bug: a classic-mode read raises an uncaught csv.Error, |
| 49 | # and an APPEND-mode read returns an EMPTY collection (the oversize row trips |
| 50 | # the torn-tail-tolerant `except csv.Error: break` in _parse_append_body, |
| 51 | # discarding every row from that point on). We raise the PARSE ceiling here |
| 52 | # and enforce the SAME ceiling on WRITE (_check_field_sizes, called from |
| 53 | # create/update) so no row is ever persisted that cannot be read back. 16 MiB |
| 54 | # matches the platform's max request body -- a field cannot exceed the |
| 55 | # request that wrote it. Per-surface limits (e.g. the 256 KiB line-items cap) |
| 56 | # are stricter and enforced above this hard floor. |
| 57 | MAX_TSV_FIELD_BYTES = 16 * 1024 * 1024 |
| 58 | csv.field_size_limit(MAX_TSV_FIELD_BYTES) |
| 59 | |
| 60 | _RECORD_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$") |
| 61 | |
| 62 | # Append-only storage (docs/append-only-storage-design.md). `OP_FIELD` is |
| 63 | # an INTERNAL, file-layer-only column: when present, it is always the |
| 64 | # first column of the physical header, and it never appears in a schema, |
| 65 | # an API response, or a record returned by any public function in this |
| 66 | # module -- it is stripped during parse-fold and only ever written by the |
| 67 | # append/rewrite helpers below. `OP_UPSERT` ("") marks a row that sets/ |
| 68 | # replaces a record; `OP_DELETE` ("del") marks a tombstone. |
| 69 | OP_FIELD = "_op" |
| 70 | OP_UPSERT = "" |
| 71 | OP_DELETE = "del" |
| 72 | |
| 73 | # Threshold (physical row count) above which a collection becomes eligible |
| 74 | # for auto-compaction: see _maybe_flag_auto_compact. |
| 75 | APPEND_COMPACT_MIN_ROWS_ENV = "DBBASIC_APPEND_COMPACT_MIN_ROWS" |
| 76 | _DEFAULT_APPEND_COMPACT_MIN_ROWS = 10_000 |
| 77 | |
| 78 | # id -> byte-offset sidecar (docs/append-only-storage-design.md item 4). |
| 79 | # Lives next to records.tsv as a dotfile so it is invisible to every glob |
| 80 | # this codebase uses to enumerate a collection's real content |
| 81 | # (iter_record_collections' `*/records.tsv` glob, object_collections' same |
| 82 | # pattern) and to backup (object_backup._should_skip drops any path with a |
| 83 | # dotfile part) -- both were checked, not just assumed. Format (text, |
| 84 | # greppable, torn-tail-tolerant like the data file itself): |
| 85 | # line 1 (header): "oidx1\t<data_ino>" -- the records.tsv inode this |
| 86 | # sidecar describes. No byte count lives in the header (a header |
| 87 | # rewrite-in-place would itself need the same torn-tail care as a data |
| 88 | # row, for no real benefit): "how much of the file is indexed" is |
| 89 | # instead DERIVED from the body, as the row_end_offset of the last |
| 90 | # complete data line -- see _load_oidx_body. |
| 91 | # subsequent lines: "<row_start_offset>\t<row_end_offset>\t<op>\t<id>", |
| 92 | # one per indexed PHYSICAL row of records.tsv (op "" or "del", exactly |
| 93 | # like OP_UPSERT/OP_DELETE). No CSV quoting is used or needed here: |
| 94 | # unlike a record's own field values, `id` is restricted to |
| 95 | # _RECORD_ID_RE (no tabs/newlines possible) and the offsets/op are |
| 96 | # plain digits/literals, so a bare tab-split is always unambiguous. |
| 97 | # The sidecar is 100% disposable and NEVER required for correctness: any |
| 98 | # reader unable to make sense of it (missing, corrupt, inode mismatch, |
| 99 | # torn tail beyond what a catch-up scan can resolve) rebuilds it with one |
| 100 | # sequential scan of records.tsv rather than raising -- see _load_oidx. |
| 101 | OIDX_FILE = ".records.oidx" |
| 102 | OIDX_HEADER_TAG = "oidx1" |
| 103 | |
| 104 | OIDX_CACHE_MAX_ENTRIES_ENV = "DBBASIC_OIDX_CACHE_MAX_ENTRIES" |
| 105 | _DEFAULT_OIDX_CACHE_MAX_ENTRIES = 2 |
| 106 | |
| 107 | # Env knobs for the records cache below. Read at call time (not cached in a |
| 108 | # module global) via _records_cache_max_entries()/_records_cache_max_rows() |
| 109 | # so tests can monkeypatch os.environ and see the change take effect on the |
| 110 | # next cache operation without reimporting the module. |
| 111 | RECORDS_CACHE_MAX_ENTRIES_ENV = "DBBASIC_RECORDS_CACHE_MAX_ENTRIES" |
| 112 | RECORDS_CACHE_MAX_ROWS_ENV = "DBBASIC_RECORDS_CACHE_MAX_ROWS" |
| 113 | _DEFAULT_RECORDS_CACHE_MAX_ENTRIES = 64 |
| 114 | _DEFAULT_RECORDS_CACHE_MAX_ROWS = 500_000 |
| 115 | |
| 116 | # Module-level cache for parsed records.tsv files, keyed by the resolved |
| 117 | # file path. An OrderedDict bounded to DBBASIC_RECORDS_CACHE_MAX_ENTRIES |
| 118 | # entries (default 64): every cache hit calls move_to_end() so the dict |
| 119 | # stays ordered oldest-to-newest by use, and storing a new entry evicts the |
| 120 | # oldest (popitem(last=False)) once the dict exceeds capacity -- see |
| 121 | # _store_records_cache. Without a bound, a long-running server that touches |
| 122 | # many collections over its lifetime (e.g. a no-downtime game server) would |
| 123 | # pin every collection it has ever parsed in RAM forever; the LRU keeps |
| 124 | # only the most-recently-used entries resident. |
| 125 | # |
| 126 | # A second knob, DBBASIC_RECORDS_CACHE_MAX_ROWS (default 500_000), bounds |
| 127 | # the cache by size rather than recency: a collection whose parse produces |
| 128 | # more rows than this is still returned to its caller normally, but is |
| 129 | # never stored in (or left in) the cache. Without this, reading one huge |
| 130 | # collection once would occupy a full LRU slot and could evict many small, |
| 131 | # hot collections just to make room for something that will likely never |
| 132 | # be reused whole. _cache_entry and _refresh_records_cache both apply this |
| 133 | # threshold before writing to _RECORDS_CACHE; _cache_entry additionally |
| 134 | # drops any stale entry already cached for a path that has since grown |
| 135 | # past the threshold, so an oversized collection never lingers there under |
| 136 | # an old signature. |
| 137 | # |
| 138 | # Value is (stat_signature, fields, records, id_index, covered_bytes): |
| 139 | # - stat_signature = (st_mtime_ns, st_size, st_ino). A CLASSIC-mode write |
| 140 | # goes through an atomic tempfile-then-replace, so a new inode backs the |
| 141 | # path after each write; including st_ino means a same-tick mtime |
| 142 | # collision (coarse clocks/filesystems) still isn't mistaken for |
| 143 | # "unchanged" as long as the replace produced a different inode, which |
| 144 | # is the common case for both our own writes and any other well-behaved |
| 145 | # writer using the same replace pattern. |
| 146 | # APPEND-mode writes (docs/append-only-storage-design.md) are the |
| 147 | # deliberate exception: a fast append opens the SAME inode in "a" mode |
| 148 | # and writes one more line, so st_ino is unchanged and only st_mtime_ns |
| 149 | # / st_size move. That's still sufficient to invalidate a stale cache |
| 150 | # entry (the signature tuple as a whole changes), it just means "same |
| 151 | # inode" is no longer proof of "unchanged content" the way it was |
| 152 | # before this feature -- st_size growing is what a reader actually |
| 153 | # relies on to notice a completed append. A torn tail (a final physical |
| 154 | # line with no trailing newline, from a write interrupted mid-append) |
| 155 | # is never cached as data: the append-mode parser drops it, and the |
| 156 | # next append's self-heal (_repair_torn_tail) removes it from disk |
| 157 | # before adding a new line, so it can never resurface as a stale-but- |
| 158 | # plausible cached row either. |
| 159 | # - fields/records mirror exactly what a fresh parse of that exact file |
| 160 | # content would produce (see _refresh_records_cache: written rows are |
| 161 | # projected to the full field set before caching, matching what |
| 162 | # csv.DictWriter/csv.reader would round-trip). For an append-mode file |
| 163 | # this means the FOLDED (last-wins-by-id, tombstones removed, `_op` |
| 164 | # stripped) view -- see _parse_append_body/_fold_append_rows -- never |
| 165 | # the raw physical rows; everything below this cache (get, list, |
| 166 | # window-copy, extra-field surfacing) operates on folded records with |
| 167 | # zero changes, exactly as it does for a classic-mode file. |
| 168 | # - id_index maps record id -> index into `records`, first-occurrence-wins |
| 169 | # (matching the original linear scan's behavior on hand-edited files |
| 170 | # with duplicate ids). For append mode this is built from the already- |
| 171 | # deduplicated folded records, so in practice every live id maps to |
| 172 | # exactly one position. |
| 173 | # - covered_bytes is the byte offset (from 0) that this entry's fold |
| 174 | # already accounts for, and always a committed row boundary -- equal |
| 175 | # to the file's size at the stat this entry was built from |
| 176 | # (signature[1]) for every entry produced by a full parse of a file |
| 177 | # that ends on a committed row, or by a full rewrite (_cache_entry's |
| 178 | # full-parse branch, _refresh_records_cache, _refresh_records_cache_ |
| 179 | # after_append). A full parse of a file with a torn tail stores where |
| 180 | # the torn row starts instead (_cache_entry explains why: the size |
| 181 | # pointed into the next writer's row once the tail was repaired). It exists so _cache_entry's INCREMENTAL branch |
| 182 | # (docs/append-only-storage-design.md Sidecars, bullet 2: "cache |
| 183 | # entries remember the byte offset they consumed; when a stat |
| 184 | # signature changes by growth alone, parse only the tail delta") can |
| 185 | # tell how much of a GROWN append-mode file is already folded into |
| 186 | # `records`, so only the new bytes need parsing -- see |
| 187 | # _try_incremental_cache_entry. A CLASSIC-mode entry carries this |
| 188 | # field too (harmless: it's just the file's size at cache time, |
| 189 | # unused by anything) since a classic rewrite always produces a new |
| 190 | # inode, which alone rules out the incremental branch regardless of |
| 191 | # covered_bytes. An entry ends up with covered_bytes < signature[1] |
| 192 | # exactly when the file ended in a torn (uncommitted) row: that |
| 193 | # fragment's bytes are left out of both `records` and covered_bytes, |
| 194 | # by the incremental fold (its tail delta ended torn) and by a full |
| 195 | # parse alike (_drop_torn_tail); a later append still compares |
| 196 | # against this same covered_bytes to find its own delta. |
| 197 | # |
| 198 | # ALIASING SAFETY: the `records` list and its dicts stored here are shared, |
| 199 | # mutable module state. Nothing in this module may mutate them in place. |
| 200 | # Every function that hands a record or records list back across the |
| 201 | # public API must copy first (see _read_collection_records, |
| 202 | # get_collection_record, list_collection_records). Internal callers that |
| 203 | # need to build on cached data for a write (create/update/delete) read |
| 204 | # `_cache_entry`'s tuple directly -- fine as long as they only ever READ |
| 205 | # from `records_ref`/`id_index_ref` (e.g. an O(1) duplicate/lookup check) |
| 206 | # or capture them in a closure that builds a fresh, independent copy on |
| 207 | # demand (see each function's `build_folded_records`, and _persist_write's |
| 208 | # `folded_records_fn`, which calls it only on a full-rewrite path -- never |
| 209 | # on the fast-append path, which is what keeps a steady-state append O(1) |
| 210 | # instead of paying an eager O(n) copy on every single write). |
| 211 | # |
| 212 | # CONCURRENCY (readers hold no lock; writers hold _records_file_lock only |
| 213 | # around their own read-modify-write): a reader's path is stat -> dict.get |
| 214 | # -> compare signature -> return (falling through to parse+store on a |
| 215 | # miss). A writer's path builds a complete new (signature, fields, records, |
| 216 | # id_index) tuple off to the side and installs it with a single dict |
| 217 | # assignment (see _store_records_cache). That assignment is one atomic |
| 218 | # store under the GIL, so a concurrent reader's dict.get() always observes |
| 219 | # either the entry from before the write or the entry from after it in |
| 220 | # full -- never a torn mix of old fields with new records, or similar. |
| 221 | # |
| 222 | # The only reachable skew is an old signature serving newer content: a |
| 223 | # reader stats the file (capturing the OLD signature), a writer's replace() |
| 224 | # lands, and only then does the reader open+parse the file via its own |
| 225 | # fresh fd. Because replace() is atomic and that fd is opened after the |
| 226 | # stat, the fd sees either the pre- or post-write content in full, never a |
| 227 | # mix -- so if it lands on the post-write content, what the reader parses |
| 228 | # is complete and correct, it's just paired with a signature it captured a |
| 229 | # moment too early. That mismatch means this parse won't be stored under a |
| 230 | # key matching what's already cached, so it simply fails every future |
| 231 | # signature comparison and self-heals with one extra reparse next time |
| 232 | # (typically immediately, since the writer's own _refresh_records_cache |
| 233 | # call installs the current signature right after the write completes). |
| 234 | # The reverse -- a new signature paired with old content -- is structurally |
| 235 | # impossible: content is always read at or after the stat that produced |
| 236 | # its signature, never before. |
| 237 | # That holds for entries built by READING. An append-mode fast append |
| 238 | # builds its entry without reading: prior entry + this row, stamped with |
| 239 | # the post-append signature. That is the reverse case unless the prior |
| 240 | # entry was current up to the byte where the row landed, which is exactly |
| 241 | # what _refresh_records_cache_after_append now checks (start_offset). It |
| 242 | # did not, and after another process's append this process cached "their |
| 243 | # rows missing" under a signature that said "current". |
| 244 | # |
| 245 | # Cross-process coherence relies on every writer in this codebase using the |
| 246 | # same temp-file + atomic-rename pattern, so a fresh inode backs every |
| 247 | # write (st_ino is part of the signature): this module's own |
| 248 | # _write_collection_records (below), object_packages.py's package-install |
| 249 | # writer (~line 1022, os.replace), and object_backup.py's restore writer |
| 250 | # (~line 607, Path.replace) were all checked and write via a temp path |
| 251 | # followed by an atomic replace, never an in-place open("w"). |
| 252 | # |
| 253 | # FIELD INDEX (row-filter pushdown; see read_collection_records_for_plan). |
| 254 | # Every entry also carries `field_index`: {field: {value: positions}}, the |
| 255 | # id_index idea for the other fields a permission rule compares by |
| 256 | # equality (owner_id, project_id, is_public, ...). It starts empty and is |
| 257 | # filled lazily, one field at a time, by the first reader that asks. |
| 258 | # - It is an ATTRIBUTE of the entry (_RecordsCacheEntry, a tuple |
| 259 | # subclass), not a sixth element and not a second dict keyed by path. |
| 260 | # Not a sixth element because the entry is unpacked as five values in |
| 261 | # several places, tests included. Not a side dict because that is a |
| 262 | # second cache with its own invalidation to get wrong: it would need a |
| 263 | # hook at every place an entry is replaced, popped (five sites) or |
| 264 | # LRU-evicted, and a missed hook pins a stale copy of up to |
| 265 | # DBBASIC_RECORDS_CACHE_MAX_ROWS rows. As an attribute the index lives |
| 266 | # and dies with the one entry whose `records` list it describes: every |
| 267 | # write installs a NEW entry (nothing cached is mutated in place -- the |
| 268 | # ALIASING SAFETY note), so a new records list always starts with an |
| 269 | # empty index, and there is no invalidation code at all. |
| 270 | # - Unlike id_index it is never carried over to the next entry, not even |
| 271 | # by the incremental paths: an update can move a row between buckets |
| 272 | # and a delete shifts every later position. The first planned read |
| 273 | # after a write rebuilds the fields it needs (measured: 0.3-0.9 ms per |
| 274 | # field per 10,000 rows; 3 ms for the five fields the notes rules use). |
| 275 | # - Positions are only ever applied to the list of the SAME entry: the |
| 276 | # reader takes (records, id_index) from _cache_entry, then accepts the |
| 277 | # index only from an entry whose records list IS that list. A |
| 278 | # concurrent write in between means "no index for this request", never |
| 279 | # "old positions into new rows". |
| 280 | # - Memory: one unsigned 4-byte position per row per indexed field, plus |
| 281 | # a dict slot and an array header (~120 bytes) per DISTINCT value of |
| 282 | # that field. Measured: 4 bytes/row for a boolean, 17 bytes/row for an |
| 283 | # owner with ten rows each, 122 bytes/row when every value is distinct |
| 284 | # (which is why `id` reuses id_index instead: _IdIndexBuckets); 40 |
| 285 | # bytes/row in all for the five fields the notes rules use. Only fields |
| 286 | # a permission rule (or the owner keys) actually looks up are ever |
| 287 | # built, only for collections in this cache, so it is bounded by the |
| 288 | # same two knobs as the cache itself. |
| 289 | _RECORDS_CACHE: "OrderedDict[str, _RecordsCacheEntry]" = OrderedDict() |
| 290 | |
| 291 | |
| 292 | class _RecordsCacheEntry(tuple): |
| 293 | """One _RECORDS_CACHE value: (stat_signature, fields, records, id_index, |
| 294 | covered_bytes), plus the lazily filled `field_index` attribute. See the |
| 295 | block comment above.""" |
| 296 | |
| 297 | field_index: dict[str, Any] |
| 298 | |
| 299 | def __new__(cls, values: tuple) -> "_RecordsCacheEntry": |
| 300 | entry = super().__new__(cls, values) |
| 301 | entry.field_index = {} |
| 302 | return entry |
| 303 | |
| 304 | |
| 305 | # Serializes lazy field-index builds so that N readers arriving at a cold |
| 306 | # index build it once, not N times. Never held across IO or while taking |
| 307 | # any other lock; the result is installed with one dict assignment, so a |
| 308 | # reader that does not take the lock sees a field's buckets whole or not at |
| 309 | # all. |
| 310 | _FIELD_INDEX_LOCK = threading.Lock() |
| 311 | |
| 312 | # Observability-only counter: incremented once per successful tail-delta |
| 313 | # incremental fold in _cache_entry (see _try_incremental_cache_entry). |
| 314 | # Never read by any runtime code path -- it exists purely so tests can |
| 315 | # assert the incremental path actually ran (rather than a full re-parse) |
| 316 | # without needing to monkeypatch internals just to observe that. |
| 317 | _INCREMENTAL_CACHE_FOLDS = 0 |
| 318 | |
| 319 | # In-memory mirror of the on-disk id->offset sidecar (see OIDX_FILE above), |
| 320 | # keyed by resolved records.tsv path. Value is (data_ino, covered_bytes, |
| 321 | # id->row_start_offset): `covered_bytes` is how much of the file (from |
| 322 | # byte 0) this dict accounts for -- see _load_oidx, the sole reader AND |
| 323 | # writer of this dict. A DELIBERATELY SEPARATE, much smaller LRU than |
| 324 | # _RECORDS_CACHE (default 2 entries, not 64): the two caches serve |
| 325 | # opposite size regimes -- _RECORDS_CACHE holds fully-parsed records and |
| 326 | # is capped by ROW COUNT (never stores anything over |
| 327 | # DBBASIC_RECORDS_CACHE_MAX_ROWS), while this sidecar is only ever |
| 328 | # consulted for collections ABOVE that same threshold (see |
| 329 | # _fast_record_lookup: it's tried only on a _RECORDS_CACHE miss), so an |
| 330 | # entry here is exactly the case _RECORDS_CACHE refuses to hold. A plain |
| 331 | # {id: int} dict is far lighter per row than a full record dict, but at |
| 332 | # millions of rows it is still tens of MB (roughly 80-120MB at 1M ids per |
| 333 | # the design doc) -- sharing _RECORDS_CACHE's 64-entry budget would let a |
| 334 | # few huge collections' sidecars alone occupy gigabytes. Bounded instead |
| 335 | # by DBBASIC_OIDX_CACHE_MAX_ENTRIES (default 2): a server touching more |
| 336 | # than a couple of huge append collections concurrently pays a reload |
| 337 | # (still just a sidecar-body read, not a records.tsv fold) rather than |
| 338 | # holding every one of them resident forever. |
| 339 | _OIDX_CACHE: "OrderedDict[str, tuple[int, int, dict[str, int]]]" = OrderedDict() |
| 340 | |
| 341 | # Collections (by resolved records.tsv path) flagged during a parse/fold as |
| 342 | # having enough superseded+deleted rows to be worth compacting -- see |
| 343 | # _maybe_flag_auto_compact. Consulted (and cleared) by _persist_write on |
| 344 | # that collection's NEXT write, which performs a compacting rewrite instead |
| 345 | # of a plain append. Never acted on from a read path: setting membership |
| 346 | # here is the only thing a read ever does, and it is not a disk write. |
| 347 | _PENDING_COMPACTION: set[str] = set() |
| 348 | |
| 349 | # UNIQUE INDEX: who holds each key of each schema `unique` constraint (see |
| 350 | # _check_unique_constraints, the only reader). Keyed by resolved records.tsv |
| 351 | # path; the value is |
| 352 | # (stat_signature, constraints_fingerprint, [ {key: holder} per constraint ]) |
| 353 | # where a holder is the record id, or a tuple of ids when the collection |
| 354 | # already held duplicates before the constraint was declared. |
| 355 | # |
| 356 | # Why not _RecordsCacheEntry.field_index, which is the same idea. That index |
| 357 | # is positional and is deliberately never carried from one cache entry to |
| 358 | # the next, so the first lookup after every write rebuilds it from every |
| 359 | # row. Fine for a list request; for a check that runs ON every write it is |
| 360 | # an O(n) scan per write, which turns an O(1) append into O(n) and a bulk |
| 361 | # load into O(n^2). This one is keyed by id, so a write moves one key and |
| 362 | # nothing shifts: it is built once and then kept current by the writes |
| 363 | # themselves. |
| 364 | # |
| 365 | # Why it can be trusted. It is only read and only changed while holding the |
| 366 | # collection's _records_file_lock, and it is only believed when its |
| 367 | # stat_signature is the file's signature at that moment -- the same test |
| 368 | # _RECORDS_CACHE uses. After this process's own write it is updated with |
| 369 | # that one change and re-stamped with the new signature. Anything else that |
| 370 | # touches the file (another process, compaction, prune, a restore) leaves a |
| 371 | # signature this stamp does not match, and the next write rebuilds from the |
| 372 | # records. There is no invalidation code: a stale index is one whose stamp |
| 373 | # is wrong. |
| 374 | # |
| 375 | # Cost. One dict entry per row that has a key, per constraint; only for |
| 376 | # collections whose schema declares `unique`; at most |
| 377 | # DBBASIC_RECORDS_CACHE_MAX_ENTRIES collections, least recently written |
| 378 | # first out. Unlike _RECORDS_CACHE there is no row ceiling: a collection too |
| 379 | # large to cache is exactly where a rebuild per write would hurt most (it is |
| 380 | # a full fold of the file), so its keys are held here even though its |
| 381 | # records are not. A build is O(rows); with several processes writing one |
| 382 | # collection in turn, each rebuilds after the other's write. |
| 383 | _UNIQUE_INDEX: "OrderedDict[str, tuple[tuple[int, int, int], str, list[dict[Any, Any]]]]" = OrderedDict() |
| 384 | |
| 385 | # Guards the OrderedDict itself (insert, reorder, evict) across threads |
| 386 | # writing DIFFERENT collections. The maps inside an entry are protected by |
| 387 | # that collection's file lock instead. Never held across IO. |
| 388 | _UNIQUE_INDEX_LOCK = threading.Lock() |
| 389 | |
| 390 | # LOCKED CHECKS (schema `locked_checks`; see _run_locked_checks and |
| 391 | # docs/validation-and-logic.md "Locked checks"). Per-thread lock state: |
| 392 | # held {check lock file path: open file} -- the named check |
| 393 | # locks this thread holds, re-entrant (a rollup refresh nested |
| 394 | # in a write asks again for a lock its outer write took); |
| 395 | # file_depth how many collection file locks (_records_file_lock) this |
| 396 | # thread holds right now -- a check lock is never WAITED for |
| 397 | # while this is non-zero (CheckLockOrderError instead); |
| 398 | # in_check the name of the locked check running on this thread, or |
| 399 | # None. While set, nothing may write (LockedCheckWriteError). |
| 400 | _LOCK_STATE = threading.local() |
| 401 | CHECK_LOCKS_DIR = ".locks" |
| 402 | CHECK_LOCK_TIMEOUT_ENV = "DBBASIC_CHECK_LOCK_TIMEOUT_SECONDS" |
| 403 | _DEFAULT_CHECK_LOCK_TIMEOUT_SECONDS = 30.0 |
| 404 | # Loaded check modules: {source path: (stat signature, module)}. A module is |
| 405 | # kept while its file keeps the stat it was loaded under (an upgrade or an |
| 406 | # override replaces the file and the next write loads the new one). |
| 407 | _CHECK_MODULES: dict[str, tuple[tuple[int, int, int, int], Any]] = {} |
| 408 | _CHECK_MODULES_LOCK = threading.Lock() |
| 409 | |
| 410 | _INTEGER_TYPES = {"int", "integer"} |
| 411 | _FLOAT_TYPES = {"float", "number", "currency"} |
| 412 | _BOOLEAN_TYPES = {"bool", "boolean"} |
| 413 | _TRUE_VALUES = {"true", "1", "yes", "on"} |
| 414 | _FALSE_VALUES = {"false", "0", "no", "off"} |
| 415 | |
| 416 | |
| 417 | class InvalidRecordIdError(ValueError): |
| 418 | """Raised when a record id is not safe for routes or lookup.""" |
| 419 | |
| 420 | |
| 421 | class RecordNotFoundError(LookupError): |
| 422 | """Raised when a record cannot be found in a collection.""" |
| 423 | |
| 424 | |
| 425 | class DuplicateRecordIdError(ValueError): |
| 426 | """Raised when a create would reuse an existing record id.""" |
| 427 | |
| 428 | |
| 429 | class InvalidRecordPayloadError(ValueError): |
| 430 | """Raised when a record write payload is not usable.""" |
| 431 | |
| 432 | |
| 433 | class TransitionNotAllowedError(InvalidRecordPayloadError): |
| 434 | """Raised when a transition's value is valid but its guard denies the subject. |
| 435 | |
| 436 | Subclasses InvalidRecordPayloadError so callers that don't distinguish |
| 437 | the two keep working (still a 400-shaped payload error); callers that |
| 438 | plumb a subject into update_collection_record (see |
| 439 | _validate_field_transitions) can catch this specifically to report a |
| 440 | permission-style 403 instead. |
| 441 | """ |
| 442 | |
| 443 | |
| 444 | class VersionConflictError(Exception): |
| 445 | """Raised when an update's ``expected_rev`` precondition does not match |
| 446 | the record's current content (63 optimistic concurrency, |
| 447 | plan/vocabulary/63-concurrency-spec.md). Deliberately NOT a subclass of |
| 448 | InvalidRecordPayloadError/ValueError so the generic write-error clauses |
| 449 | that map to 400 never swallow it -- the server maps it to a distinct |
| 450 | 409, mirroring how TransitionNotAllowedError maps to 403. |
| 451 | """ |
| 452 | |
| 453 | |
| 454 | class RecordChangedError(VersionConflictError): |
| 455 | """Raised when the row under the write lock is not the row the caller's |
| 456 | gates judged (``judged_rev``). The record API decides permission, the |
| 457 | owner change, field permissions, relation ``requires`` and the pre-write |
| 458 | hook on a row read BEFORE the lock (they read policy, other collections |
| 459 | and run package code, none of which belongs under a collection's file |
| 460 | lock). A writer that changes the row in between would otherwise have the |
| 461 | request land on a row nobody judged: an edit allowed on Ann's row |
| 462 | written after the row was given to Bob. A VersionConflictError, so it is |
| 463 | the same retryable ``409 conflict``: read the row again and retry, and |
| 464 | the gates then judge the row as it is. |
| 465 | """ |
| 466 | |
| 467 | |
| 468 | class UniqueConstraintError(ValueError): |
| 469 | """Raised when a create or update would give a second record a key that |
| 470 | a schema ``unique`` constraint says only one record may hold. |
| 471 | |
| 472 | Raised from inside the write lock, before anything is written. A |
| 473 | ValueError, like DuplicateRecordIdError (the same kind of refusal, about |
| 474 | a declared key instead of the id), so a writer that treats any refused |
| 475 | write alike keeps working; the server catches it first and answers 409. |
| 476 | |
| 477 | A storage-level writer that must be idempotent (a handler replaying an |
| 478 | event, a scheduled top-up) catches this and treats it as "already |
| 479 | done" -- ``existing_id`` is the record that holds the key. That id is |
| 480 | for trusted callers: the HTTP response does not carry it, because the |
| 481 | caller may not be allowed to read that record. |
| 482 | """ |
| 483 | |
| 484 | def __init__( |
| 485 | self, |
| 486 | message: str, |
| 487 | *, |
| 488 | collection: str, |
| 489 | fields: list[str], |
| 490 | scope: list[str], |
| 491 | existing_id: str, |
| 492 | ) -> None: |
| 493 | super().__init__(message) |
| 494 | self.collection = collection |
| 495 | self.fields = list(fields) |
| 496 | self.scope = list(scope) |
| 497 | self.existing_id = existing_id |
| 498 | |
| 499 | |
| 500 | class RecordLockedError(ValueError): |
| 501 | """Raised when an update or delete is refused by a schema ``locked_when`` |
| 502 | rule: the stored record is in a state the schema declares settled. |
| 503 | |
| 504 | Raised from inside the write lock, before anything is written. A |
| 505 | ValueError for the same reason UniqueConstraintError is one; the server |
| 506 | catches it first and answers 409. ``action`` is "update" or "delete"; |
| 507 | ``fields`` are the frozen fields the update tried to change (empty for |
| 508 | a delete); ``when`` is the rule's condition. |
| 509 | """ |
| 510 | |
| 511 | def __init__( |
| 512 | self, |
| 513 | message: str, |
| 514 | *, |
| 515 | collection: str, |
| 516 | record_id: str, |
| 517 | action: str, |
| 518 | fields: list[str], |
| 519 | when: dict[str, list[str]], |
| 520 | ) -> None: |
| 521 | super().__init__(message) |
| 522 | self.collection = collection |
| 523 | self.record_id = record_id |
| 524 | self.action = action |
| 525 | self.fields = list(fields) |
| 526 | self.when = {name: list(values) for name, values in when.items()} |
| 527 | |
| 528 | |
| 529 | class CheckRefusedError(ValueError): |
| 530 | """Raised when a schema ``locked_checks`` entry refuses a write, or |
| 531 | cannot decide it. |
| 532 | |
| 533 | Raised from inside the write lock (and the check's named lock), before |
| 534 | anything is written. A ValueError for the same reason |
| 535 | UniqueConstraintError is one; the server catches it first and answers |
| 536 | with ``status``: |
| 537 | |
| 538 | - 409 ``check_refused``: the check said no (``status`` may be another |
| 539 | 4xx the check chose); |
| 540 | - 503 ``check_unavailable``: the check could not decide -- it said so |
| 541 | (a read it could not make), it raised, its object is not installed, |
| 542 | or its lock could not be had in time. Retrying may succeed; |
| 543 | - 500 ``check_failed``: the check answered outside its contract or tried |
| 544 | to write. |
| 545 | |
| 546 | ``check`` is the entry's name. In every case nothing was written. |
| 547 | """ |
| 548 | |
| 549 | def __init__( |
| 550 | self, |
| 551 | message: str, |
| 552 | *, |
| 553 | collection: str, |
| 554 | check: str, |
| 555 | status: int = 409, |
| 556 | code: str = "check_refused", |
| 557 | ) -> None: |
| 558 | super().__init__(message) |
| 559 | self.collection = collection |
| 560 | self.check = check |
| 561 | self.status = status |
| 562 | self.code = code |
| 563 | |
| 564 | |
| 565 | class CheckLockOrderError(RuntimeError): |
| 566 | """A write asked for a check lock it would have to take while already |
| 567 | holding a collection's file lock. Locks are only ever taken check locks |
| 568 | first, in sorted order, then file locks; waiting the other way round is |
| 569 | how two writers deadlock, so this refuses instead of waiting. Only a |
| 570 | write nested inside another (a rollup refresh) can get here, and only |
| 571 | when the schemas changed between the outer write planning its locks and |
| 572 | the inner one running; the rollup refresh is best-effort and skips.""" |
| 573 | |
| 574 | |
| 575 | class LockedCheckWriteError(RuntimeError): |
| 576 | """A locked check (or something it called) tried to write. A check runs |
| 577 | holding locks other writers wait on; it reads, decides and returns.""" |
| 578 | |
| 579 | |
| 580 | # 63: the wire name for the content fingerprint. ETag-shaped -- opaque to |
| 581 | # callers, compared for equality only, never parsed, never a schema field. |
| 582 | REV_FIELD = "_rev" |
| 583 | |
| 584 | |
| 585 | def compute_record_rev(record: Mapping[str, Any]) -> str: |
| 586 | """Return an opaque content fingerprint of a record's field values. |
| 587 | |
| 588 | SERVER-SIDE ONLY: unkeyed, so anyone holding it can test a guess of any |
| 589 | field in the row. Never hand it to a caller who may not read the whole |
| 590 | row; a client gets client_record_rev. Package code may use it for its |
| 591 | own compare-and-set (``expected_rev``) and the record API for |
| 592 | ``judged_rev``. |
| 593 | |
| 594 | The version signal for optimistic concurrency (63): a deterministic |
| 595 | hash of the record's current fields, computed for free from the |
| 596 | surfaced/projected row already in hand on every read and, inside the |
| 597 | write lock, from the freshly-read row at update time -- no stored |
| 598 | column, no migration, works retroactively on every record. Excludes |
| 599 | REV_FIELD itself so echoing a read's ``_rev`` back into a full-record |
| 600 | round-trip never changes the fingerprint. Sorted keys + a stable JSON |
| 601 | encoding so serialization noise (key order, whitespace) never makes two |
| 602 | logically-identical records disagree. ``default=str`` keeps mixed-type |
| 603 | surfaced values (extra-blob JSON: ints, lists) hashable deterministically. |
| 604 | """ |
| 605 | payload = json.dumps( |
| 606 | {k: v for k, v in record.items() if k != REV_FIELD}, |
| 607 | sort_keys=True, |
| 608 | ensure_ascii=False, |
| 609 | separators=(",", ":"), |
| 610 | default=str, |
| 611 | ) |
| 612 | return hashlib.sha256(payload.encode("utf-8")).hexdigest() |
| 613 | |
| 614 | |
| 615 | # The `_rev` a CLIENT is given is not compute_record_rev. That one is an |
| 616 | # unkeyed hash of the whole stored row, hidden fields included, so a caller |
| 617 | # who could see every other field of a row could hash each candidate value |
| 618 | # of a hidden one (a salary band A/B/C, a status) and compare: the rev was an |
| 619 | # oracle for the field it was meant to say nothing about. The client rev is |
| 620 | # an HMAC over the same full row (and the collection), keyed with a secret |
| 621 | # only this box holds, so nobody outside can compute or test one. It still |
| 622 | # changes whenever any stored field changes -- hidden ones included -- so an |
| 623 | # If-Match still means "the row I read is the row on disk", exactly as |
| 624 | # strict as before. compute_record_rev stays what the server's own checks |
| 625 | # (`judged_rev`, storage-level `expected_rev`) compare; it never leaves the |
| 626 | # server. |
| 627 | REV_KEY_DIR = "record_rev" |
| 628 | REV_KEY_FILE = "secret.key" |
| 629 | _REV_KEY_DOMAIN = b"dbbasic-record-rev-v1\x00" |
| 630 | _REV_KEYS: dict[str, bytes] = {} |
| 631 | _REV_KEYS_LOCK = threading.Lock() |
| 632 | |
| 633 | |
| 634 | def _record_rev_key(base_dir: Path | str) -> bytes: |
| 635 | """This box's revision key: 32 random bytes in |
| 636 | ``<data dir>/record_rev/secret.key`` (0600 in a 0700 directory), made on |
| 637 | first use and read from the file ever after, so a restart and every |
| 638 | worker process sharing the data dir agree. Outside every directory a |
| 639 | backup copies, like the exchange signing key. Made under a temporary |
| 640 | name and linked into place, so two workers racing to make it both end |
| 641 | up reading the one that won, and nobody reads a half-written file.""" |
| 642 | folder = Path(base_dir) / REV_KEY_DIR |
| 643 | cache_key = str(folder.absolute()) |
| 644 | cached = _REV_KEYS.get(cache_key) |
| 645 | if cached is not None: |
| 646 | return cached |
| 647 | with _REV_KEYS_LOCK: |
| 648 | cached = _REV_KEYS.get(cache_key) |
| 649 | if cached is not None: |
| 650 | return cached |
| 651 | path = folder / REV_KEY_FILE |
| 652 | if not path.exists(): |
| 653 | folder.mkdir(parents=True, exist_ok=True) |
| 654 | os.chmod(folder, 0o700) |
| 655 | temp = folder / f".{REV_KEY_FILE}.{os.getpid()}.{os.urandom(4).hex()}" |
| 656 | fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) |
| 657 | try: |
| 658 | os.write(fd, os.urandom(32).hex().encode("ascii")) |
| 659 | os.fsync(fd) |
| 660 | finally: |
| 661 | os.close(fd) |
| 662 | try: |
| 663 | os.link(temp, path) |
| 664 | except FileExistsError: |
| 665 | pass # another worker made it first: use theirs |
| 666 | finally: |
| 667 | temp.unlink(missing_ok=True) |
| 668 | text = path.read_text(encoding="ascii").strip() |
| 669 | if not re.fullmatch(r"[0-9a-f]{64}", text): |
| 670 | # Fail closed: a damaged key would otherwise mean revs nobody |
| 671 | # can check, or a key an outsider could guess. |
| 672 | raise RuntimeError(f"The record revision key {path} is damaged; " |
| 673 | f"delete it and restart (every held _rev then 409s once).") |
| 674 | key = bytes.fromhex(text) |
| 675 | _REV_KEYS[cache_key] = key |
| 676 | return key |
| 677 | |
| 678 | |
| 679 | def client_record_rev( |
| 680 | collection: str, record: Mapping[str, Any], *, base_dir: Path | str = DEFAULT_DATA_DIR |
| 681 | ) -> str: |
| 682 | """The opaque ``_rev`` a caller is given for a row (GET, a list's |
| 683 | ``revs``, an update's answer) and sends back as ``If-Match``. |
| 684 | |
| 685 | Over the full stored row like compute_record_rev (same inputs, REV_FIELD |
| 686 | excluded), plus the collection, keyed with this box's secret |
| 687 | (_record_rev_key). It reveals that a row changed and nothing about what |
| 688 | it holds: it cannot be recomputed from a guess, and two rows never share |
| 689 | one (the id and collection are in it).""" |
| 690 | payload = json.dumps( |
| 691 | [collection, {k: v for k, v in record.items() if k != REV_FIELD}], |
| 692 | sort_keys=True, |
| 693 | ensure_ascii=False, |
| 694 | separators=(",", ":"), |
| 695 | default=str, |
| 696 | ) |
| 697 | return hmac.new(_record_rev_key(base_dir), _REV_KEY_DOMAIN + payload.encode("utf-8"), |
| 698 | hashlib.sha256).hexdigest() |
| 699 | |
| 700 | |
| 701 | def _client_rev_matches( |
| 702 | collection: str, record: Mapping[str, Any], given: str, *, base_dir: Path | str |
| 703 | ) -> bool: |
| 704 | return hmac.compare_digest( |
| 705 | client_record_rev(collection, record, base_dir=base_dir).encode("ascii"), |
| 706 | given.encode("utf-8", "surrogatepass")) |
| 707 | |
| 708 | |
| 709 | def _refuse_unjudged_row( |
| 710 | collection: str, record_id: str, locked: Mapping[str, Any], judged_rev: str | None |
| 711 | ) -> None: |
| 712 | """Raise RecordChangedError when the row read under the write lock is not |
| 713 | the row (by compute_record_rev) the caller's gates judged.""" |
| 714 | if judged_rev is not None and compute_record_rev(locked) != judged_rev: |
| 715 | raise RecordChangedError( |
| 716 | f"Record {collection}/{record_id} changed while this request was being " |
| 717 | f"checked; read it again and retry." |
| 718 | ) |
| 719 | |
| 720 | |
| 721 | def validate_record_id(record_id: str) -> bool: |
| 722 | """Return True when a record id is route-safe.""" |
| 723 | if not isinstance(record_id, str): |
| 724 | return False |
| 725 | return bool(_RECORD_ID_RE.fullmatch(record_id)) |
| 726 | |
| 727 | |
| 728 | def normalize_record_payload(payload: dict[str, Any], *, require_id: bool = False) -> dict[str, str]: |
| 729 | """Return a TSV-safe record payload with scalar values converted to strings.""" |
| 730 | return _normalize_record_payload(payload, require_id=require_id) |
| 731 | |
| 732 | |
| 733 | def list_collection_records( |
| 734 | collection: str, |
| 735 | *, |
| 736 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 737 | roots: Iterable[Path] | None = None, |
| 738 | limit: int = DEFAULT_RECORD_LIMIT, |
| 739 | offset: int = 0, |
| 740 | where: Mapping[str, Any] | None = None, |
| 741 | ) -> dict[str, Any]: |
| 742 | """Return a paginated record list for one collection. |
| 743 | |
| 744 | Copies only the window (records[offset:offset + limit]) rather than |
| 745 | the whole collection first: callers of a paginated list only ever |
| 746 | consume a small page, and copying every record before slicing it away |
| 747 | (the straightforward implementation) dominates cost on large |
| 748 | collections for a window that is thrown away 99% copied. `total` is |
| 749 | computed from the cache's own record count, not from the copied |
| 750 | window. |
| 751 | |
| 752 | `where` (plan/vocabulary/58-query-filter-spec.md) is an optional |
| 753 | normalized field filter, evaluated with `filter_records` -- see there |
| 754 | for the shape. It is purely a field filter with no permission |
| 755 | awareness of its own: callers that also need row-level permission |
| 756 | filtering (object_server's HTTP/MCP surfaces) apply that FIRST and |
| 757 | pass only the already-permitted records through the same evaluator |
| 758 | (`filter_records`), so a field filter can only narrow what a caller |
| 759 | already decided is readable, never widen it -- this function's own |
| 760 | `where` follows the identical narrow-only contract, just without a |
| 761 | row filter of its own to narrow. When `where` is given, the windowing |
| 762 | optimization above no longer applies (a filtered window can't be |
| 763 | known without first testing every row), so the whole collection is |
| 764 | read and filtered before slicing -- same O(rows) cost as any other |
| 765 | full-collection read (see 58's Storage section). |
| 766 | """ |
| 767 | _ensure_collection_known(collection, base_dir=base_dir, roots=roots) |
| 768 | _validate_page(limit=limit, offset=offset) |
| 769 | |
| 770 | records_ref = _cached_records_ref(collection, base_dir=base_dir) |
| 771 | extra_names = _extra_field_names(collection, base_dir=base_dir, roots=roots) |
| 772 | |
| 773 | if where: |
| 774 | matching = [ |
| 775 | _surface_extra(dict(record), extra_names=extra_names) |
| 776 | for record in records_ref |
| 777 | if object_permissions.record_matches_filter( |
| 778 | record, where, object_permissions.PermissionSubject.anonymous() |
| 779 | ) |
| 780 | ] |
| 781 | total = len(matching) |
| 782 | window = matching[offset:offset + limit] |
| 783 | return _build_records_payload(collection, window, total=total, limit=limit, offset=offset) |
| 784 | |
| 785 | total = len(records_ref) |
| 786 | # Copy + surface only the window's records: entries in `records_ref` |
| 787 | # are the module cache's own dicts (see _RECORDS_CACHE ALIASING |
| 788 | # SAFETY above) and _surface_extra mutates its argument in place, so |
| 789 | # each must be copied before use -- but only the rows inside the |
| 790 | # window, never the rest of the collection. |
| 791 | window = [ |
| 792 | _surface_extra(dict(record), extra_names=extra_names) |
| 793 | for record in records_ref[offset:offset + limit] |
| 794 | ] |
| 795 | return _build_records_payload(collection, window, total=total, limit=limit, offset=offset) |
| 796 | |
| 797 | |
| 798 | def filter_records( |
| 799 | records: Iterable[Mapping[str, Any]], |
| 800 | where: Mapping[str, Any] | None, |
| 801 | ) -> list[dict[str, Any]]: |
| 802 | """Return the subset of `records` matching a normalized field filter. |
| 803 | |
| 804 | Pure and in-memory: no read, no schema/permission awareness of its |
| 805 | own. Reuses `object_permissions.record_matches_filter` -- the same |
| 806 | flat-condition evaluator that backs guarded transitions and |
| 807 | permission row filters -- so there is exactly one filter evaluator in |
| 808 | the codebase (plan/vocabulary/58-query-filter-spec.md). |
| 809 | |
| 810 | Callers that also apply a permission row filter MUST do so first and |
| 811 | pass only its output here: this function can only remove rows from |
| 812 | what it is given, never add any back, so "row filter's output is |
| 813 | this function's input" is what structurally guarantees a field |
| 814 | filter can narrow the readable set but never widen it (58's |
| 815 | Permissions Posture). |
| 816 | """ |
| 817 | if not where: |
| 818 | return [dict(record) for record in records] |
| 819 | anonymous = object_permissions.PermissionSubject.anonymous() |
| 820 | return [ |
| 821 | dict(record) |
| 822 | for record in records |
| 823 | if object_permissions.record_matches_filter(record, where, anonymous) |
| 824 | ] |
| 825 | |
| 826 | |
| 827 | _ORDERED_FILTER_OPERATORS = frozenset({"gte", "lte", "gt", "lt"}) |
| 828 | _ORDERED_FILTERABLE_TYPES = _INTEGER_TYPES | _FLOAT_TYPES | {"date", "datetime", "timestamp"} |
| 829 | |
| 830 | |
| 831 | def normalize_filter_value(field: dict[str, Any] | None, op: str, value: str) -> str: |
| 832 | """Validate one query-filter condition's value against a schema field |
| 833 | and return its canonical stored-string form. |
| 834 | |
| 835 | `field` is the schema field definition (or None for a schemaless/ |
| 836 | derived collection, which has no type to validate against and is |
| 837 | treated as permissive -- consistent with every other schema-optional |
| 838 | check in this module). Raises InvalidRecordPayloadError -- the same |
| 839 | exception schema validation already raises -- naming the field on a |
| 840 | bad type, or on an ordered operator (gte/lte/gt/lt) against a field |
| 841 | type that doesn't support ordered comparison (58 restricts those to |
| 842 | date/datetime/integer/number fields). Reuses `_validate_field_type`, |
| 843 | the same per-type parser create/update already validates against, so |
| 844 | there is exactly one value-type validator, not a second one for |
| 845 | filters. |
| 846 | |
| 847 | A boolean field's value is normalized to "true"/"false" -- the same |
| 848 | canonical form `_canonicalize_schema_values` stores on write -- so an |
| 849 | `eq`/`ne` filter written as `?is_public=1` still string-matches a |
| 850 | stored "true" rather than silently never matching. |
| 851 | """ |
| 852 | if field is None: |
| 853 | return value |
| 854 | |
| 855 | name = field.get("name", "") |
| 856 | field_type = str(field.get("type") or "text").lower() |
| 857 | if op in _ORDERED_FILTER_OPERATORS and field_type not in _ORDERED_FILTERABLE_TYPES: |
| 858 | raise InvalidRecordPayloadError( |
| 859 | f"Record field '{name}' does not support operator '{op}' " |
| 860 | f"(only date, datetime, integer, and number fields support " |
| 861 | f"ordered comparison)" |
| 862 | ) |
| 863 | _validate_field_type(field, value) |
| 864 | if field_type in _BOOLEAN_TYPES: |
| 865 | return "true" if _parse_boolean(value, field_name=name) else "false" |
| 866 | return value |
| 867 | |
| 868 | |
| 869 | def read_collection_records( |
| 870 | collection: str, |
| 871 | *, |
| 872 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 873 | roots: Iterable[Path] | None = None, |
| 874 | ) -> list[dict[str, str]]: |
| 875 | """Return all records for one known collection.""" |
| 876 | _ensure_collection_known(collection, base_dir=base_dir, roots=roots) |
| 877 | records = _read_collection_records(collection, base_dir=base_dir) |
| 878 | extra_names = _extra_field_names(collection, base_dir=base_dir, roots=roots) |
| 879 | return [_surface_extra(record, extra_names=extra_names) for record in records] |
| 880 | |
| 881 | |
| 882 | def read_collection_records_where( |
| 883 | collection: str, |
| 884 | field: str, |
| 885 | value: Any, |
| 886 | *, |
| 887 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 888 | roots: Iterable[Path] | None = None, |
| 889 | ) -> list[dict[str, str]]: |
| 890 | """Return the records whose `field` equals `value`, in file order: |
| 891 | exactly `[r for r in read_collection_records(...) if r.get(field) == |
| 892 | value]`, without copying (or even looking at) every other row. |
| 893 | |
| 894 | For a caller that wants one user's handful of rows out of a collection |
| 895 | that grows with the number of users. The server resolves a signed-in |
| 896 | user's project grants, owned projects and record shares this way two to |
| 897 | five times per request, and read_collection_records copied the whole of |
| 898 | all three collections each time (about 1.5 ms of a 1.8 ms record read |
| 899 | at 1,000 users). |
| 900 | |
| 901 | Not a cache of its own. The rows come from the current records snapshot |
| 902 | and the candidates from that same entry's field index (see FIELD INDEX |
| 903 | and _plan_snapshot: one _cache_entry call, positions only ever applied |
| 904 | to the list they were computed from), so a file changed on disk by any |
| 905 | writer is seen on the very next call, exactly as by |
| 906 | read_collection_records. Every candidate is tested again with `==`, so |
| 907 | the index can only make the answer cheaper, never different. Without an |
| 908 | index (a collection too large to cache, a value that is not a string, |
| 909 | or a `store: extra` field, whose value exists only on the surfaced |
| 910 | copy) every row is tested, as before. Same calls in the same order as |
| 911 | read_collection_records, so the same errors at the same points. |
| 912 | """ |
| 913 | groups = (((((field, (value,)),),),) if type(value) is str else None) |
| 914 | records_ref, extra_names, positions = _plan_snapshot( |
| 915 | collection, groups, base_dir=base_dir, roots=roots |
| 916 | ) |
| 917 | if field in extra_names: |
| 918 | surfaced = (_surface_extra(dict(record), extra_names=extra_names) for record in records_ref) |
| 919 | return [record for record in surfaced if record.get(field) == value] |
| 920 | candidates = records_ref if positions is None else [records_ref[p] for p in positions] |
| 921 | # `records_ref` is the module cache's own list of its own dicts (ALIASING |
| 922 | # SAFETY above): read here, copied before anything leaves. |
| 923 | return [ |
| 924 | _surface_extra(dict(record), extra_names=extra_names) |
| 925 | for record in candidates |
| 926 | if record.get(field) == value |
| 927 | ] |
| 928 | |
| 929 | |
| 930 | def read_collection_records_for_plan( |
| 931 | collection: str, |
| 932 | groups: Sequence[Sequence[Sequence[tuple[str, Any]]]] | None, |
| 933 | *, |
| 934 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 935 | roots: Iterable[Path] | None = None, |
| 936 | ) -> tuple[list[dict[str, str]], bool]: |
| 937 | """Return the records a row-filter plan asks for, in file order. |
| 938 | |
| 939 | `groups` is `object_permissions.RowFilterPlan.groups`: equality lookups |
| 940 | whose rows are a superset of what a subject may read. Returns |
| 941 | `(records, narrowed)`: |
| 942 | |
| 943 | - `narrowed` True: `records` are exactly the candidate rows, copied and |
| 944 | surfaced the way read_collection_records returns them, in the order |
| 945 | they have in the collection. The caller still runs the permission |
| 946 | engine on each one; this only decides which rows it has to look at. |
| 947 | - `narrowed` False: `records` is every row -- exactly what |
| 948 | read_collection_records returns -- because `groups` is None (the |
| 949 | planner's own fallback), the collection is too large to be in |
| 950 | _RECORDS_CACHE (over DBBASIC_RECORDS_CACHE_MAX_ROWS, so there is no |
| 951 | index), some rule's every lookup is on a field that cannot be indexed |
| 952 | (a `store: extra` field), or anything went wrong while resolving the |
| 953 | lookups. |
| 954 | |
| 955 | Raises exactly what read_collection_records raises, at the same points. |
| 956 | """ |
| 957 | records_ref, extra_names, positions = _plan_snapshot( |
| 958 | collection, groups, base_dir=base_dir, roots=roots |
| 959 | ) |
| 960 | # Copy before surfacing: `records_ref` is the module cache's own list of |
| 961 | # its own dicts (ALIASING SAFETY above) and _surface_extra mutates. |
| 962 | if positions is None: |
| 963 | return [ |
| 964 | _surface_extra(dict(record), extra_names=extra_names) for record in records_ref |
| 965 | ], False |
| 966 | return [ |
| 967 | _surface_extra(dict(records_ref[position]), extra_names=extra_names) |
| 968 | for position in positions |
| 969 | ], True |
| 970 | |
| 971 | |
| 972 | def read_collection_records_and_candidates( |
| 973 | collection: str, |
| 974 | groups: Sequence[Sequence[Sequence[tuple[str, Any]]]] | None, |
| 975 | *, |
| 976 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 977 | roots: Iterable[Path] | None = None, |
| 978 | ) -> tuple[list[dict[str, str]], list[int] | None]: |
| 979 | """Return EVERY record (exactly what read_collection_records returns) |
| 980 | plus the plan's candidate positions into that same list, or None where |
| 981 | read_collection_records_for_plan would not have narrowed. |
| 982 | |
| 983 | For a caller that wants to compare the full scan with the index |
| 984 | (object_server's shadow mode): both views come from the one snapshot, |
| 985 | so a write landing between "read all" and "read candidates" cannot |
| 986 | show up as a difference that is not there. |
| 987 | """ |
| 988 | records_ref, extra_names, positions = _plan_snapshot( |
| 989 | collection, groups, base_dir=base_dir, roots=roots |
| 990 | ) |
| 991 | return [ |
| 992 | _surface_extra(dict(record), extra_names=extra_names) for record in records_ref |
| 993 | ], positions |
| 994 | |
| 995 | |
| 996 | def _plan_snapshot( |
| 997 | collection: str, |
| 998 | groups: Sequence[Sequence[Sequence[tuple[str, Any]]]] | None, |
| 999 | *, |
| 1000 | base_dir: Path | str, |
| 1001 | roots: Iterable[Path] | None, |
| 1002 | ) -> tuple[list[dict[str, str]], set[str], list[int] | None]: |
| 1003 | """(cached records list, extra field names, candidate positions | None). |
| 1004 | |
| 1005 | ONE SNAPSHOT. The rows and the index come from a single _cache_entry |
| 1006 | call: positions are computed from, and only ever applied to, the |
| 1007 | records list returned here. The alternative -- read the rows, then ask |
| 1008 | for an index a moment later -- pairs positions from a newer entry with |
| 1009 | an older list after a concurrent write. The engine would still refuse |
| 1010 | anything not allowed, but rows would go missing for that request. |
| 1011 | |
| 1012 | Same calls in the same order as read_collection_records, so the same |
| 1013 | errors surface at the same points. The returned list is the module |
| 1014 | cache's own: callers copy (see the two public readers above). |
| 1015 | """ |
| 1016 | _ensure_collection_known(collection, base_dir=base_dir, roots=roots) |
| 1017 | path = collection_records_file(collection, base_dir=base_dir) |
| 1018 | _fields, records_ref, id_index_ref = _cache_entry(collection, path) |
| 1019 | extra_names = _extra_field_names(collection, base_dir=base_dir, roots=roots) |
| 1020 | |
| 1021 | positions: list[int] | None = None |
| 1022 | if groups is not None: |
| 1023 | try: |
| 1024 | lookup = _field_index_lookup(path, records_ref, id_index_ref, extra_names) |
| 1025 | if lookup is not None: |
| 1026 | positions = candidate_positions(groups, lookup) |
| 1027 | except Exception: # noqa: BLE001 - an index problem must never change a response |
| 1028 | positions = None |
| 1029 | return records_ref, extra_names, positions |
| 1030 | |
| 1031 | |
| 1032 | def candidate_positions( |
| 1033 | groups: Sequence[Sequence[Sequence[tuple[str, Any]]]], |
| 1034 | buckets_for: Callable[[str], Any], |
| 1035 | ) -> list[int] | None: |
| 1036 | """Resolve a row-filter plan against per-field buckets. |
| 1037 | |
| 1038 | `buckets_for(field)` returns that field's `{value: positions}` mapping |
| 1039 | (anything with `.get`), or None when the field cannot be indexed. |
| 1040 | Returns the ascending positions of every candidate row, or None when |
| 1041 | the plan cannot be narrowed (some group has no option whose every field |
| 1042 | is indexable): the caller then looks at every row. |
| 1043 | |
| 1044 | Per group, the option with the fewest rows is used -- each option alone |
| 1045 | is a superset of what the group can allow (see RowFilterPlan), so this |
| 1046 | choice affects cost only, never the result. Ascending order is what |
| 1047 | keeps a narrowed list in the collection's own row order. |
| 1048 | """ |
| 1049 | chosen: list[Sequence[int]] = [] |
| 1050 | for group in groups: |
| 1051 | best: list[Sequence[int]] | None = None |
| 1052 | best_size = 0 |
| 1053 | for option in group: |
| 1054 | lists: list[Sequence[int]] | None = [] |
| 1055 | for field, values in option: |
| 1056 | buckets = buckets_for(field) |
| 1057 | if buckets is None: |
| 1058 | lists = None |
| 1059 | break |
| 1060 | for value in values: |
| 1061 | found = buckets.get(value) |
| 1062 | if found: |
| 1063 | lists.append(found) |
| 1064 | if lists is None: |
| 1065 | continue |
| 1066 | size = sum(len(found) for found in lists) |
| 1067 | if best is None or size < best_size: |
| 1068 | best, best_size = lists, size |
| 1069 | if best is None: |
| 1070 | return None |
| 1071 | chosen.extend(best) |
| 1072 | |
| 1073 | positions: set[int] = set() |
| 1074 | for found in chosen: |
| 1075 | positions.update(found) |
| 1076 | return sorted(positions) |
| 1077 | |
| 1078 | |
| 1079 | def collection_records_payload( |
| 1080 | collection: str, |
| 1081 | records: list[dict[str, str]], |
| 1082 | *, |
| 1083 | limit: int = DEFAULT_RECORD_LIMIT, |
| 1084 | offset: int = 0, |
| 1085 | ) -> dict[str, Any]: |
| 1086 | """Return the standard paginated record-list payload shape. |
| 1087 | |
| 1088 | Takes a full records list and slices the window out of it here -- |
| 1089 | unlike list_collection_records, which slices before copying. This |
| 1090 | public entry point's contract is "you already have the full list"; |
| 1091 | callers (e.g. object_server's search/permission-filtered list paths) |
| 1092 | rely on that. |
| 1093 | """ |
| 1094 | _validate_page(limit=limit, offset=offset) |
| 1095 | total = len(records) |
| 1096 | window = records[offset:offset + limit] |
| 1097 | return _build_records_payload(collection, window, total=total, limit=limit, offset=offset) |
| 1098 | |
| 1099 | |
| 1100 | def _build_records_payload( |
| 1101 | collection: str, |
| 1102 | window: list[dict[str, str]], |
| 1103 | *, |
| 1104 | total: int, |
| 1105 | limit: int, |
| 1106 | offset: int, |
| 1107 | ) -> dict[str, Any]: |
| 1108 | return { |
| 1109 | "collection": collection, |
| 1110 | "records": window, |
| 1111 | "count": len(window), |
| 1112 | "total": total, |
| 1113 | "limit": limit, |
| 1114 | "offset": offset, |
| 1115 | "has_more": offset + len(window) < total, |
| 1116 | } |
| 1117 | |
| 1118 | |
| 1119 | def get_collection_record( |
| 1120 | collection: str, |
| 1121 | record_id: str, |
| 1122 | *, |
| 1123 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 1124 | roots: Iterable[Path] | None = None, |
| 1125 | ) -> dict[str, Any]: |
| 1126 | """Return one record by its ``id`` column.""" |
| 1127 | _ensure_collection_known(collection, base_dir=base_dir, roots=roots) |
| 1128 | if not validate_record_id(record_id): |
| 1129 | raise InvalidRecordIdError(f"Invalid record id: {record_id}") |
| 1130 | |
| 1131 | extra_names = _extra_field_names(collection, base_dir=base_dir, roots=roots) |
| 1132 | path = collection_records_file(collection, base_dir=base_dir) |
| 1133 | # _fast_record_lookup tries the warm cache, then (append mode, over |
| 1134 | # the cache's row threshold) the id->offset sidecar, before falling |
| 1135 | # back to a full fold -- see its docstring. `existing_row`, when |
| 1136 | # returned, is always already a fresh, independent copy. |
| 1137 | _, exists, existing_row, _, _ = _fast_record_lookup( |
| 1138 | collection, path, record_id, need_row=True |
| 1139 | ) |
| 1140 | if not exists: |
| 1141 | raise RecordNotFoundError(f"Record not found: {collection}/{record_id}") |
| 1142 | |
| 1143 | return _surface_extra(existing_row, extra_names=extra_names) |
| 1144 | |
| 1145 | |
| 1146 | def create_collection_record( |
| 1147 | collection: str, |
| 1148 | record: dict[str, Any], |
| 1149 | *, |
| 1150 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 1151 | roots: Iterable[Path] | None = None, |
| 1152 | actor: str | None = None, |
| 1153 | preserve_read_only: bool = False, |
| 1154 | allow_computed_submission: bool = False, |
| 1155 | record_changes: bool = True, |
| 1156 | ) -> dict[str, str]: |
| 1157 | """Append one record to a collection TSV and return the stored row. |
| 1158 | |
| 1159 | `record_changes=False` skips the change-log entry, and exists for |
| 1160 | exactly one caller shape: a full recompute writing DERIVED rows. A |
| 1161 | rollup target's history is not "who did what" -- it is the source |
| 1162 | collection plus the definition, both of which are still there, so the |
| 1163 | log adds nothing anyone could audit while costing one entry per row |
| 1164 | per pass, forever. One such log reached 944MB describing a collection |
| 1165 | of 1818 rows, and the activity feed that reads every log stopped |
| 1166 | finishing. Do NOT reach for this to make an ordinary write quieter: |
| 1167 | a write nobody can trace is the thing the log exists to prevent. |
| 1168 | |
| 1169 | Every successful write is durably attributed here (universal |
| 1170 | attribution -- every mutation, on every path, emits a record change). |
| 1171 | ``actor`` identifies who/what caused the write; callers that omit it |
| 1172 | are logged as ``"unattributed"`` rather than silently skipped, so gaps |
| 1173 | stay visible instead of disappearing. See object_record_changes for |
| 1174 | the append itself and its recursion note. |
| 1175 | |
| 1176 | ``preserve_read_only``: an ordinary write (client-submitted payload) |
| 1177 | may never set a ``read_only`` field (e.g. a schema's ``created_at``) -- |
| 1178 | the server owns it, per ``_apply_auto_created_at``. A bulk loader |
| 1179 | replaying another system's history (object_import.py) legitimately |
| 1180 | needs to carry that system's own ``created_at`` through instead of |
| 1181 | stamping "now", which is exactly what a hand-typed form must never be |
| 1182 | able to do. Setting this narrows, not removes, the read-only |
| 1183 | protection: a genuinely ``computed`` field (a server-derived formula, |
| 1184 | not just a field the client shouldn't touch) still rejects a |
| 1185 | client-submitted value regardless of this flag -- see |
| 1186 | ``_validate_record_against_schema``. Trusted, explicit, opt-in callers |
| 1187 | only; never wired to an HTTP request payload. |
| 1188 | |
| 1189 | ``allow_computed_submission`` is the narrower sibling ``preserve_read_only`` |
| 1190 | deliberately does not grant: a field marked ``computed`` (e.g. a rollup |
| 1191 | target's metric columns, ``plan/vocabulary/14-rollup-spec.md``) is meant |
| 1192 | to hold a server-derived formula's result, and no HTTP-facing caller |
| 1193 | should ever be able to write one directly. The one legitimate writer is |
| 1194 | the block that owns the derivation itself (the rollup daemon pass |
| 1195 | writing its own computed metric columns into its own target row) -- |
| 1196 | trusted, explicit, opt-in, same posture as ``preserve_read_only``, never |
| 1197 | wired to a request payload. |
| 1198 | """ |
| 1199 | _refuse_write_in_check(collection) |
| 1200 | _ensure_collection_known(collection, base_dir=base_dir, roots=roots) |
| 1201 | extra_names = _extra_field_names(collection, base_dir=base_dir, roots=roots) |
| 1202 | clean = _normalize_record_payload(record, require_id=True) |
| 1203 | record_id = clean["id"] |
| 1204 | if not validate_record_id(record_id): |
| 1205 | raise InvalidRecordIdError(f"Invalid record id: {record_id}") |
| 1206 | submitted_fields = frozenset(clean) |
| 1207 | clean = _apply_schema_defaults(collection, clean, base_dir=base_dir, roots=roots) |
| 1208 | _check_field_storable(clean) |
| 1209 | clean = _apply_auto_created_at(collection, clean, submitted_fields, base_dir=base_dir, roots=roots) |
| 1210 | clean = _apply_computed_fields(collection, clean, base_dir=base_dir, roots=roots) |
| 1211 | _validate_record_against_schema( |
| 1212 | collection, |
| 1213 | clean, |
| 1214 | submitted_fields=submitted_fields, |
| 1215 | base_dir=base_dir, |
| 1216 | roots=roots, |
| 1217 | allow_read_only_submission=preserve_read_only, |
| 1218 | allow_computed_submission=allow_computed_submission, |
| 1219 | ) |
| 1220 | clean = _canonicalize_schema_values(collection, clean, base_dir=base_dir, roots=roots) |
| 1221 | clean = _route_extra(clean, existing_blob={}, extra_names=extra_names) |
| 1222 | |
| 1223 | path = collection_records_file(collection, base_dir=base_dir) |
| 1224 | checks, check_locks, rollup_parents = _write_checks_plan( |
| 1225 | collection, base_dir=base_dir, roots=roots) |
| 1226 | with _check_locks(check_locks, base_dir=base_dir, collection=collection), \ |
| 1227 | _records_file_lock(path): |
| 1228 | # _fast_record_lookup resolves the duplicate check via the |
| 1229 | # cheapest source available: warm cache, then (append mode, over |
| 1230 | # threshold) the id->offset sidecar -- neither of which needs a |
| 1231 | # full fold or a copy of every existing record. `records_ref`/ |
| 1232 | # `id_index_ref` are the module cache's own uncopied objects when |
| 1233 | # sourced from the cache (or a forced full fold below) -- fine to |
| 1234 | # read (the O(1) duplicate check already happened above) or |
| 1235 | # capture in a closure that builds a fresh copy lazily, only if a |
| 1236 | # full rewrite turns out to be needed (see _persist_write's |
| 1237 | # folded_records_fn). Skipping an eager copy of every existing |
| 1238 | # record is what keeps a fast-append create O(1) rather than |
| 1239 | # O(n): an `any(row.get("id") == ... for row in records)` linear |
| 1240 | # scan plus a full deep-copy of every existing record were, |
| 1241 | # together, the dominant cost of a "fast" append in an earlier |
| 1242 | # version of this function -- and, before the sidecar, the O(n) |
| 1243 | # fold itself was the dominant cost above the cache's row |
| 1244 | # threshold. |
| 1245 | # |
| 1246 | # In append mode, "exists" reflects the last-wins-by-id folded |
| 1247 | # view either way (a deleted id is absent, so a create can reuse |
| 1248 | # it -- resurrection), same as classic mode's index, which never |
| 1249 | # indexes a stale/removed row. |
| 1250 | fields, exists, _, records_ref, id_index_ref = _fast_record_lookup( |
| 1251 | collection, path, record_id, need_row=False |
| 1252 | ) |
| 1253 | if exists: |
| 1254 | raise DuplicateRecordIdError(f"Record already exists: {collection}/{record_id}") |
| 1255 | |
| 1256 | # Schema `unique` constraints: checked here, under the lock, against |
| 1257 | # the rows as they are now -- the one place a duplicate check is |
| 1258 | # atomic with the write it guards. Raises before anything is written. |
| 1259 | unique_index = _check_unique_constraints( |
| 1260 | collection, path, record_id=record_id, old_row=None, new_row=clean, |
| 1261 | records_ref=records_ref, base_dir=base_dir, roots=roots, |
| 1262 | ) |
| 1263 | # Schema `locked_checks`: called here, holding their check locks and |
| 1264 | # this file lock, so what they read cannot move before the append. |
| 1265 | if checks: |
| 1266 | _run_locked_checks( |
| 1267 | checks, collection, "create", existing=None, |
| 1268 | record=_surface_extra(dict(clean), extra_names=extra_names), |
| 1269 | base_dir=base_dir, roots=roots, |
| 1270 | ) |
| 1271 | |
| 1272 | merged_fields = _merge_fields(fields, clean) |
| 1273 | |
| 1274 | def build_folded_records() -> list[dict[str, str]]: |
| 1275 | if records_ref is not None: |
| 1276 | records = [dict(existing) for existing in records_ref] |
| 1277 | else: |
| 1278 | # Sidecar-sourced lookup: no full record list was ever |
| 1279 | # built. Only reached on a rare full-rewrite path (new |
| 1280 | # field / pending auto-compaction / mode transition), so |
| 1281 | # paying one full fold here -- unavoidable, a full |
| 1282 | # rewrite needs the complete record set -- doesn't |
| 1283 | # regress the fast steady-state append this whole path |
| 1284 | # exists to keep O(1). |
| 1285 | _, full_records, _ = _cache_entry(collection, path) |
| 1286 | records = [dict(existing) for existing in full_records] |
| 1287 | records.append(clean) |
| 1288 | return records |
| 1289 | |
| 1290 | _persist_write( |
| 1291 | collection, |
| 1292 | path, |
| 1293 | base_dir=base_dir, |
| 1294 | roots=roots, |
| 1295 | prior_fields=fields, |
| 1296 | merged_fields=merged_fields, |
| 1297 | folded_records_fn=build_folded_records, |
| 1298 | delta_row=clean, |
| 1299 | delta_op=OP_UPSERT, |
| 1300 | delta_id=record_id, |
| 1301 | ) |
| 1302 | _commit_unique_index(unique_index, path, record_id=record_id, old_row=None, new_row=clean) |
| 1303 | result = _surface_extra(_project_record(clean, merged_fields), extra_names=extra_names) |
| 1304 | if record_changes: |
| 1305 | object_record_changes.append_record_change( |
| 1306 | collection=collection, |
| 1307 | record_id=record_id, |
| 1308 | action="create", |
| 1309 | before=None, |
| 1310 | after=result, |
| 1311 | actor=actor or "unattributed", |
| 1312 | correlation_id=object_correlation.current_correlation_id(), |
| 1313 | base_dir=base_dir, |
| 1314 | ) |
| 1315 | _recompute_rollups_for_source(collection, [result], base_dir=base_dir, roots=roots, |
| 1316 | parents=rollup_parents) |
| 1317 | return result |
| 1318 | |
| 1319 | |
| 1320 | def update_collection_record( |
| 1321 | collection: str, |
| 1322 | record_id: str, |
| 1323 | changes: dict[str, Any], |
| 1324 | *, |
| 1325 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 1326 | roots: Iterable[Path] | None = None, |
| 1327 | actor: str | None = None, |
| 1328 | transition_subject: object_permissions.PermissionSubject | None = None, |
| 1329 | preserve_read_only: bool = False, |
| 1330 | allow_computed_submission: bool = False, |
| 1331 | expected_rev: str | None = None, |
| 1332 | record_changes: bool = True, |
| 1333 | judged_rev: str | None = None, |
| 1334 | expected_client_rev: str | None = None, |
| 1335 | ) -> dict[str, str]: |
| 1336 | """Update one existing record by id and return the stored row. |
| 1337 | |
| 1338 | See create_collection_record for the attribution contract: every |
| 1339 | successful update is durably attributed, defaulting to |
| 1340 | ``"unattributed"`` when the caller doesn't identify itself. |
| 1341 | |
| 1342 | ``transition_subject`` is optional and only affects schema-declared |
| 1343 | transition guards (see _validate_field_transitions). The HTTP update |
| 1344 | path resolves the request subject once permissions have already run |
| 1345 | and passes it through here; direct library callers (daemon, CLI, |
| 1346 | tests) that don't pass one are trusted callers -- guarded moves are |
| 1347 | still checked for validity, just not for who is making them. |
| 1348 | |
| 1349 | ``preserve_read_only``/``allow_computed_submission`` mirror |
| 1350 | create_collection_record's own flags, same "trusted, explicit, opt-in, |
| 1351 | never wired to a request payload" posture -- an update needs them too, |
| 1352 | e.g. the rollup daemon pass (plan/vocabulary/14-rollup-spec.md) stamping |
| 1353 | a definition's read-only ``last_computed_at`` and a target row's |
| 1354 | computed metric columns on every recompute. |
| 1355 | |
| 1356 | ``expected_rev`` is 63's optimistic-concurrency precondition |
| 1357 | (plan/vocabulary/63-concurrency-spec.md): when supplied, the freshly-read |
| 1358 | row's compute_record_rev is compared against it INSIDE the write lock, |
| 1359 | before any validation or write; a mismatch raises VersionConflictError |
| 1360 | and nothing is written. ``None`` (the default) means last-write-wins, |
| 1361 | exactly as before -- the precondition is opt-in per write, never |
| 1362 | mandatory. Because the check runs after the lock is held and reads the |
| 1363 | same post-lock row every writer serializes behind, two racing updates |
| 1364 | to the same record resolve as "first wins, second sees the changed row |
| 1365 | and 409s" rather than a silent clobber -- see the spec's worked example. |
| 1366 | |
| 1367 | ``expected_client_rev`` is the same precondition for a rev a CLIENT |
| 1368 | sent (``If-Match``): compared, at the same point, against |
| 1369 | client_record_rev of the row under the lock. The record API passes a |
| 1370 | client's value here and never as ``expected_rev``, so an unkeyed guess |
| 1371 | can never be tested by whether a write 409s. |
| 1372 | |
| 1373 | ``judged_rev`` is the server's own precondition, always on when given |
| 1374 | and independent of the concurrency flag: the compute_record_rev of the |
| 1375 | row a caller's permission gates were decided on, before this lock. A |
| 1376 | row under the lock that differs raises RecordChangedError and nothing |
| 1377 | is written (see that class). |
| 1378 | """ |
| 1379 | _refuse_write_in_check(collection) |
| 1380 | _ensure_collection_known(collection, base_dir=base_dir, roots=roots) |
| 1381 | if not validate_record_id(record_id): |
| 1382 | raise InvalidRecordIdError(f"Invalid record id: {record_id}") |
| 1383 | extra_names = _extra_field_names(collection, base_dir=base_dir, roots=roots) |
| 1384 | |
| 1385 | clean = _normalize_record_payload(changes, require_id=False) |
| 1386 | if "id" in clean and clean["id"] != record_id: |
| 1387 | raise InvalidRecordPayloadError("Record id cannot be changed") |
| 1388 | submitted_fields = frozenset(clean) |
| 1389 | |
| 1390 | path = collection_records_file(collection, base_dir=base_dir) |
| 1391 | checks, check_locks, rollup_parents = _write_checks_plan( |
| 1392 | collection, base_dir=base_dir, roots=roots) |
| 1393 | with _check_locks(check_locks, base_dir=base_dir, collection=collection), \ |
| 1394 | _records_file_lock(path): |
| 1395 | # See the matching comment in create_collection_record: this |
| 1396 | # resolves via warm cache, then (append mode, over threshold) the |
| 1397 | # id->offset sidecar, before a full fold -- see |
| 1398 | # _fast_record_lookup. `existing_row` is always already a fresh, |
| 1399 | # independent copy. When sourced from the cache (or a forced full |
| 1400 | # fold below), id_index_ref is first-occurrence-wins |
| 1401 | # (_build_id_index), same as the linear scan this replaces, so |
| 1402 | # this changes nothing about WHICH row a duplicate-id file |
| 1403 | # resolves to. |
| 1404 | fields, exists, existing_row, records_ref, id_index_ref = _fast_record_lookup( |
| 1405 | collection, path, record_id, need_row=True |
| 1406 | ) |
| 1407 | if not exists: |
| 1408 | raise RecordNotFoundError(f"Record not found: {collection}/{record_id}") |
| 1409 | |
| 1410 | existing_blob = _parse_extra_blob(existing_row.get(EXTRA_FIELD)) |
| 1411 | existing = _surface_extra(existing_row, extra_names=extra_names) |
| 1412 | |
| 1413 | # 63: the precondition, checked against the row just read under the |
| 1414 | # lock (the freshest possible state -- not the caller's earlier |
| 1415 | # pre-lock read, which may be stale by now). `existing` is the same |
| 1416 | # surfaced representation get_collection_record returns and the read |
| 1417 | # side fingerprints, so the two `_rev` values are computed over |
| 1418 | # identical inputs. Runs before any validation/write: a mismatch is |
| 1419 | # a clean no-op. |
| 1420 | if expected_rev is not None and compute_record_rev(existing) != expected_rev: |
| 1421 | raise VersionConflictError( |
| 1422 | f"Record {collection}/{record_id} has changed since it was read " |
| 1423 | f"(expected _rev {expected_rev!r})." |
| 1424 | ) |
| 1425 | if expected_client_rev is not None and not _client_rev_matches( |
| 1426 | collection, existing, expected_client_rev, base_dir=base_dir): |
| 1427 | raise VersionConflictError( |
| 1428 | f"Record {collection}/{record_id} has changed since it was read " |
| 1429 | f"(expected _rev {expected_client_rev!r})." |
| 1430 | ) |
| 1431 | _refuse_unjudged_row(collection, record_id, existing, judged_rev) |
| 1432 | |
| 1433 | updated = dict(existing) |
| 1434 | updated.update(clean) |
| 1435 | updated["id"] = record_id |
| 1436 | updated = _apply_computed_fields(collection, updated, base_dir=base_dir, roots=roots) |
| 1437 | _validate_record_against_schema( |
| 1438 | collection, |
| 1439 | updated, |
| 1440 | submitted_fields=submitted_fields, |
| 1441 | base_dir=base_dir, |
| 1442 | roots=roots, |
| 1443 | allow_read_only_submission=preserve_read_only, |
| 1444 | allow_computed_submission=allow_computed_submission, |
| 1445 | ) |
| 1446 | _check_field_storable(updated) |
| 1447 | _validate_field_transitions( |
| 1448 | collection, |
| 1449 | existing, |
| 1450 | updated, |
| 1451 | base_dir=base_dir, |
| 1452 | roots=roots, |
| 1453 | subject=transition_subject, |
| 1454 | ) |
| 1455 | updated = _canonicalize_schema_values( |
| 1456 | collection, updated, base_dir=base_dir, roots=roots |
| 1457 | ) |
| 1458 | # Schema `locked_when`: judged here, against the row just read under |
| 1459 | # the lock, not against whatever an earlier gate read. Before |
| 1460 | # _route_extra, while a `store: extra` field is still a top-level |
| 1461 | # value that can be compared like any other. |
| 1462 | lock_rules = _record_lock_rules(collection, base_dir=base_dir, roots=roots) |
| 1463 | if lock_rules: |
| 1464 | _check_record_locks( |
| 1465 | lock_rules, collection, record_id, existing, updated, |
| 1466 | submitted=submitted_fields, base_dir=base_dir, roots=roots, |
| 1467 | ) |
| 1468 | updated = _route_extra(updated, existing_blob=existing_blob, extra_names=extra_names) |
| 1469 | # See the matching comment in create_collection_record. An update |
| 1470 | # that leaves a record's own key alone is never refused, so rows that |
| 1471 | # were duplicates before a constraint was declared stay editable. |
| 1472 | unique_index = _check_unique_constraints( |
| 1473 | collection, path, record_id=record_id, old_row=existing_row, new_row=updated, |
| 1474 | records_ref=records_ref, base_dir=base_dir, roots=roots, |
| 1475 | ) |
| 1476 | # See the matching comment in create_collection_record. `existing` |
| 1477 | # is the row read under this lock, not a hook's earlier read. |
| 1478 | if checks: |
| 1479 | _run_locked_checks( |
| 1480 | checks, collection, "update", existing=existing, |
| 1481 | record=_surface_extra(dict(updated), extra_names=extra_names), |
| 1482 | base_dir=base_dir, roots=roots, |
| 1483 | ) |
| 1484 | merged_fields = _merge_fields(fields, updated) |
| 1485 | |
| 1486 | def build_folded_records() -> list[dict[str, str]]: |
| 1487 | if records_ref is not None: |
| 1488 | records = [dict(existing_row) for existing_row in records_ref] |
| 1489 | records[id_index_ref[record_id]] = updated |
| 1490 | else: |
| 1491 | # Sidecar-sourced lookup -- see the matching comment in |
| 1492 | # create_collection_record's build_folded_records. |
| 1493 | _, full_records, full_id_index = _cache_entry(collection, path) |
| 1494 | records = [dict(existing_row) for existing_row in full_records] |
| 1495 | records[full_id_index[record_id]] = updated |
| 1496 | return records |
| 1497 | |
| 1498 | _persist_write( |
| 1499 | collection, |
| 1500 | path, |
| 1501 | base_dir=base_dir, |
| 1502 | roots=roots, |
| 1503 | prior_fields=fields, |
| 1504 | merged_fields=merged_fields, |
| 1505 | folded_records_fn=build_folded_records, |
| 1506 | delta_row=updated, |
| 1507 | delta_op=OP_UPSERT, |
| 1508 | delta_id=record_id, |
| 1509 | ) |
| 1510 | _commit_unique_index( |
| 1511 | unique_index, path, record_id=record_id, old_row=existing_row, new_row=updated |
| 1512 | ) |
| 1513 | result = _surface_extra(_project_record(updated, merged_fields), extra_names=extra_names) |
| 1514 | if record_changes: |
| 1515 | object_record_changes.append_record_change( |
| 1516 | collection=collection, |
| 1517 | record_id=record_id, |
| 1518 | action="update", |
| 1519 | before=existing, |
| 1520 | after=result, |
| 1521 | actor=actor or "unattributed", |
| 1522 | correlation_id=object_correlation.current_correlation_id(), |
| 1523 | base_dir=base_dir, |
| 1524 | ) |
| 1525 | _recompute_rollups_for_source( |
| 1526 | collection, [existing, result], base_dir=base_dir, roots=roots, |
| 1527 | parents=rollup_parents, |
| 1528 | ) |
| 1529 | return result |
| 1530 | |
| 1531 | |
| 1532 | def delete_collection_record( |
| 1533 | collection: str, |
| 1534 | record_id: str, |
| 1535 | *, |
| 1536 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 1537 | roots: Iterable[Path] | None = None, |
| 1538 | actor: str | None = None, |
| 1539 | record_changes: bool = True, |
| 1540 | judged_rev: str | None = None, |
| 1541 | ) -> dict[str, str]: |
| 1542 | """Delete one existing record by id and return the removed row. |
| 1543 | |
| 1544 | See create_collection_record for the attribution contract: every |
| 1545 | successful delete is durably attributed, defaulting to |
| 1546 | ``"unattributed"`` when the caller doesn't identify itself. |
| 1547 | ``judged_rev``: as update_collection_record's. |
| 1548 | """ |
| 1549 | _refuse_write_in_check(collection) |
| 1550 | _ensure_collection_known(collection, base_dir=base_dir, roots=roots) |
| 1551 | if not validate_record_id(record_id): |
| 1552 | raise InvalidRecordIdError(f"Invalid record id: {record_id}") |
| 1553 | |
| 1554 | path = collection_records_file(collection, base_dir=base_dir) |
| 1555 | checks, check_locks, rollup_parents = _write_checks_plan( |
| 1556 | collection, base_dir=base_dir, roots=roots) |
| 1557 | with _check_locks(check_locks, base_dir=base_dir, collection=collection), \ |
| 1558 | _records_file_lock(path): |
| 1559 | # See the matching comment in create_collection_record. |
| 1560 | # `existing_row` is already a fresh, independent copy -- safe to |
| 1561 | # hand back across the API as-is. |
| 1562 | fields, exists, existing_row, records_ref, id_index_ref = _fast_record_lookup( |
| 1563 | collection, path, record_id, need_row=True |
| 1564 | ) |
| 1565 | if not exists: |
| 1566 | raise RecordNotFoundError(f"Record not found: {collection}/{record_id}") |
| 1567 | |
| 1568 | removed = existing_row |
| 1569 | if judged_rev is not None: |
| 1570 | _refuse_unjudged_row( |
| 1571 | collection, record_id, |
| 1572 | _surface_extra(dict(removed), extra_names=_extra_field_names( |
| 1573 | collection, base_dir=base_dir, roots=roots)), |
| 1574 | judged_rev, |
| 1575 | ) |
| 1576 | # Schema `locked_when`: a settled record is not removed either. See |
| 1577 | # the matching comment in update_collection_record. |
| 1578 | lock_rules = _record_lock_rules(collection, base_dir=base_dir, roots=roots) |
| 1579 | if lock_rules: |
| 1580 | _check_record_locks( |
| 1581 | lock_rules, collection, record_id, |
| 1582 | _surface_extra( |
| 1583 | dict(removed), |
| 1584 | extra_names=_extra_field_names(collection, base_dir=base_dir, roots=roots), |
| 1585 | ), |
| 1586 | None, submitted=frozenset(), base_dir=base_dir, roots=roots, |
| 1587 | ) |
| 1588 | # A delete cannot violate a `unique` constraint, but it frees a key: |
| 1589 | # if this collection's unique index is current it is kept current |
| 1590 | # (None when there are no constraints, or no current index to keep). |
| 1591 | unique_index = _check_unique_constraints( |
| 1592 | collection, path, record_id=record_id, old_row=removed, new_row=None, |
| 1593 | records_ref=records_ref, base_dir=base_dir, roots=roots, |
| 1594 | ) |
| 1595 | if checks: |
| 1596 | surfaced = _surface_extra( |
| 1597 | dict(removed), |
| 1598 | extra_names=_extra_field_names(collection, base_dir=base_dir, roots=roots), |
| 1599 | ) |
| 1600 | _run_locked_checks( |
| 1601 | checks, collection, "delete", existing=surfaced, record=surfaced, |
| 1602 | base_dir=base_dir, roots=roots, |
| 1603 | ) |
| 1604 | |
| 1605 | def build_folded_records() -> list[dict[str, str]]: |
| 1606 | if records_ref is not None: |
| 1607 | records = [dict(existing_row) for existing_row in records_ref] |
| 1608 | records.pop(id_index_ref[record_id]) |
| 1609 | else: |
| 1610 | # Sidecar-sourced lookup -- see the matching comment in |
| 1611 | # create_collection_record's build_folded_records. |
| 1612 | _, full_records, full_id_index = _cache_entry(collection, path) |
| 1613 | records = [dict(existing_row) for existing_row in full_records] |
| 1614 | records.pop(full_id_index[record_id]) |
| 1615 | return records |
| 1616 | |
| 1617 | _persist_write( |
| 1618 | collection, |
| 1619 | path, |
| 1620 | base_dir=base_dir, |
| 1621 | roots=roots, |
| 1622 | prior_fields=fields, |
| 1623 | merged_fields=fields, |
| 1624 | folded_records_fn=build_folded_records, |
| 1625 | delta_row=None, |
| 1626 | delta_op=OP_DELETE, |
| 1627 | delta_id=record_id, |
| 1628 | ) |
| 1629 | _commit_unique_index(unique_index, path, record_id=record_id, old_row=removed, new_row=None) |
| 1630 | result = _project_record(removed, fields) |
| 1631 | if record_changes: |
| 1632 | object_record_changes.append_record_change( |
| 1633 | collection=collection, |
| 1634 | record_id=record_id, |
| 1635 | action="delete", |
| 1636 | before=result, |
| 1637 | after=None, |
| 1638 | actor=actor or "unattributed", |
| 1639 | correlation_id=object_correlation.current_correlation_id(), |
| 1640 | base_dir=base_dir, |
| 1641 | ) |
| 1642 | _recompute_rollups_for_source(collection, [result], base_dir=base_dir, roots=roots, |
| 1643 | parents=rollup_parents) |
| 1644 | return result |
| 1645 | |
| 1646 | |
| 1647 | def find_unique_violations( |
| 1648 | collection: str, |
| 1649 | *, |
| 1650 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 1651 | roots: Iterable[Path] | None = None, |
| 1652 | ) -> list[dict[str, Any]]: |
| 1653 | """List the keys of the collection's schema `unique` constraints that |
| 1654 | more than one record already holds. |
| 1655 | |
| 1656 | Declaring a constraint over existing data does not clean it: rows that |
| 1657 | were duplicates stay, and only NEW holders of a key are refused (see |
| 1658 | _check_unique_constraints). This is the report to run before declaring |
| 1659 | one, or after, to see what a person still has to merge or delete. Each |
| 1660 | entry is {"fields", "scope", "values": {field: compared value}, "ids": |
| 1661 | [record ids, in row order]}; `values` are as compared (trimmed, and |
| 1662 | case-folded where the constraint says ignore_case), not as stored. |
| 1663 | Read-only, takes no lock, [] when there is nothing to report. |
| 1664 | """ |
| 1665 | _ensure_collection_known(collection, base_dir=base_dir, roots=roots) |
| 1666 | constraints = _unique_constraints(collection, base_dir=base_dir, roots=roots) |
| 1667 | if not constraints: |
| 1668 | return [] |
| 1669 | records = _cached_records_ref(collection, base_dir=base_dir) |
| 1670 | violations: list[dict[str, Any]] = [] |
| 1671 | for constraint in constraints: |
| 1672 | names = [*constraint["fields"], *(constraint.get("scope") or [])] |
| 1673 | for key, held in _build_unique_map(constraint, records).items(): |
| 1674 | if not isinstance(held, tuple): |
| 1675 | continue |
| 1676 | parts = key if isinstance(key, tuple) else (key,) |
| 1677 | violations.append({ |
| 1678 | "fields": list(constraint["fields"]), |
| 1679 | "scope": list(constraint.get("scope") or []), |
| 1680 | "values": dict(zip(names, parts)), |
| 1681 | "ids": list(held), |
| 1682 | }) |
| 1683 | return violations |
| 1684 | |
| 1685 | |
| 1686 | def compact_collection( |
| 1687 | collection: str, |
| 1688 | *, |
| 1689 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 1690 | roots: Iterable[Path] | None = None, |
| 1691 | ) -> dict[str, Any]: |
| 1692 | """Fold an append-mode collection's records file to its live rows only. |
| 1693 | |
| 1694 | Rewrites atomically via the same _write_collection_records path a |
| 1695 | plain write uses (temp file + replace), under the collection's file |
| 1696 | lock, keeping the `_op` column (every row becomes an upsert). Callable |
| 1697 | directly (this function), via POST /admin/collections/{collection}/ |
| 1698 | compact (object_server.py), or automatically: Auto-compaction |
| 1699 | (_maybe_flag_auto_compact) causes a collection's next ordinary write |
| 1700 | to perform this same rewrite instead of a plain append, and the |
| 1701 | daemon's process_compactions (object_daemon.py) polls append_ |
| 1702 | collection_stats and compacts any collection over its bloat/row |
| 1703 | thresholds on a timer (see docs/append-only-storage-design.md |
| 1704 | Compaction: "run on a schedule or when the superseded-row ratio |
| 1705 | passes a threshold — never inline in a request"). This function can |
| 1706 | also be called directly at any time, including on a classic-mode or |
| 1707 | never-written collection, where it is a correctly-reported no-op. |
| 1708 | |
| 1709 | Returns {"rows_before", "rows_after", "bytes_before", "bytes_after"} |
| 1710 | (row counts are physical rows on disk before/after; for a collection |
| 1711 | not currently in append physical format, before == after). |
| 1712 | """ |
| 1713 | _ensure_collection_known(collection, base_dir=base_dir, roots=roots) |
| 1714 | path = collection_records_file(collection, base_dir=base_dir) |
| 1715 | |
| 1716 | with _records_file_lock(path): |
| 1717 | try: |
| 1718 | bytes_before = path.stat().st_size |
| 1719 | except OSError: |
| 1720 | bytes_before = 0 |
| 1721 | |
| 1722 | physical_header = _physical_header(path) |
| 1723 | if not physical_header or physical_header[0] != OP_FIELD: |
| 1724 | rows_before = len(_read_collection_records(collection, base_dir=base_dir)) |
| 1725 | return { |
| 1726 | "rows_before": rows_before, |
| 1727 | "rows_after": rows_before, |
| 1728 | "bytes_before": bytes_before, |
| 1729 | "bytes_after": bytes_before, |
| 1730 | } |
| 1731 | |
| 1732 | with path.open(newline="") as handle: |
| 1733 | text = handle.read() |
| 1734 | folded_records, physical_row_count = _parse_append_body(collection, text, physical_header) |
| 1735 | logical_fields = physical_header[1:] |
| 1736 | |
| 1737 | _write_collection_records( |
| 1738 | collection, path, physical_header, folded_records, cache_fields=logical_fields |
| 1739 | ) |
| 1740 | _PENDING_COMPACTION.discard(str(path.resolve(strict=False))) |
| 1741 | _discard_oidx(path) |
| 1742 | |
| 1743 | bytes_after = path.stat().st_size |
| 1744 | return { |
| 1745 | "rows_before": physical_row_count, |
| 1746 | "rows_after": len(folded_records), |
| 1747 | "bytes_before": bytes_before, |
| 1748 | "bytes_after": bytes_after, |
| 1749 | } |
| 1750 | |
| 1751 | |
| 1752 | def prune_collection_records( |
| 1753 | collection: str, |
| 1754 | *, |
| 1755 | keep_newer_than: str, |
| 1756 | timestamp_field: str = "created_at", |
| 1757 | keep_last: int | None = None, |
| 1758 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 1759 | roots: Iterable[Path] | None = None, |
| 1760 | ) -> dict[str, Any]: |
| 1761 | """Retention / rotation: drop rows whose ``timestamp_field`` is strictly |
| 1762 | older than ``keep_newer_than`` (an ISO-8601 string), rewriting the file to |
| 1763 | only the kept rows in ONE atomic pass (temp + replace, under the file lock) |
| 1764 | -- the same rewrite path compaction uses. |
| 1765 | |
| 1766 | This is the tool for high-volume append-mode event logs (page_views) where |
| 1767 | id-fold compaction cannot help: every row is a distinct event, nothing is |
| 1768 | superseded, so the only way to bound the file is to age rows out. A row with |
| 1769 | a missing or unparseable timestamp is KEPT (never delete data we can't |
| 1770 | date). Only meaningful for append-format collections; a classic-mode or |
| 1771 | never-written collection is a correctly-reported no-op. |
| 1772 | |
| 1773 | ``keep_last`` additionally caps the row COUNT, keeping the newest N after |
| 1774 | the time filter. Time alone does not bound a log: a retention window says |
| 1775 | how far back to look, not how much can arrive inside it, so a traffic |
| 1776 | spike (or a bot storm) can fill a disk without aging a single row out. |
| 1777 | Small machines need the second bound, and a bound nobody set is a bound |
| 1778 | that fails on the worst day rather than an ordinary one. |
| 1779 | |
| 1780 | Returns ``{"rows_before", "rows_after", "removed", "pruned"}``. |
| 1781 | |
| 1782 | A collection whose schema declares ``locked_when`` is refused |
| 1783 | (ValueError), before anything is read or written. The rewrite removes |
| 1784 | rows without passing each through delete_collection_record, so the |
| 1785 | lock check never ran: pointed at such a collection, this aged a posted |
| 1786 | or approved record out like a page view. Its one caller is the |
| 1787 | page_views retention pass (object_daemon.process_analytics_retention), |
| 1788 | and a collection that can hold settled records is not a log; "nobody |
| 1789 | is exempt" (_check_record_locks) has no retention exception. |
| 1790 | |
| 1791 | For the same reason a collection that a schema's ``locked_checks`` |
| 1792 | guards, or reads, is refused: removing a refund's payment, or an |
| 1793 | invoice's line, by retention would move a ceiling no check was asked |
| 1794 | about. |
| 1795 | """ |
| 1796 | _refuse_write_in_check(collection) |
| 1797 | _ensure_collection_known(collection, base_dir=base_dir, roots=roots) |
| 1798 | if _record_lock_rules(collection, base_dir=base_dir, roots=roots): |
| 1799 | raise ValueError( |
| 1800 | f"{collection} declares locked_when, so its records can be settled; " |
| 1801 | f"retention does not remove records from it" |
| 1802 | ) |
| 1803 | check_locks, _parents = _write_plan(collection, base_dir=base_dir, roots=roots) |
| 1804 | if check_locks or _locked_check_specs(collection, base_dir=base_dir, roots=roots): |
| 1805 | raise ValueError( |
| 1806 | f"{collection} is guarded or read by a locked check " |
| 1807 | f"({', '.join(check_locks) or collection}); retention does not remove records from it" |
| 1808 | ) |
| 1809 | path = collection_records_file(collection, base_dir=base_dir) |
| 1810 | |
| 1811 | with _records_file_lock(path): |
| 1812 | physical_header = _physical_header(path) |
| 1813 | if not physical_header or physical_header[0] != OP_FIELD: |
| 1814 | live = len(_read_collection_records(collection, base_dir=base_dir)) |
| 1815 | return {"rows_before": live, "rows_after": live, "removed": 0, "pruned": False} |
| 1816 | |
| 1817 | with path.open(newline="") as handle: |
| 1818 | text = handle.read() |
| 1819 | folded_records, _physical_row_count = _parse_append_body(collection, text, physical_header) |
| 1820 | logical_fields = physical_header[1:] |
| 1821 | |
| 1822 | cutoff = str(keep_newer_than) |
| 1823 | |
| 1824 | def _keep(record: dict[str, str]) -> bool: |
| 1825 | stamp = str(record.get(timestamp_field) or "") |
| 1826 | return True if not stamp else stamp >= cutoff |
| 1827 | |
| 1828 | kept = [record for record in folded_records if _keep(record)] |
| 1829 | if keep_last is not None and keep_last >= 0 and len(kept) > keep_last: |
| 1830 | # Newest N. The append log is written in arrival order, so the tail |
| 1831 | # IS the newest -- no sort, which matters because this runs against |
| 1832 | # the largest file the server owns. |
| 1833 | kept = kept[len(kept) - keep_last:] |
| 1834 | removed = len(folded_records) - len(kept) |
| 1835 | if removed == 0: |
| 1836 | return { |
| 1837 | "rows_before": len(folded_records), |
| 1838 | "rows_after": len(folded_records), |
| 1839 | "removed": 0, |
| 1840 | "pruned": False, |
| 1841 | } |
| 1842 | |
| 1843 | _write_collection_records( |
| 1844 | collection, path, physical_header, kept, cache_fields=logical_fields |
| 1845 | ) |
| 1846 | _PENDING_COMPACTION.discard(str(path.resolve(strict=False))) |
| 1847 | _discard_oidx(path) |
| 1848 | return { |
| 1849 | "rows_before": len(folded_records), |
| 1850 | "rows_after": len(kept), |
| 1851 | "removed": removed, |
| 1852 | "pruned": True, |
| 1853 | } |
| 1854 | |
| 1855 | |
| 1856 | def append_collection_stats( |
| 1857 | collection: str, |
| 1858 | *, |
| 1859 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 1860 | roots: Iterable[Path] | None = None, |
| 1861 | allow_fold: bool = True, |
| 1862 | ) -> dict[str, Any] | None: |
| 1863 | """Return compaction-observability stats for one collection, or None |
| 1864 | when it is not currently in append storage mode (docs/storage-modes.md |
| 1865 | "Compaction"). |
| 1866 | |
| 1867 | Returns: |
| 1868 | {"collection", "storage": "append", "physical_rows", "live_rows", |
| 1869 | "dead_rows", "bloat_ratio" (dead_rows / max(live_rows, 1), rounded |
| 1870 | 3dp), "file_bytes", "sidecar_present", "compaction_flagged"} |
| 1871 | |
| 1872 | Cheapest-source-first, same doctrine as _fast_record_lookup's point-op |
| 1873 | resolution (docs/append-only-storage-design.md Sidecars), tried in |
| 1874 | order and combined -- either can answer `live_rows`, but only the |
| 1875 | sidecar can answer `physical_rows` short of a fold: |
| 1876 | |
| 1877 | 1. A warm _RECORDS_CACHE hit (_peek_records_cache) answers |
| 1878 | `live_rows` for free -- it's already the folded record count, no |
| 1879 | I/O at all. |
| 1880 | 2. The id->offset sidecar (.records.oidx), read directly via |
| 1881 | _load_oidx_body -- a "pure line-count read" as opposed to a |
| 1882 | records.tsv parse: one line per physical row was written when |
| 1883 | that row was appended (OIDX_FILE's format), so the sidecar's own |
| 1884 | body length IS `physical_rows` without touching records.tsv at |
| 1885 | all, and the same read's last-wins fold gives `live_rows` too |
| 1886 | (used only when tier 1 didn't already answer it). Deliberately |
| 1887 | narrower than the hot-path loader _load_oidx: this never triggers |
| 1888 | a catch-up scan or a from-scratch rebuild when the sidecar is |
| 1889 | stale or missing (`covered_bytes` short of the file's current |
| 1890 | size, wrong header inode, or absent) -- an observability call |
| 1891 | should never be the reason records.tsv gets scanned; it just |
| 1892 | doesn't answer from this tier, and falls through to tier 3 (or |
| 1893 | the estimated shortcut below) instead. |
| 1894 | 3. Neither tier answered both numbers: a full fold via |
| 1895 | _parse_append_body -- the same O(file) cost compact_collection |
| 1896 | itself pays to read the file (docs/storage-modes.md: "cold reads |
| 1897 | of an append file cost ~1.6x a classic parse"). This is the ONLY |
| 1898 | expensive path in this function, and only runs when `allow_fold` |
| 1899 | is True (the default for direct/CLI callers, and for the daemon's |
| 1900 | polling pass, where an occasional full fold is an acceptable |
| 1901 | cost against an interval timer). Callers that must never pay it |
| 1902 | -- GET /admin/storage (object_server.py), which must stay O(1) |
| 1903 | regardless of any one collection's cache/sidecar state -- pass |
| 1904 | allow_fold=False and get an {"estimated": True, "physical_rows": |
| 1905 | None, "live_rows": None, "dead_rows": None, "bloat_ratio": None} |
| 1906 | entry instead (still with a real, cheap `file_bytes` from the |
| 1907 | initial stat). |
| 1908 | |
| 1909 | A collection whose records.tsv doesn't exist yet (schema declared |
| 1910 | "append" but never written) short-circuits to an honest all-zero |
| 1911 | result before any of the above -- that check (`path.exists()`, done as |
| 1912 | part of the initial stat) is itself O(1), so it's never worth |
| 1913 | representing as "estimated". |
| 1914 | """ |
| 1915 | _ensure_collection_known(collection, base_dir=base_dir, roots=roots) |
| 1916 | mode = _collection_storage_mode(collection, base_dir=base_dir, roots=roots) |
| 1917 | if mode != object_schemas.STORAGE_APPEND: |
| 1918 | return None |
| 1919 | |
| 1920 | path = collection_records_file(collection, base_dir=base_dir) |
| 1921 | try: |
| 1922 | st = path.stat() |
| 1923 | file_bytes = st.st_size |
| 1924 | data_ino: int | None = st.st_ino |
| 1925 | except OSError: |
| 1926 | file_bytes = 0 |
| 1927 | data_ino = None |
| 1928 | |
| 1929 | cache_key = str(path.resolve(strict=False)) |
| 1930 | sidecar_path = _oidx_path(path) |
| 1931 | sidecar_present = sidecar_path.exists() |
| 1932 | compaction_flagged = cache_key in _PENDING_COMPACTION |
| 1933 | |
| 1934 | if data_ino is None: |
| 1935 | # No records.tsv at all -- a schema can declare "append" storage |
| 1936 | # before its collection is ever written. Nothing to fold, sidecar |
| 1937 | # or otherwise; report honest zeros rather than routing this |
| 1938 | # through the fold/estimate machinery below. |
| 1939 | return { |
| 1940 | "collection": collection, |
| 1941 | "storage": object_schemas.STORAGE_APPEND, |
| 1942 | "physical_rows": 0, |
| 1943 | "live_rows": 0, |
| 1944 | "dead_rows": 0, |
| 1945 | "bloat_ratio": 0.0, |
| 1946 | "file_bytes": 0, |
| 1947 | "sidecar_present": sidecar_present, |
| 1948 | "compaction_flagged": compaction_flagged, |
| 1949 | } |
| 1950 | |
| 1951 | live_rows: int | None = None |
| 1952 | physical_rows: int | None = None |
| 1953 | |
| 1954 | peeked = _peek_records_cache(path) |
| 1955 | if peeked is not None: |
| 1956 | live_rows = len(peeked[1]) |
| 1957 | |
| 1958 | if sidecar_present: |
| 1959 | header_ino = _read_oidx_header(sidecar_path) |
| 1960 | if header_ino == data_ino: |
| 1961 | loaded = _load_oidx_body(sidecar_path) |
| 1962 | if loaded is not None: |
| 1963 | body_dict, body_covered, body_physical = loaded |
| 1964 | covered = ( |
| 1965 | body_covered if body_covered is not None else _records_header_length(path) |
| 1966 | ) |
| 1967 | if covered == file_bytes: |
| 1968 | physical_rows = body_physical |
| 1969 | if live_rows is None: |
| 1970 | live_rows = len(body_dict) |
| 1971 | |
| 1972 | if physical_rows is None or live_rows is None: |
| 1973 | if not allow_fold: |
| 1974 | return { |
| 1975 | "collection": collection, |
| 1976 | "storage": object_schemas.STORAGE_APPEND, |
| 1977 | "physical_rows": None, |
| 1978 | "live_rows": None, |
| 1979 | "dead_rows": None, |
| 1980 | "bloat_ratio": None, |
| 1981 | "file_bytes": file_bytes, |
| 1982 | "sidecar_present": sidecar_present, |
| 1983 | "compaction_flagged": compaction_flagged, |
| 1984 | "estimated": True, |
| 1985 | } |
| 1986 | |
| 1987 | physical_header = _physical_header(path) |
| 1988 | if not physical_header or physical_header[0] != OP_FIELD: |
| 1989 | # Exists on disk but never written in append physical format |
| 1990 | # (e.g. an empty file) -- nothing to fold. |
| 1991 | physical_rows = 0 |
| 1992 | live_rows = 0 |
| 1993 | else: |
| 1994 | with path.open(newline="") as handle: |
| 1995 | text = handle.read() |
| 1996 | folded_records, physical_row_count = _parse_append_body(collection, text, physical_header) |
| 1997 | physical_rows = physical_row_count |
| 1998 | live_rows = len(folded_records) |
| 1999 | |
| 2000 | dead_rows = max(physical_rows - live_rows, 0) |
| 2001 | bloat_ratio = round(dead_rows / max(live_rows, 1), 3) |
| 2002 | return { |
| 2003 | "collection": collection, |
| 2004 | "storage": object_schemas.STORAGE_APPEND, |
| 2005 | "physical_rows": physical_rows, |
| 2006 | "live_rows": live_rows, |
| 2007 | "dead_rows": dead_rows, |
| 2008 | "bloat_ratio": bloat_ratio, |
| 2009 | "file_bytes": file_bytes, |
| 2010 | "sidecar_present": sidecar_present, |
| 2011 | "compaction_flagged": compaction_flagged, |
| 2012 | } |
| 2013 | |
| 2014 | |
| 2015 | def list_append_collection_stats( |
| 2016 | *, |
| 2017 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 2018 | roots: Iterable[Path] | None = None, |
| 2019 | allow_fold: bool = True, |
| 2020 | ) -> list[dict[str, Any]]: |
| 2021 | """Return append_collection_stats() for every collection whose schema |
| 2022 | currently declares "storage": "append", sorted by collection name. |
| 2023 | |
| 2024 | Discovery (object_schemas.list_append_storage_collections) is cheap |
| 2025 | regardless of how many collections exist on disk: it globs the schemas |
| 2026 | directory and loads each manual schema through the same mtime/size- |
| 2027 | keyed cache every other schema read in this codebase already goes |
| 2028 | through, never touching records.tsv. A collection whose schema |
| 2029 | disappears between that listing and its own stats call (a benign race |
| 2030 | under concurrent schema edits) is skipped rather than raising -- same |
| 2031 | tolerance _ensure_collection_known's callers generally apply to |
| 2032 | concurrent schema/collection changes. |
| 2033 | """ |
| 2034 | names = object_schemas.list_append_storage_collections(base_dir=base_dir) |
| 2035 | stats: list[dict[str, Any]] = [] |
| 2036 | for name in names: |
| 2037 | try: |
| 2038 | entry = append_collection_stats( |
| 2039 | name, base_dir=base_dir, roots=roots, allow_fold=allow_fold |
| 2040 | ) |
| 2041 | except ( |
| 2042 | object_collections.InvalidCollectionNameError, |
| 2043 | object_collections.CollectionNotFoundError, |
| 2044 | ): |
| 2045 | continue |
| 2046 | if entry is not None: |
| 2047 | stats.append(entry) |
| 2048 | return stats |
| 2049 | |
| 2050 | |
| 2051 | def collection_records_file(collection: str, base_dir: Path | str = DEFAULT_DATA_DIR) -> Path: |
| 2052 | """Return the validated TSV file path for a collection.""" |
| 2053 | if not object_collections.validate_collection_name(collection): |
| 2054 | raise object_collections.InvalidCollectionNameError( |
| 2055 | f"Invalid collection name: {collection}" |
| 2056 | ) |
| 2057 | |
| 2058 | root = Path(base_dir) / COLLECTIONS_DIR |
| 2059 | path = root / collection / RECORDS_FILE |
| 2060 | if _no_link_below_root(path): |
| 2061 | return path |
| 2062 | resolved_root = root.resolve(strict=False) |
| 2063 | resolved_path = path.resolve(strict=False) |
| 2064 | |
| 2065 | try: |
| 2066 | resolved_path.relative_to(resolved_root) |
| 2067 | except ValueError as exc: |
| 2068 | raise object_collections.InvalidCollectionNameError( |
| 2069 | f"Collection path escapes collection directory: {collection}" |
| 2070 | ) from exc |
| 2071 | |
| 2072 | return path |
| 2073 | |
| 2074 | |
| 2075 | def _no_link_below_root(path: Path) -> bool: |
| 2076 | """True when `root/<collection>/records.tsv` provably resolves inside |
| 2077 | `root`, by two lstat()s instead of two Path.resolve()s. |
| 2078 | |
| 2079 | The name is one validated component (no slash, no dot), so the only way |
| 2080 | the path can leave the collections directory is a symlink at the |
| 2081 | collection directory or at the records file; whatever `root` itself is |
| 2082 | (a link, missing, relative) is resolved identically on both sides of |
| 2083 | the check below. So: neither of the two is a link, and each one is |
| 2084 | either missing or (for the directory) a real directory, means the |
| 2085 | check would pass. Anything else -- a link, a collection "directory" |
| 2086 | that is a file, an lstat that fails for any reason but "not there" -- |
| 2087 | returns False and the full resolve check runs, unchanged. Not a cache: |
| 2088 | asked again on every call, so a link created later is seen at once. |
| 2089 | |
| 2090 | Each resolve() walked every component of the absolute path with one |
| 2091 | lstat per component; the record read of every request does this four |
| 2092 | to six times (each identity resolution alone reads three collections). |
| 2093 | """ |
| 2094 | try: |
| 2095 | st = os.lstat(path.parent) |
| 2096 | except FileNotFoundError: |
| 2097 | return True |
| 2098 | except OSError: |
| 2099 | return False |
| 2100 | if not stat.S_ISDIR(st.st_mode): |
| 2101 | return False |
| 2102 | try: |
| 2103 | st = os.lstat(path) |
| 2104 | except FileNotFoundError: |
| 2105 | return True |
| 2106 | except OSError: |
| 2107 | return False |
| 2108 | return not stat.S_ISLNK(st.st_mode) |
| 2109 | |
| 2110 | |
| 2111 | def collection_has_records(collection: str, base_dir: Path | str = DEFAULT_DATA_DIR) -> bool: |
| 2112 | """Return True when a collection has a records TSV file.""" |
| 2113 | try: |
| 2114 | path = collection_records_file(collection, base_dir=base_dir) |
| 2115 | except object_collections.InvalidCollectionNameError: |
| 2116 | return False |
| 2117 | return path.is_file() |
| 2118 | |
| 2119 | |
| 2120 | def iter_record_collections(base_dir: Path | str = DEFAULT_DATA_DIR) -> list[str]: |
| 2121 | """Return collection names with a ``records.tsv`` file.""" |
| 2122 | root = Path(base_dir) / COLLECTIONS_DIR |
| 2123 | if not root.exists() or not root.is_dir(): |
| 2124 | return [] |
| 2125 | |
| 2126 | names = [] |
| 2127 | for path in sorted(root.glob(f"*/{RECORDS_FILE}"), key=lambda item: item.as_posix()): |
| 2128 | name = path.parent.name |
| 2129 | if object_collections.validate_collection_name(name): |
| 2130 | names.append(name) |
| 2131 | return names |
| 2132 | |
| 2133 | |
| 2134 | def _ensure_collection_known( |
| 2135 | collection: str, |
| 2136 | *, |
| 2137 | base_dir: Path | str, |
| 2138 | roots: Iterable[Path] | None, |
| 2139 | ) -> None: |
| 2140 | if not object_collections.validate_collection_name(collection): |
| 2141 | raise object_collections.InvalidCollectionNameError( |
| 2142 | f"Invalid collection name: {collection}" |
| 2143 | ) |
| 2144 | |
| 2145 | if collection_has_records(collection, base_dir=base_dir): |
| 2146 | return |
| 2147 | |
| 2148 | try: |
| 2149 | object_schemas.get_schema(collection, base_dir=base_dir, roots=roots) |
| 2150 | return |
| 2151 | except object_schemas.SchemaNotFoundError: |
| 2152 | pass |
| 2153 | |
| 2154 | raise object_collections.CollectionNotFoundError(f"Collection not found: {collection}") |
| 2155 | |
| 2156 | |
| 2157 | def _cached_records_ref( |
| 2158 | collection: str, |
| 2159 | *, |
| 2160 | base_dir: Path | str, |
| 2161 | ) -> list[dict[str, str]]: |
| 2162 | """Return the module cache's own records list for a collection. |
| 2163 | |
| 2164 | Callers must not mutate the returned list or its dicts in place, and |
| 2165 | must copy before handing anything derived from it back across the |
| 2166 | public API -- see the _RECORDS_CACHE ALIASING SAFETY note above. |
| 2167 | """ |
| 2168 | path = collection_records_file(collection, base_dir=base_dir) |
| 2169 | _, records, _ = _cache_entry(collection, path) |
| 2170 | return records |
| 2171 | |
| 2172 | |
| 2173 | def _read_collection_records( |
| 2174 | collection: str, |
| 2175 | *, |
| 2176 | base_dir: Path | str, |
| 2177 | ) -> list[dict[str, str]]: |
| 2178 | records = _cached_records_ref(collection, base_dir=base_dir) |
| 2179 | # Copy: `records` is the module cache's own list of its own dicts. |
| 2180 | return [dict(record) for record in records] |
| 2181 | |
| 2182 | |
| 2183 | def _stat_signature(path: Path) -> tuple[int, int, int] | None: |
| 2184 | try: |
| 2185 | st = path.stat() |
| 2186 | except OSError: |
| 2187 | return None |
| 2188 | return (st.st_mtime_ns, st.st_size, st.st_ino) |
| 2189 | |
| 2190 | |
| 2191 | def _build_id_index(records: list[dict[str, str]]) -> dict[str, int]: |
| 2192 | index: dict[str, int] = {} |
| 2193 | for position, record in enumerate(records): |
| 2194 | record_id = record.get("id") |
| 2195 | if record_id and record_id not in index: |
| 2196 | index[record_id] = position |
| 2197 | return index |
| 2198 | |
| 2199 | |
| 2200 | def _build_field_buckets( |
| 2201 | records: Sequence[Mapping[str, Any]], field: str |
| 2202 | ) -> dict[str, "array[int]"]: |
| 2203 | """{str(value): ascending positions} for one field of one records list. |
| 2204 | |
| 2205 | The id_index idea for a field whose values repeat. Keys are stringified |
| 2206 | exactly as the permission engine stringifies a field before comparing |
| 2207 | it (str(); cached rows only ever hold strings, the general case is for |
| 2208 | the pure callers and tests). A row whose field is missing or None is in |
| 2209 | NO bucket: no equality or membership condition can match it |
| 2210 | (object_permissions._condition_matches), so nothing ever looks it up -- |
| 2211 | and an empty string is an ordinary value with its own bucket. |
| 2212 | |
| 2213 | Positions are stored as unsigned 4-byte ints (array("I")): a list of |
| 2214 | Python ints costs about ten times that per row. |
| 2215 | """ |
| 2216 | built: dict[str, "array[int]"] = {} |
| 2217 | for position, record in enumerate(records): |
| 2218 | value = record.get(field) |
| 2219 | if value is None: |
| 2220 | continue |
| 2221 | key = value if type(value) is str else str(value) |
| 2222 | bucket = built.get(key) |
| 2223 | if bucket is None: |
| 2224 | built[key] = array("I", (position,)) |
| 2225 | else: |
| 2226 | bucket.append(position) |
| 2227 | return built |
| 2228 | |
| 2229 | |
| 2230 | class _IdIndexBuckets: |
| 2231 | """`id_index` presented as buckets, for a collection whose ids are all |
| 2232 | present and unique: every id's bucket is its one position, which is |
| 2233 | exactly what id_index already holds -- no second copy, no build. |
| 2234 | |
| 2235 | Only valid under that condition (see _field_index_lookup): id_index is |
| 2236 | first-occurrence-wins and skips blank ids, so in a hand-edited file |
| 2237 | with duplicate ids it would silently omit the second row. |
| 2238 | """ |
| 2239 | |
| 2240 | __slots__ = ("_id_index",) |
| 2241 | |
| 2242 | def __init__(self, id_index: Mapping[str, int]) -> None: |
| 2243 | self._id_index = id_index |
| 2244 | |
| 2245 | def get(self, value: str, default: Any = None) -> Any: |
| 2246 | position = self._id_index.get(value) |
| 2247 | return default if position is None else (position,) |
| 2248 | |
| 2249 | |
| 2250 | def _field_index_lookup( |
| 2251 | path: Path, |
| 2252 | records: list[dict[str, str]], |
| 2253 | id_index: Mapping[str, int], |
| 2254 | extra_names: set[str], |
| 2255 | ) -> Callable[[str], Any] | None: |
| 2256 | """Return `buckets_for(field)` over `records`, or None when `records` is |
| 2257 | not the list of the current _RECORDS_CACHE entry (the collection is too |
| 2258 | large to cache, or a write replaced the entry since `records` was |
| 2259 | taken) -- in which case there is no index and the caller reads every |
| 2260 | row. |
| 2261 | |
| 2262 | `records` and `id_index` must be what ONE _cache_entry call returned. |
| 2263 | The identity check is the whole invalidation scheme: the index is an |
| 2264 | attribute of the entry, and an entry's records list never changes. |
| 2265 | |
| 2266 | A `store: extra` field is refused (buckets_for returns None): its value |
| 2267 | lives inside the JSON `extra` column and is surfaced onto the row only |
| 2268 | on the way out, so the cached column of that name -- if one exists at |
| 2269 | all -- is not what the permission engine compares. |
| 2270 | """ |
| 2271 | entry = _RECORDS_CACHE.get(str(path.resolve(strict=False))) |
| 2272 | if entry is None or entry[2] is not records: |
| 2273 | return None |
| 2274 | field_index = getattr(entry, "field_index", None) |
| 2275 | if field_index is None: |
| 2276 | return None |
| 2277 | ids_exact = len(id_index) == len(records) |
| 2278 | |
| 2279 | def buckets_for(field: str) -> Any: |
| 2280 | if field in extra_names: |
| 2281 | return None |
| 2282 | if field == "id" and ids_exact: |
| 2283 | return _IdIndexBuckets(id_index) |
| 2284 | found = field_index.get(field) |
| 2285 | if found is None: |
| 2286 | with _FIELD_INDEX_LOCK: |
| 2287 | found = field_index.get(field) |
| 2288 | if found is None: |
| 2289 | found = _build_field_buckets(records, field) |
| 2290 | field_index[field] = found # one assignment: whole or absent |
| 2291 | return found |
| 2292 | |
| 2293 | return buckets_for |
| 2294 | |
| 2295 | |
| 2296 | def _record_lock_rules( |
| 2297 | collection: str, |
| 2298 | *, |
| 2299 | base_dir: Path | str, |
| 2300 | roots: Iterable[Path] | None, |
| 2301 | ) -> list[dict[str, Any]]: |
| 2302 | """The collection's schema `locked_when` rules, canonical form (see |
| 2303 | object_schemas._normalize_locked_when). [] for a collection with no |
| 2304 | schema; a schema that cannot be loaded raises.""" |
| 2305 | try: |
| 2306 | schema = object_schemas.get_schema(collection, base_dir=base_dir, roots=roots) |
| 2307 | except object_schemas.SchemaNotFoundError: |
| 2308 | return [] |
| 2309 | return schema.get("locked_when") or [] |
| 2310 | |
| 2311 | |
| 2312 | def _check_record_locks( |
| 2313 | rules: list[dict[str, Any]], |
| 2314 | collection: str, |
| 2315 | record_id: str, |
| 2316 | existing: Mapping[str, Any], |
| 2317 | updated: Mapping[str, Any] | None, |
| 2318 | *, |
| 2319 | submitted: Iterable[str], |
| 2320 | base_dir: Path | str, |
| 2321 | roots: Iterable[Path] | None, |
| 2322 | ) -> None: |
| 2323 | """Refuse an update or delete of a record a `locked_when` rule freezes. |
| 2324 | |
| 2325 | MUST be called holding the collection's _records_file_lock, with |
| 2326 | `existing` the row read under that lock (surfaced, i.e. `store: extra` |
| 2327 | fields at the top level). `updated` is the row as it would be stored, |
| 2328 | in the same surfaced form, or None for a delete; `submitted` is the |
| 2329 | field names this write actually sent. |
| 2330 | |
| 2331 | Why here and not in a hook, where the first three of these rules |
| 2332 | lived. A hook is handed the record as it was read BEFORE the lock. An |
| 2333 | edit that overlaps an approval is checked against the draft, passes, |
| 2334 | and is then written onto the approved row -- the hours somebody |
| 2335 | approved are no longer the hours on file, and nothing refused |
| 2336 | anything. The hook also never ran on delete, and never runs for |
| 2337 | storage-level writers. This check reads the state the write will |
| 2338 | actually land on, for every writer. |
| 2339 | |
| 2340 | Rules: |
| 2341 | - A rule applies when the STORED row matches `when`. The row the write |
| 2342 | would produce is irrelevant: the write that moves a draft to approved |
| 2343 | may change anything, and a write that moves an approved row back to |
| 2344 | draft is still a write to an approved row -- it may touch only the |
| 2345 | `except` fields, so unlocking and editing take two writes. (Were it |
| 2346 | judged by the outcome, having `status` in `except` would let one |
| 2347 | request un-approve, rewrite and re-approve.) |
| 2348 | - A change is a SUBMITTED field whose value would differ. A field sent |
| 2349 | back unchanged is not a change (a form posts everything it shows). |
| 2350 | A field not sent cannot be an edit, whatever recomputation or |
| 2351 | canonicalization does to it. |
| 2352 | - A rule is an allow-list (`except`: everything else is frozen) or a |
| 2353 | deny-list (`fields`: only these are frozen), never both. |
| 2354 | - Computed and read-only fields are never frozen. A client cannot |
| 2355 | submit either; what changes them is the server (a rollup recomputed |
| 2356 | on a posted journal, a trusted writer's stamp), and that is not |
| 2357 | somebody editing settled data. |
| 2358 | - Every matching rule applies; each can only restrict. |
| 2359 | - Nobody is exempt. The rule is about the record, not the caller, and |
| 2360 | there is deliberately no bypass argument: a way round a gate gets |
| 2361 | used. A settled record is corrected by a compensating record, or |
| 2362 | unlocked by a transition out of the state if the schema allows one. |
| 2363 | """ |
| 2364 | matching = [ |
| 2365 | rule |
| 2366 | for rule in rules |
| 2367 | if all( |
| 2368 | ("" if existing.get(name) is None else str(existing.get(name))) in values |
| 2369 | for name, values in rule["when"].items() |
| 2370 | ) |
| 2371 | ] |
| 2372 | if not matching: |
| 2373 | return |
| 2374 | |
| 2375 | def state(rule: Mapping[str, Any]) -> str: |
| 2376 | return " and ".join( |
| 2377 | f"{name} is {str(existing.get(name) or '') or 'blank'}" for name in rule["when"] |
| 2378 | ) |
| 2379 | |
| 2380 | if updated is None: |
| 2381 | for rule in matching: |
| 2382 | if not rule.get("allow_delete"): |
| 2383 | raise RecordLockedError( |
| 2384 | rule.get("message") |
| 2385 | or f"This {collection} record cannot be deleted while {state(rule)}.", |
| 2386 | collection=collection, |
| 2387 | record_id=record_id, |
| 2388 | action="delete", |
| 2389 | fields=[], |
| 2390 | when=rule["when"], |
| 2391 | ) |
| 2392 | return |
| 2393 | |
| 2394 | server_owned = { |
| 2395 | field["name"] |
| 2396 | for field in _schema_fields(collection, base_dir=base_dir, roots=roots) |
| 2397 | if _is_computed_or_read_only(field) |
| 2398 | } |
| 2399 | changed = sorted( |
| 2400 | name |
| 2401 | for name in submitted |
| 2402 | if name != "id" |
| 2403 | and name not in server_owned |
| 2404 | and ("" if existing.get(name) is None else str(existing.get(name))) |
| 2405 | != ("" if updated.get(name) is None else str(updated.get(name))) |
| 2406 | ) |
| 2407 | if not changed: |
| 2408 | return |
| 2409 | for rule in matching: |
| 2410 | if "fields" in rule: |
| 2411 | frozen = [name for name in changed if name in rule["fields"]] |
| 2412 | else: |
| 2413 | frozen = [name for name in changed if name not in rule["except"]] |
| 2414 | if frozen: |
| 2415 | raise RecordLockedError( |
| 2416 | rule.get("message") |
| 2417 | or ( |
| 2418 | f"This {collection} record is locked while {state(rule)}: " |
| 2419 | f"{', '.join(frozen)} cannot be changed." |
| 2420 | ), |
| 2421 | collection=collection, |
| 2422 | record_id=record_id, |
| 2423 | action="update", |
| 2424 | fields=frozen, |
| 2425 | when=rule["when"], |
| 2426 | ) |
| 2427 | |
| 2428 | |
| 2429 | def _unique_constraints( |
| 2430 | collection: str, |
| 2431 | *, |
| 2432 | base_dir: Path | str, |
| 2433 | roots: Iterable[Path] | None, |
| 2434 | ) -> list[dict[str, Any]]: |
| 2435 | """The collection's schema `unique` constraints, canonical form (see |
| 2436 | object_schemas._normalize_unique). [] for a collection with no schema. |
| 2437 | A schema that cannot be loaded raises: an unreadable constraint is not |
| 2438 | an absent one.""" |
| 2439 | try: |
| 2440 | schema = object_schemas.get_schema(collection, base_dir=base_dir, roots=roots) |
| 2441 | except object_schemas.SchemaNotFoundError: |
| 2442 | return [] |
| 2443 | return schema.get("unique") or [] |
| 2444 | |
| 2445 | |
| 2446 | def _unique_key(constraint: Mapping[str, Any], row: Mapping[str, Any]) -> Any: |
| 2447 | """The key `row` holds under `constraint`, or None when it holds none. |
| 2448 | |
| 2449 | - Every value is compared TRIMMED. "evt-1" and "evt-1 " are one key: |
| 2450 | the second is what a duplicate looks like when it arrives by paste. |
| 2451 | - A blank `fields` value means the row has no key and is exempt. Most |
| 2452 | wallets have no gift-card code; a bank line from a CSV has no bank |
| 2453 | transaction id. Uniqueness is a property of the keys that exist. |
| 2454 | - A blank `scope` value is an ordinary value. Scope is who the key |
| 2455 | belongs to (owner_id, bank_account_id); treating "no owner" as exempt |
| 2456 | would let every admin-token write, which is not owner-stamped, |
| 2457 | duplicate freely. |
| 2458 | - `ignore_case` folds the `fields` values (not the scope, which is an |
| 2459 | id). upper() then casefold(): a code is compared with upper() where |
| 2460 | it is redeemed (object_promotions.normalize_code, hook_wallets), and |
| 2461 | casefold() alone keeps dotless i apart from i where upper() does not, |
| 2462 | so folding with only one of them would let through a pair the other |
| 2463 | treats as the same code. |
| 2464 | """ |
| 2465 | fold = constraint.get("ignore_case") |
| 2466 | parts: list[str] = [] |
| 2467 | for name in constraint["fields"]: |
| 2468 | value = row.get(name) |
| 2469 | text = "" if value is None else str(value).strip() |
| 2470 | if not text: |
| 2471 | return None |
| 2472 | parts.append(text.upper().casefold() if fold else text) |
| 2473 | for name in constraint.get("scope") or (): |
| 2474 | value = row.get(name) |
| 2475 | parts.append("" if value is None else str(value).strip()) |
| 2476 | return parts[0] if len(parts) == 1 else tuple(parts) |
| 2477 | |
| 2478 | |
| 2479 | def _unique_map_add(holders: dict[Any, Any], key: Any, record_id: str) -> None: |
| 2480 | held = holders.get(key) |
| 2481 | if held is None: |
| 2482 | holders[key] = record_id |
| 2483 | elif isinstance(held, tuple): |
| 2484 | if record_id not in held: |
| 2485 | holders[key] = held + (record_id,) |
| 2486 | elif held != record_id: |
| 2487 | holders[key] = (held, record_id) |
| 2488 | |
| 2489 | |
| 2490 | def _unique_map_discard(holders: dict[Any, Any], key: Any, record_id: str) -> None: |
| 2491 | held = holders.get(key) |
| 2492 | if held is None: |
| 2493 | return |
| 2494 | if not isinstance(held, tuple): |
| 2495 | if held == record_id: |
| 2496 | del holders[key] |
| 2497 | return |
| 2498 | rest = tuple(holder for holder in held if holder != record_id) |
| 2499 | if not rest: |
| 2500 | del holders[key] |
| 2501 | else: |
| 2502 | holders[key] = rest[0] if len(rest) == 1 else rest |
| 2503 | |
| 2504 | |
| 2505 | def _build_unique_map( |
| 2506 | constraint: Mapping[str, Any], records: Iterable[Mapping[str, Any]] |
| 2507 | ) -> dict[Any, Any]: |
| 2508 | """{key: holder} for one constraint over one records list. A holder is a |
| 2509 | record id; where the data already holds duplicates (the constraint was |
| 2510 | declared over existing rows) it is a tuple of every id, in row order, |
| 2511 | so that deleting one of them does not free a key another still holds.""" |
| 2512 | holders: dict[Any, Any] = {} |
| 2513 | for record in records: |
| 2514 | key = _unique_key(constraint, record) |
| 2515 | if key is not None: |
| 2516 | _unique_map_add(holders, key, record.get("id") or "") |
| 2517 | return holders |
| 2518 | |
| 2519 | |
| 2520 | def _check_unique_constraints( |
| 2521 | collection: str, |
| 2522 | path: Path, |
| 2523 | *, |
| 2524 | record_id: str, |
| 2525 | old_row: Mapping[str, Any] | None, |
| 2526 | new_row: Mapping[str, Any] | None, |
| 2527 | records_ref: list[dict[str, str]] | None, |
| 2528 | base_dir: Path | str, |
| 2529 | roots: Iterable[Path] | None, |
| 2530 | ) -> tuple[str, str, list[dict[str, Any]], list[dict[Any, Any]]] | None: |
| 2531 | """Refuse a write that would give `new_row` a key another record holds. |
| 2532 | |
| 2533 | MUST be called holding `path`'s _records_file_lock, after the row to be |
| 2534 | written is final and before _persist_write. That placement is the whole |
| 2535 | feature: a duplicate check anywhere earlier (a pre-write hook, a |
| 2536 | handler's own "have I done this already?" read) is a read followed by a |
| 2537 | write with a gap between them, and two writers in that gap both find |
| 2538 | nothing and both write. This is how one usage event was billed twice, |
| 2539 | one wallet top-up credited twice and one settings key configured twice. |
| 2540 | Under the lock, the second writer sees the first one's row. |
| 2541 | |
| 2542 | `old_row` is the stored row (update, delete) or None (create); |
| 2543 | `new_row` is the row about to be stored, or None (delete). Raises |
| 2544 | UniqueConstraintError; otherwise returns what _commit_unique_index |
| 2545 | needs to keep the index current once the write has landed, or None when |
| 2546 | there is nothing to keep (no constraints; or no current index and a |
| 2547 | write that takes no key, which is no reason to build one). |
| 2548 | |
| 2549 | Rules, beyond _unique_key's: |
| 2550 | - An update is checked only for a key it CHANGES. A record keeping its |
| 2551 | own key cannot create a violation, and refusing it would freeze any |
| 2552 | row that was already a duplicate when the constraint was declared. |
| 2553 | - Existing duplicates are left alone -- the platform does not pick a |
| 2554 | winner among rows it did not write (find_unique_violations lists |
| 2555 | them) -- but no further holder of that key is admitted. |
| 2556 | |
| 2557 | `records_ref` is _fast_record_lookup's records list when it had one |
| 2558 | (the warm cache: an index build costs no parse). When it did not (an |
| 2559 | append collection resolved through the id->offset sidecar, i.e. too |
| 2560 | large to cache or cold) a build folds the file once, via _cache_entry. |
| 2561 | See the _UNIQUE_INDEX block comment for why that happens once and not |
| 2562 | on every write. |
| 2563 | """ |
| 2564 | constraints = _unique_constraints(collection, base_dir=base_dir, roots=roots) |
| 2565 | if not constraints: |
| 2566 | return None |
| 2567 | |
| 2568 | # The keys this write would newly take: (position of constraint, key). |
| 2569 | taking: list[tuple[int, Any]] = [] |
| 2570 | if new_row is not None: |
| 2571 | for position, constraint in enumerate(constraints): |
| 2572 | key = _unique_key(constraint, new_row) |
| 2573 | if key is None: |
| 2574 | continue |
| 2575 | if old_row is not None and key == _unique_key(constraint, old_row): |
| 2576 | continue |
| 2577 | taking.append((position, key)) |
| 2578 | |
| 2579 | cache_key = str(path.resolve(strict=False)) |
| 2580 | fingerprint = json.dumps(constraints, sort_keys=True) |
| 2581 | signature = _stat_signature(path) |
| 2582 | with _UNIQUE_INDEX_LOCK: |
| 2583 | cached = _UNIQUE_INDEX.get(cache_key) |
| 2584 | if ( |
| 2585 | cached is not None |
| 2586 | and signature is not None |
| 2587 | and cached[0] == signature |
| 2588 | and cached[1] == fingerprint |
| 2589 | ): |
| 2590 | maps = cached[2] |
| 2591 | elif not taking: |
| 2592 | # Nothing to check, and no current index to keep current: do not |
| 2593 | # build one for a delete, or for an update that moves no key (a |
| 2594 | # status flip, a rollup recompute). The next write that takes a key |
| 2595 | # builds it. |
| 2596 | return None |
| 2597 | else: |
| 2598 | if records_ref is None: |
| 2599 | # Parsed directly, NOT through _cache_entry: that would also |
| 2600 | # install the rows in _RECORDS_CACHE, and a warm records cache |
| 2601 | # makes every later append copy the whole list and id index |
| 2602 | # (_refresh_records_cache_after_append) where the sidecar path |
| 2603 | # this lookup came through is O(1). Measured at 100k rows: 1.2ms |
| 2604 | # per append cold, 3.4ms once warmed. Declaring a constraint |
| 2605 | # must not move a collection between those regimes. |
| 2606 | records_ref = _parse_records_file(collection, path)[1] if path.is_file() else [] |
| 2607 | maps = [_build_unique_map(constraint, records_ref) for constraint in constraints] |
| 2608 | if signature is not None: |
| 2609 | # Stored now, not only after the write: a refused write changes |
| 2610 | # nothing, and a burst of refused duplicates (a retry storm is |
| 2611 | # exactly when this matters) must not rebuild on every attempt. |
| 2612 | _store_unique_index(cache_key, signature, fingerprint, maps) |
| 2613 | |
| 2614 | for position, key in taking: |
| 2615 | held = maps[position].get(key) |
| 2616 | if held is None: |
| 2617 | continue |
| 2618 | others = [ |
| 2619 | holder |
| 2620 | for holder in (held if isinstance(held, tuple) else (held,)) |
| 2621 | if holder != record_id |
| 2622 | ] |
| 2623 | if others: |
| 2624 | constraint = constraints[position] |
| 2625 | raise UniqueConstraintError( |
| 2626 | _unique_violation_message(collection, constraint), |
| 2627 | collection=collection, |
| 2628 | fields=constraint["fields"], |
| 2629 | scope=constraint.get("scope") or [], |
| 2630 | existing_id=others[0], |
| 2631 | ) |
| 2632 | return cache_key, fingerprint, constraints, maps |
| 2633 | |
| 2634 | |
| 2635 | def _commit_unique_index( |
| 2636 | pending: tuple[str, str, list[dict[str, Any]], list[dict[Any, Any]]] | None, |
| 2637 | path: Path, |
| 2638 | *, |
| 2639 | record_id: str, |
| 2640 | old_row: Mapping[str, Any] | None, |
| 2641 | new_row: Mapping[str, Any] | None, |
| 2642 | ) -> None: |
| 2643 | """Apply one landed write to the unique index and re-stamp it. |
| 2644 | |
| 2645 | Called under the same lock as _check_unique_constraints, immediately |
| 2646 | after _persist_write returns -- so the file now is exactly the file the |
| 2647 | index described plus this one change, and the new stat signature is |
| 2648 | this process's own write. If _persist_write raised, this is never |
| 2649 | reached: the maps are untouched and still carry the old stamp, which |
| 2650 | still matches the file only if the write changed nothing. |
| 2651 | """ |
| 2652 | if pending is None: |
| 2653 | return |
| 2654 | cache_key, fingerprint, constraints, maps = pending |
| 2655 | for constraint, holders in zip(constraints, maps): |
| 2656 | old_key = _unique_key(constraint, old_row) if old_row is not None else None |
| 2657 | new_key = _unique_key(constraint, new_row) if new_row is not None else None |
| 2658 | if old_key == new_key: |
| 2659 | continue |
| 2660 | if old_key is not None: |
| 2661 | _unique_map_discard(holders, old_key, record_id) |
| 2662 | if new_key is not None: |
| 2663 | _unique_map_add(holders, new_key, record_id) |
| 2664 | |
| 2665 | signature = _stat_signature(path) |
| 2666 | if signature is None: |
| 2667 | with _UNIQUE_INDEX_LOCK: |
| 2668 | _UNIQUE_INDEX.pop(cache_key, None) |
| 2669 | return |
| 2670 | _store_unique_index(cache_key, signature, fingerprint, maps) |
| 2671 | |
| 2672 | |
| 2673 | def _store_unique_index( |
| 2674 | cache_key: str, |
| 2675 | signature: tuple[int, int, int], |
| 2676 | fingerprint: str, |
| 2677 | maps: list[dict[Any, Any]], |
| 2678 | ) -> None: |
| 2679 | with _UNIQUE_INDEX_LOCK: |
| 2680 | _UNIQUE_INDEX[cache_key] = (signature, fingerprint, maps) |
| 2681 | _UNIQUE_INDEX.move_to_end(cache_key) |
| 2682 | max_entries = _records_cache_max_entries() |
| 2683 | while len(_UNIQUE_INDEX) > max_entries: |
| 2684 | _UNIQUE_INDEX.popitem(last=False) |
| 2685 | |
| 2686 | |
| 2687 | def _unique_violation_message(collection: str, constraint: Mapping[str, Any]) -> str: |
| 2688 | """The schema's own `message` when it gives one, else a sentence that |
| 2689 | names the fields. Never the conflicting record or its values: the |
| 2690 | caller may not be allowed to read that record.""" |
| 2691 | message = constraint.get("message") |
| 2692 | if message: |
| 2693 | return str(message) |
| 2694 | fields = constraint["fields"] |
| 2695 | scope = constraint.get("scope") or [] |
| 2696 | what = " + ".join(fields) |
| 2697 | within = f" for the same {' + '.join(scope)}" if scope else "" |
| 2698 | verb = "is" if len(fields) == 1 else "are" |
| 2699 | return ( |
| 2700 | f"Another {collection} record already has this {what}{within}; " |
| 2701 | f"{what} {verb} unique in {collection}." |
| 2702 | ) |
| 2703 | |
| 2704 | |
| 2705 | def _env_int(name: str, default: int) -> int: |
| 2706 | """Read an int env var, falling back to `default` when unset or unparseable.""" |
| 2707 | raw = os.environ.get(name) |
| 2708 | if raw is None: |
| 2709 | return default |
| 2710 | try: |
| 2711 | return int(raw) |
| 2712 | except ValueError: |
| 2713 | return default |
| 2714 | |
| 2715 | |
| 2716 | def _records_cache_max_entries() -> int: |
| 2717 | return _env_int(RECORDS_CACHE_MAX_ENTRIES_ENV, _DEFAULT_RECORDS_CACHE_MAX_ENTRIES) |
| 2718 | |
| 2719 | |
| 2720 | def _records_cache_max_rows() -> int: |
| 2721 | return _env_int(RECORDS_CACHE_MAX_ROWS_ENV, _DEFAULT_RECORDS_CACHE_MAX_ROWS) |
| 2722 | |
| 2723 | |
| 2724 | def _oidx_cache_max_entries() -> int: |
| 2725 | return _env_int(OIDX_CACHE_MAX_ENTRIES_ENV, _DEFAULT_OIDX_CACHE_MAX_ENTRIES) |
| 2726 | |
| 2727 | |
| 2728 | def _store_records_cache( |
| 2729 | cache_key: str, |
| 2730 | signature: tuple[int, int, int], |
| 2731 | fields: list[str], |
| 2732 | records: list[dict[str, str]], |
| 2733 | id_index: dict[str, int], |
| 2734 | covered_bytes: int, |
| 2735 | ) -> None: |
| 2736 | """Insert/refresh one entry as most-recently-used, then evict over capacity. |
| 2737 | |
| 2738 | Eviction is pure LRU by entry count: once the dict exceeds |
| 2739 | DBBASIC_RECORDS_CACHE_MAX_ENTRIES, the oldest (least-recently-used) |
| 2740 | entries are dropped first via OrderedDict.popitem(last=False). |
| 2741 | |
| 2742 | `covered_bytes` is normally just `signature[1]` (every caller except |
| 2743 | the two torn-tail cases -- _try_incremental_cache_entry's and |
| 2744 | _cache_entry's full parse of a torn file -- passes exactly that) -- |
| 2745 | see the _RECORDS_CACHE block comment above for what it means and the |
| 2746 | one case where it differs. |
| 2747 | """ |
| 2748 | _RECORDS_CACHE[cache_key] = _RecordsCacheEntry( |
| 2749 | (signature, fields, records, id_index, covered_bytes) |
| 2750 | ) |
| 2751 | _RECORDS_CACHE.move_to_end(cache_key) |
| 2752 | max_entries = _records_cache_max_entries() |
| 2753 | while len(_RECORDS_CACHE) > max_entries: |
| 2754 | _RECORDS_CACHE.popitem(last=False) |
| 2755 | |
| 2756 | |
| 2757 | def _peek_records_cache( |
| 2758 | path: Path, |
| 2759 | ) -> tuple[list[str], list[dict[str, str]], dict[str, int]] | None: |
| 2760 | """Return a warm _RECORDS_CACHE hit for `path`, or None on any miss. |
| 2761 | |
| 2762 | Never parses: this is the "is there already a fully-folded view of |
| 2763 | this file sitting in memory" check used to decide, in |
| 2764 | _fast_record_lookup, whether a point op can skip both a full fold AND |
| 2765 | the sidecar (cache hit -- the common case for any collection at or |
| 2766 | under DBBASIC_RECORDS_CACHE_MAX_ROWS once warm) or must try the |
| 2767 | cheaper-than-a-fold sidecar path next (a miss -- cold cache, an |
| 2768 | evicted LRU entry, or a collection that has never fit under the row |
| 2769 | threshold and so is never stored here at all; see _cache_entry, this |
| 2770 | function's parsing counterpart, which _fast_record_lookup and every |
| 2771 | non-fast-path caller fall back to when neither a cache hit nor the |
| 2772 | sidecar can answer). |
| 2773 | """ |
| 2774 | cache_key = str(path.resolve(strict=False)) |
| 2775 | signature = _stat_signature(path) |
| 2776 | if signature is None: |
| 2777 | return None |
| 2778 | cached = _RECORDS_CACHE.get(cache_key) |
| 2779 | if cached is not None and cached[0] == signature: |
| 2780 | _RECORDS_CACHE.move_to_end(cache_key) |
| 2781 | return cached[1], cached[2], cached[3] |
| 2782 | return None |
| 2783 | |
| 2784 | |
| 2785 | def _cache_entry( |
| 2786 | collection: str, |
| 2787 | path: Path, |
| 2788 | ) -> tuple[list[str], list[dict[str, str]], dict[str, int]]: |
| 2789 | """Return (fields, records, id_index) for path's current content. |
| 2790 | |
| 2791 | Serves from the module cache when the file's stat signature matches |
| 2792 | (moving the entry to most-recently-used); otherwise parses fresh and, |
| 2793 | when the file exists and its row count is within |
| 2794 | DBBASIC_RECORDS_CACHE_MAX_ROWS, stores the result for next time (a |
| 2795 | collection over that threshold is returned normally but left out of |
| 2796 | the cache -- see the _RECORDS_CACHE block comment above). The returned |
| 2797 | fields/records/id_index are the CACHED objects -- see the |
| 2798 | _RECORDS_CACHE docstring above. Callers within this module must copy |
| 2799 | before handing anything back across the public API. |
| 2800 | |
| 2801 | On a peek miss, tries one more thing before paying a full parse: if a |
| 2802 | STALE entry is sitting in _RECORDS_CACHE for this exact path and the |
| 2803 | file has purely grown in place (same inode, size beyond what that |
| 2804 | entry covered) on an append-mode file, _try_incremental_cache_entry |
| 2805 | folds only the new tail bytes onto the stale entry instead -- O(new |
| 2806 | rows), not O(file). See that function for the full precondition list |
| 2807 | and fallback rules; anything it can't handle falls through to the |
| 2808 | ordinary full parse below, unchanged. |
| 2809 | |
| 2810 | Absent that, this is the O(n) fold path: a full parse of the whole |
| 2811 | file whenever there's no warm cache hit. _fast_record_lookup (get/ |
| 2812 | create/update/delete's shared point-op resolver) tries |
| 2813 | _peek_records_cache and then the id->offset sidecar FIRST specifically |
| 2814 | to avoid paying this on every write to a collection too large to fit |
| 2815 | in _RECORDS_CACHE; this function remains the correctness fallback for |
| 2816 | everything else (list, read_collection_records, a cold/small |
| 2817 | collection's first touch, and any point op the sidecar can't answer |
| 2818 | authoritatively). |
| 2819 | """ |
| 2820 | if not path.exists(): |
| 2821 | return ["id"], [], {} |
| 2822 | if not path.is_file(): |
| 2823 | raise ValueError(f"Collection records path is not a file: {collection}") |
| 2824 | |
| 2825 | peeked = _peek_records_cache(path) |
| 2826 | if peeked is not None: |
| 2827 | return peeked |
| 2828 | |
| 2829 | cache_key = str(path.resolve(strict=False)) |
| 2830 | signature = _stat_signature(path) |
| 2831 | |
| 2832 | incremental = _try_incremental_cache_entry(path, cache_key, signature) |
| 2833 | if incremental is not None: |
| 2834 | return incremental |
| 2835 | |
| 2836 | # covered_bytes is where the NEXT incremental fold starts parsing, so it |
| 2837 | # must be a committed row boundary. The file's size is one only when |
| 2838 | # the file ends on a committed row. With a torn tail on disk (a writer |
| 2839 | # died mid-append) the parse drops the fragment, and the size points |
| 2840 | # past it: the next writer -- usually another process -- truncates the |
| 2841 | # fragment in place (_repair_torn_tail, same inode) and appends, the |
| 2842 | # file grows past that size, and a fold starting there began partway |
| 2843 | # into the new row. Its remainder, read as a row, shifted every column |
| 2844 | # left: the new record was missing and one named after its value took |
| 2845 | # its place (tests/test_append_cache_torn_tail.py). So a torn parse |
| 2846 | # records where the fragment starts, which is exactly where the repair |
| 2847 | # truncates to (the same quote-aware _committed_prefix_len). |
| 2848 | torn_covered: list[int] = [] |
| 2849 | fields, records = _parse_records_file(collection, path, torn_covered=torn_covered) |
| 2850 | id_index = _build_id_index(records) |
| 2851 | if signature is not None: |
| 2852 | covered = torn_covered[0] if torn_covered else signature[1] |
| 2853 | if len(records) <= _records_cache_max_rows(): |
| 2854 | _store_records_cache(cache_key, signature, fields, records, id_index, covered) |
| 2855 | else: |
| 2856 | # Too large to cache: don't pin it, and drop any stale entry |
| 2857 | # left over from before this collection grew past the |
| 2858 | # threshold, so it doesn't linger under an old signature. |
| 2859 | _RECORDS_CACHE.pop(cache_key, None) |
| 2860 | return fields, records, id_index |
| 2861 | |
| 2862 | |
| 2863 | def _try_incremental_cache_entry( |
| 2864 | path: Path, |
| 2865 | cache_key: str, |
| 2866 | signature: tuple[int, int, int] | None, |
| 2867 | ) -> tuple[list[str], list[dict[str, str]], dict[str, int]] | None: |
| 2868 | """Attempt the tail-delta incremental fold for an append-mode file that |
| 2869 | grew in place since it was last cached (docs/append-only-storage- |
| 2870 | design.md Sidecars, bullet 2: "when a stat signature changes by |
| 2871 | growth alone, parse only the tail delta"). Returns the fresh (fields, |
| 2872 | records, id_index) on success, or None when the fast path doesn't |
| 2873 | apply -- _cache_entry then falls back to its ordinary full parse, |
| 2874 | unchanged. |
| 2875 | |
| 2876 | This is what makes a WARM cache stay O(delta) instead of O(file) when |
| 2877 | the growth happened outside this process's own write path (another |
| 2878 | process's writer, the CLI, a sibling pool worker, or this process's |
| 2879 | cache having gone cold and been rebuilt from a stat mismatch) -- the |
| 2880 | in-process fast-append path (_refresh_records_cache_after_append) |
| 2881 | already keeps this process's OWN writes O(1); this covers the gap |
| 2882 | where the growth was observed on a read instead. |
| 2883 | |
| 2884 | Preconditions, ALL required (anything off -> None, no partial work is |
| 2885 | trusted): |
| 2886 | - a stat signature could be taken (file still exists, readable) |
| 2887 | - a PRIOR entry is warm in _RECORDS_CACHE for this exact path (a |
| 2888 | cold/evicted/never-cached collection has nothing to build on -- |
| 2889 | the ordinary full parse is the only option) |
| 2890 | - same inode as the prior entry's signature -- a classic-mode |
| 2891 | rewrite, and an append-mode compaction/transition/new-field |
| 2892 | rewrite, all produce a fresh inode via temp+replace |
| 2893 | (_write_collection_records), so this alone rules out every case |
| 2894 | except an in-place append-mode growth |
| 2895 | - the new size is strictly greater than the prior entry's |
| 2896 | covered_bytes -- pure growth, nothing rewritten in place |
| 2897 | - the file's CURRENT physical header is append-format (`_op` first |
| 2898 | column) and its logical fields match the prior entry's fields |
| 2899 | exactly (a header/field change under the same inode should be |
| 2900 | impossible given the point above, but this stays defensive |
| 2901 | rather than trusting that unconditionally) |
| 2902 | |
| 2903 | On success, parses only the new bytes (_append_tail_delta_records, |
| 2904 | the shared torn-tail-tolerant tail reader also used by the id->offset |
| 2905 | sidecar's catch-up scan -- see _scan_append_tail) and folds them onto |
| 2906 | the PRIOR entry's records/id_index -- never mutating the prior |
| 2907 | entry's own list/dict in place (a fresh list/dict is always built; |
| 2908 | other code in this same event-loop turn may still hold references to |
| 2909 | the prior entry's objects, same rule as every other cache-installing |
| 2910 | function in this module). |
| 2911 | |
| 2912 | A tombstone (`_op == "del"`) ANYWHERE in the delta bails out (returns |
| 2913 | None, falling back to the full fold) rather than special-casing |
| 2914 | position shifts: a delete removes a slot and shifts every later |
| 2915 | position down by one (see _fold_append_rows), which this cheap |
| 2916 | replace-or-append merge does not model. Deletes are the rare case for |
| 2917 | the append-shaped workloads this exists for (game-server state, |
| 2918 | impression logs, price history), so this is an accepted, documented |
| 2919 | trade, not a gap -- correctness always wins over speed here. A |
| 2920 | blank-id row in the delta (only reachable via a hand-edited file -- |
| 2921 | see _fold_append_rows) bails out for the same reason: its fold |
| 2922 | position depends on the FULL row history, which an incremental merge |
| 2923 | doesn't have. |
| 2924 | |
| 2925 | The row-count cache threshold (DBBASIC_RECORDS_CACHE_MAX_ROWS) is |
| 2926 | still honored: a successful merge that grows the collection past it |
| 2927 | is still returned to the caller (correct, and far cheaper than a |
| 2928 | full parse either way), but is evicted rather than (re)cached -- the |
| 2929 | same rule _cache_entry's full-parse branch applies just above. |
| 2930 | """ |
| 2931 | if signature is None: |
| 2932 | return None |
| 2933 | |
| 2934 | prior = _RECORDS_CACHE.get(cache_key) |
| 2935 | if prior is None: |
| 2936 | return None |
| 2937 | old_signature, old_fields, old_records, old_id_index, old_covered = prior |
| 2938 | |
| 2939 | if old_signature[2] != signature[2]: |
| 2940 | return None # different inode: not an in-place append |
| 2941 | if signature[1] <= old_covered: |
| 2942 | return None # no growth beyond what's already folded |
| 2943 | |
| 2944 | physical_header = _physical_header(path) |
| 2945 | if not physical_header or physical_header[0] != OP_FIELD: |
| 2946 | return None # not (or no longer) append-physical |
| 2947 | if physical_header[1:] != old_fields: |
| 2948 | return None # defensive: header shouldn't change under the same inode |
| 2949 | |
| 2950 | delta_rows, new_covered = _append_tail_delta_records(path, physical_header, old_covered) |
| 2951 | if not delta_rows: |
| 2952 | return None # nothing complete to fold yet (e.g. a torn tail only) |
| 2953 | |
| 2954 | if any( |
| 2955 | row.get(OP_FIELD, OP_UPSERT) == OP_DELETE or not row.get("id") |
| 2956 | for row in delta_rows |
| 2957 | ): |
| 2958 | return None # tombstone or blank id: fall back to a full fold |
| 2959 | |
| 2960 | new_records = list(old_records) |
| 2961 | new_id_index = dict(old_id_index) |
| 2962 | for row in delta_rows: |
| 2963 | record_id = row["id"] |
| 2964 | clean = {key: value for key, value in row.items() if key != OP_FIELD} |
| 2965 | idx = new_id_index.get(record_id) |
| 2966 | if idx is not None: |
| 2967 | new_records[idx] = clean |
| 2968 | else: |
| 2969 | new_id_index[record_id] = len(new_records) |
| 2970 | new_records.append(clean) |
| 2971 | |
| 2972 | global _INCREMENTAL_CACHE_FOLDS |
| 2973 | _INCREMENTAL_CACHE_FOLDS += 1 |
| 2974 | |
| 2975 | if len(new_records) <= _records_cache_max_rows(): |
| 2976 | _store_records_cache(cache_key, signature, old_fields, new_records, new_id_index, new_covered) |
| 2977 | else: |
| 2978 | _RECORDS_CACHE.pop(cache_key, None) |
| 2979 | return old_fields, new_records, new_id_index |
| 2980 | |
| 2981 | |
| 2982 | def _parse_records_file( |
| 2983 | collection: str, path: Path, *, torn_covered: list[int] | None = None |
| 2984 | ) -> tuple[list[str], list[dict[str, str]]]: |
| 2985 | """Parse one records.tsv file into (fields, records). |
| 2986 | |
| 2987 | ``torn_covered``: when given and the file is append-physical with a |
| 2988 | torn tail, the byte length of its committed prefix (where the torn |
| 2989 | row starts) is appended to it. _cache_entry stores that as the entry's |
| 2990 | covered_bytes; see the comment there for why the file's size is wrong. |
| 2991 | |
| 2992 | Uses csv.reader rather than csv.DictReader: csv.reader is the same |
| 2993 | C-accelerated tokenizer DictReader wraps, but skips DictReader's |
| 2994 | per-row dict-construction overhead (zip + restkey/restval handling) in |
| 2995 | favor of a direct index walk here. Using csv.reader (not a naive |
| 2996 | line.split("\t")) is required for correctness, not just speed: a value |
| 2997 | written by csv.DictWriter's default QUOTE_MINIMAL may legitimately |
| 2998 | contain a quoted tab or embedded newline, and only real CSV/TSV parsing |
| 2999 | reconstructs that value correctly. |
| 3000 | |
| 3001 | Dispatches on the physical header (docs/append-only-storage-design.md): |
| 3002 | a file whose first column is `_op` is in append-only physical format |
| 3003 | and is parsed+folded by _parse_append_body; every other file is parsed |
| 3004 | by the original classic-mode routine, unchanged. This dispatch is by |
| 3005 | the FILE's own header, not the collection's current schema `storage` |
| 3006 | setting -- a collection that just switched storage modes keeps reading |
| 3007 | correctly until its next write physically transitions the file (see |
| 3008 | _persist_write), and a collection that switched back to classic still |
| 3009 | reads correctly (via the append path) until its next write compacts |
| 3010 | the `_op` column away. |
| 3011 | """ |
| 3012 | with path.open(newline="") as handle: |
| 3013 | reader = csv.reader(handle, delimiter="\t") |
| 3014 | try: |
| 3015 | header = next(reader) |
| 3016 | except StopIteration: |
| 3017 | header = None |
| 3018 | _validate_header(collection, header) |
| 3019 | physical_fields = list(header) |
| 3020 | |
| 3021 | if physical_fields and physical_fields[0] == OP_FIELD: |
| 3022 | with path.open(newline="") as handle: |
| 3023 | text = handle.read() |
| 3024 | committed = _drop_torn_tail(text) |
| 3025 | if torn_covered is not None and len(committed) != len(text): |
| 3026 | torn_covered.append(len(committed.encode("utf-8"))) |
| 3027 | folded_records, physical_row_count = _parse_append_body( |
| 3028 | collection, committed, physical_fields, committed=True) |
| 3029 | _maybe_flag_auto_compact( |
| 3030 | path, physical_row_count=physical_row_count, live_row_count=len(folded_records) |
| 3031 | ) |
| 3032 | return physical_fields[1:], folded_records |
| 3033 | |
| 3034 | return physical_fields, _parse_classic_records(collection, path, physical_fields) |
| 3035 | |
| 3036 | |
| 3037 | def _parse_classic_records( |
| 3038 | collection: str, path: Path, fields: list[str] |
| 3039 | ) -> list[dict[str, str]]: |
| 3040 | """Parse the data rows of a classic-mode (no `_op` column) file. |
| 3041 | |
| 3042 | Replicates csv.DictReader's exact semantics for short/long rows and |
| 3043 | blank-line skipping -- see the block comment above _RECORDS_CACHE and |
| 3044 | the tests in tests/test_object_records.py for the specific cases this |
| 3045 | was checked against on the pre-change code. Unchanged from before |
| 3046 | append-only storage existed: a strict parse, no torn-tail tolerance. |
| 3047 | """ |
| 3048 | field_count = len(fields) |
| 3049 | with path.open(newline="") as handle: |
| 3050 | reader = csv.reader(handle, delimiter="\t") |
| 3051 | next(reader, None) # header, already parsed/validated by the caller |
| 3052 | |
| 3053 | records: list[dict[str, str]] = [] |
| 3054 | row_number = 1 # the header is row 1; DictReader's enumerate started data rows at 2 |
| 3055 | for row in reader: |
| 3056 | # csv.DictReader's __next__ silently skips rows the underlying |
| 3057 | # csv.reader returns as [] (blank physical lines) rather than |
| 3058 | # emitting a record for them; replicate that here so row_number |
| 3059 | # (used only in the error message below) still lines up with |
| 3060 | # DictReader's numbering of *emitted* rows, not physical lines. |
| 3061 | if not row: |
| 3062 | continue |
| 3063 | row_number += 1 |
| 3064 | if len(row) > field_count: |
| 3065 | # Mirrors DictReader putting overflow values under the |
| 3066 | # `None` restkey, which the pre-change code detected via |
| 3067 | # `None in row`. |
| 3068 | raise ValueError( |
| 3069 | f"Collection records file has extra fields on row {row_number}: {collection}" |
| 3070 | ) |
| 3071 | # Mirrors DictReader's restval=None for a short row, which the |
| 3072 | # pre-change code then normalized to "" (`value if value is not |
| 3073 | # None else ""`) -- do that normalization directly here. |
| 3074 | record = { |
| 3075 | fields[i]: (row[i] if i < len(row) else "") |
| 3076 | for i in range(field_count) |
| 3077 | } |
| 3078 | records.append(record) |
| 3079 | |
| 3080 | return records |
| 3081 | |
| 3082 | |
| 3083 | def _committed_prefix_len(text: str) -> int: |
| 3084 | """Char length of the prefix of `text` ending at the last CSV ROW |
| 3085 | TERMINATOR -- a "\\n" seen OUTSIDE a quoted field. |
| 3086 | |
| 3087 | QUOTE-AWARE, single O(len) forward pass tracking csv quote state: a "\\n" |
| 3088 | INSIDE a quoted field (a multi-line cell) is field content, never a row |
| 3089 | boundary. "" inside a quoted field is an escaped quote (stays quoted), |
| 3090 | matching csv QUOTE_MINIMAL/QUOTE_ALL. Everything after the last real |
| 3091 | terminator is an incomplete (torn) trailing row -- an interrupted write -- |
| 3092 | and is excluded. This can only ever trim a torn TAIL, never bisect a |
| 3093 | committed row. |
| 3094 | """ |
| 3095 | # Whether a position is inside a quoted field is just "has an odd number |
| 3096 | # of '"' gone by": a quote toggles the state, and an escaped "" inside a |
| 3097 | # field is two toggles, which cancels. So instead of walking every |
| 3098 | # character in Python (this runs over the WHOLE file on every append-mode |
| 3099 | # write that finds no warm sidecar -- ~270ms at 100k rows), look for the |
| 3100 | # last "\n" with str.rfind and decide quoted-or-not from a quote COUNT, |
| 3101 | # both at C speed. Quotes are counted once per segment, so the whole scan |
| 3102 | # stays O(len) even for a file that is mostly newlines inside quotes. |
| 3103 | # Identical result to the character loop this replaced (checked against |
| 3104 | # it on 300k random strings and on the repo's torn-tail suites). |
| 3105 | total_quotes = text.count('"') |
| 3106 | tail_quotes = 0 # quotes in text[end:] |
| 3107 | end = len(text) |
| 3108 | while True: |
| 3109 | i = text.rfind("\n", 0, end) |
| 3110 | if i < 0: |
| 3111 | return 0 |
| 3112 | tail_quotes += text.count('"', i + 1, end) |
| 3113 | if (total_quotes - tail_quotes) % 2 == 0: # not inside a quoted field |
| 3114 | return i + 1 |
| 3115 | end = i |
| 3116 | |
| 3117 | |
| 3118 | # Public alias. `_committed_prefix_len` is the one correct answer to "where |
| 3119 | # does the last complete CSV row end", and it is needed in more than one |
| 3120 | # module: object_backup_index parses records.tsv out of a backup archive on |
| 3121 | # the restore path and must reach the same verdict. |
| 3122 | # |
| 3123 | # It is exported rather than copied because the copy is what went wrong. |
| 3124 | # object_backup_index kept its own `_drop_torn_tail` with a docstring saying |
| 3125 | # it "mirrors object_records._drop_torn_tail" -- and when this module's copy |
| 3126 | # was upgraded to be quote-aware, the mirror was not, silently, for months. |
| 3127 | # Two implementations of one invariant drift; one implementation cannot. |
| 3128 | committed_prefix_len = _committed_prefix_len |
| 3129 | |
| 3130 | |
| 3131 | def _drop_torn_tail(text: str) -> str: |
| 3132 | """Return `text` truncated to the end of its last COMPLETE csv row. |
| 3133 | |
| 3134 | QUOTE-AWARE. This was previously a quote-BLIND check ("ends with \\n", else |
| 3135 | rfind the last \\n) which mistook a "\\n" INSIDE a quoted multi-line field |
| 3136 | for a row boundary -- silently resurrecting a torn multi-line row and, in |
| 3137 | append mode, cascading to swallow later writes (the torn-write durability |
| 3138 | characterization mapped this to ~97% of a multi-line row's write window). |
| 3139 | A row is committed only when a row-terminating "\\n" (outside any quoted |
| 3140 | field) follows it; anything after the last such terminator is an |
| 3141 | interrupted write and is dropped. |
| 3142 | |
| 3143 | Fast path: a text containing no '"' at all has no quoted fields, so every |
| 3144 | "\\n" is a row terminator and the cheap check is exact -- this keeps |
| 3145 | collections whose cells never need quoting (no tab/quote/newline in any |
| 3146 | value) on the original O(1)/rfind path. Only text with quoting pays the |
| 3147 | O(len) quote-aware scan, and that path is already parsing the same text. |
| 3148 | """ |
| 3149 | if text == "": |
| 3150 | return text |
| 3151 | if '"' not in text: |
| 3152 | if text.endswith("\n"): |
| 3153 | return text |
| 3154 | cut = text.rfind("\n") |
| 3155 | return text[: cut + 1] if cut >= 0 else "" |
| 3156 | return text[:_committed_prefix_len(text)] |
| 3157 | |
| 3158 | |
| 3159 | def _parse_append_body( |
| 3160 | collection: str, text: str, physical_fields: list[str], *, committed: bool = False |
| 3161 | ) -> tuple[list[dict[str, str]], int]: |
| 3162 | """Parse+fold an append-mode file's body. Returns (folded_records, physical_row_count). |
| 3163 | |
| 3164 | Torn-tail tolerant: a trailing unterminated line is dropped first |
| 3165 | (_drop_torn_tail); a row that still fails to parse (e.g. a value with |
| 3166 | an embedded newline whose closing quote never arrived, so its |
| 3167 | apparent line boundary landed mid-field) stops consumption at that |
| 3168 | point rather than raising -- everything after an unparseable point is, |
| 3169 | by construction, either that same torn write or unreachable. This |
| 3170 | differs from classic mode, which keeps raising on malformed content |
| 3171 | (see _parse_classic_records): append mode's contract is specifically |
| 3172 | that in-flight writes are tolerated, not silently-corrupt files. |
| 3173 | """ |
| 3174 | field_count = len(physical_fields) |
| 3175 | # `committed`: the caller already cut `text` to its committed prefix |
| 3176 | # (_parse_records_file, which needs that length) -- the quote-aware cut |
| 3177 | # is a full scan, so it is not paid twice. |
| 3178 | reader = csv.reader(io.StringIO(text if committed else _drop_torn_tail(text)), |
| 3179 | delimiter="\t") |
| 3180 | next(reader, None) # header, already parsed/validated by the caller |
| 3181 | |
| 3182 | physical_rows: list[dict[str, str]] = [] |
| 3183 | while True: |
| 3184 | try: |
| 3185 | row = next(reader) |
| 3186 | except StopIteration: |
| 3187 | break |
| 3188 | except csv.Error: |
| 3189 | break |
| 3190 | if not row: |
| 3191 | continue |
| 3192 | if len(row) > field_count: |
| 3193 | raise ValueError( |
| 3194 | f"Collection records file has extra fields: {collection}" |
| 3195 | ) |
| 3196 | record = { |
| 3197 | physical_fields[i]: (row[i] if i < len(row) else "") |
| 3198 | for i in range(field_count) |
| 3199 | } |
| 3200 | physical_rows.append(record) |
| 3201 | |
| 3202 | return _fold_append_rows(physical_rows), len(physical_rows) |
| 3203 | |
| 3204 | |
| 3205 | def _fold_append_rows(physical_rows: list[dict[str, str]]) -> list[dict[str, str]]: |
| 3206 | """Fold physical append-mode rows into live records, last-wins per id. |
| 3207 | |
| 3208 | An id's position in the returned list is where it was inserted since |
| 3209 | it was last live: an upsert for an id already present updates it in |
| 3210 | place (same position, matching classic mode's update-in-place); an |
| 3211 | upsert for a not-currently-live id inserts at the current end |
| 3212 | (matching classic mode's create-appends); a delete (`_op == "del"`) |
| 3213 | removes the id's slot entirely (matching classic mode's delete |
| 3214 | popping the row) -- so a later upsert for that same id is a fresh |
| 3215 | insertion at the end, not a return to its old position. Built with an |
| 3216 | OrderedDict so this falls out of normal dict semantics rather than |
| 3217 | needing to be modeled by hand; this is what gives append mode the |
| 3218 | same list order as classic mode for the same operation sequence (see |
| 3219 | the equivalence tests in tests/test_object_records.py). `_op` is |
| 3220 | stripped from every folded record. |
| 3221 | |
| 3222 | Rows with a blank/missing id (only reachable via a hand-edited file -- |
| 3223 | every write path in this module requires a valid id) cannot be |
| 3224 | last-wins folded against each other for lack of a key; each is kept as |
| 3225 | its own entry and appended after the id-keyed records, which does not |
| 3226 | preserve their original interleaving with id-keyed rows. This is a |
| 3227 | documented limitation of a pre-existing edge case, not a behavior this |
| 3228 | feature needs to support: normalize_record_payload never lets a create |
| 3229 | omit its id, and update always operates on an already-valid id. |
| 3230 | """ |
| 3231 | folded: "OrderedDict[str, dict[str, str]]" = OrderedDict() |
| 3232 | blank_id_rows: list[dict[str, str]] = [] |
| 3233 | blank_counter = 0 |
| 3234 | for row in physical_rows: |
| 3235 | op = row.get(OP_FIELD, OP_UPSERT) |
| 3236 | record_id = row.get("id", "") |
| 3237 | clean = {key: value for key, value in row.items() if key != OP_FIELD} |
| 3238 | if not record_id: |
| 3239 | if op == OP_DELETE: |
| 3240 | continue |
| 3241 | blank_id_rows.append((f"__blank__{blank_counter}", clean)) |
| 3242 | blank_counter += 1 |
| 3243 | continue |
| 3244 | if op == OP_DELETE: |
| 3245 | folded.pop(record_id, None) |
| 3246 | continue |
| 3247 | folded[record_id] = clean |
| 3248 | |
| 3249 | return list(folded.values()) + [record for _, record in blank_id_rows] |
| 3250 | |
| 3251 | |
| 3252 | def _scan_append_tail( |
| 3253 | path: Path, physical_fields: list[str], start_byte: int |
| 3254 | ) -> tuple[list[tuple[int, int, dict[str, str]]], int]: |
| 3255 | """Read and parse complete physical rows of an append-mode file from |
| 3256 | `start_byte` to EOF, returning (rows, covered_bytes) where each row is |
| 3257 | (row_start_offset, row_end_offset, physical_record) -- `physical_record` |
| 3258 | keyed by every column in `physical_fields`, `_op` included, exactly |
| 3259 | like a row from _parse_append_body before folding. `covered_bytes` is |
| 3260 | the byte offset up to which parsing is authoritative (>= start_byte, |
| 3261 | equal to it when nothing new/complete was found). `start_byte` must |
| 3262 | land exactly on a row boundary -- every offset any caller ever hands |
| 3263 | back here (a prior scan/cache entry's covered_bytes, or the |
| 3264 | records-header length) always does, since it is always either 0 or a |
| 3265 | previous row's end. |
| 3266 | |
| 3267 | Torn-tail tolerant exactly like _parse_append_body: a trailing |
| 3268 | unterminated physical line is dropped first (_drop_torn_tail), and a |
| 3269 | row that still fails to parse (or reports more fields than the header |
| 3270 | -- real corruption, not a torn write) stops consumption at that point |
| 3271 | rather than raising. NEVER raises: this is the shared low-level scan |
| 3272 | behind two callers that both need "read complete new rows appended |
| 3273 | since an earlier point, without re-reading or re-folding the whole |
| 3274 | file" -- the id->offset sidecar's incremental catch-up |
| 3275 | (_scan_append_rows_for_offsets, which projects each row down to just |
| 3276 | its (op, id) for the offset index) and the records-cache's tail-delta |
| 3277 | incremental fold (_append_tail_delta_records, which keeps every field |
| 3278 | since it must produce real records). Neither caller may raise either, |
| 3279 | so this doesn't. |
| 3280 | |
| 3281 | Byte offsets are computed by decoding `path`'s bytes from `start_byte` |
| 3282 | once, then, after each row csv.reader consumes, converting the |
| 3283 | now-consumed prefix of that decoded text back to its exact byte |
| 3284 | length (`str.encode` on the newly consumed slice only, not the whole |
| 3285 | prefix each time, so total work stays O(scanned bytes) instead of |
| 3286 | O(scanned bytes squared)). `start_byte` itself is always a byte |
| 3287 | offset immediately after a "\\n", which is a single ASCII byte and |
| 3288 | therefore never a UTF-8 continuation byte -- so slicing raw bytes from |
| 3289 | there and decoding is always safe. |
| 3290 | """ |
| 3291 | try: |
| 3292 | with path.open("rb") as handle: |
| 3293 | handle.seek(start_byte) |
| 3294 | raw = handle.read() |
| 3295 | except OSError: |
| 3296 | return [], start_byte |
| 3297 | if not raw: |
| 3298 | return [], start_byte |
| 3299 | |
| 3300 | try: |
| 3301 | text = raw.decode("utf-8") |
| 3302 | except UnicodeDecodeError: |
| 3303 | return [], start_byte |
| 3304 | text = _drop_torn_tail(text) |
| 3305 | if not text: |
| 3306 | return [], start_byte |
| 3307 | |
| 3308 | field_count = len(physical_fields) |
| 3309 | stream = io.StringIO(text) |
| 3310 | reader = csv.reader(stream, delimiter="\t") |
| 3311 | rows: list[tuple[int, int, dict[str, str]]] = [] |
| 3312 | prev_char = 0 |
| 3313 | byte_cursor = start_byte |
| 3314 | while True: |
| 3315 | try: |
| 3316 | row = next(reader) |
| 3317 | except StopIteration: |
| 3318 | break |
| 3319 | except csv.Error: |
| 3320 | break |
| 3321 | cur_char = stream.tell() |
| 3322 | row_bytes = len(text[prev_char:cur_char].encode("utf-8")) |
| 3323 | prev_char = cur_char |
| 3324 | row_start = byte_cursor |
| 3325 | row_end = byte_cursor + row_bytes |
| 3326 | byte_cursor = row_end |
| 3327 | if not row: |
| 3328 | continue |
| 3329 | if len(row) > field_count: |
| 3330 | break |
| 3331 | record = { |
| 3332 | physical_fields[i]: (row[i] if i < len(row) else "") |
| 3333 | for i in range(field_count) |
| 3334 | } |
| 3335 | rows.append((row_start, row_end, record)) |
| 3336 | |
| 3337 | return rows, byte_cursor |
| 3338 | |
| 3339 | |
| 3340 | def _append_tail_delta_records( |
| 3341 | path: Path, physical_fields: list[str], start_byte: int |
| 3342 | ) -> tuple[list[dict[str, str]], int]: |
| 3343 | """Parse complete physical rows appended to an append-mode file since |
| 3344 | `start_byte`, returning (physical_rows, covered_bytes) -- a thin |
| 3345 | projection of _scan_append_tail down to just the row dicts (`_op` |
| 3346 | included, unfolded), for _try_incremental_cache_entry's tail-delta |
| 3347 | fold. See _scan_append_tail for the shared torn-tail-tolerant scan |
| 3348 | this builds on: never raises, stops at the first row it can't make |
| 3349 | sense of. |
| 3350 | """ |
| 3351 | scanned, covered_bytes = _scan_append_tail(path, physical_fields, start_byte) |
| 3352 | return [record for _, _, record in scanned], covered_bytes |
| 3353 | |
| 3354 | |
| 3355 | def _append_compact_min_rows() -> int: |
| 3356 | return _env_int(APPEND_COMPACT_MIN_ROWS_ENV, _DEFAULT_APPEND_COMPACT_MIN_ROWS) |
| 3357 | |
| 3358 | |
| 3359 | def append_compact_min_rows() -> int: |
| 3360 | """Public read of DBBASIC_APPEND_COMPACT_MIN_ROWS (default 10_000). |
| 3361 | |
| 3362 | Exists so callers outside this module (object_daemon.py's |
| 3363 | process_compactions) can apply the exact same physical-row-count floor |
| 3364 | _maybe_flag_auto_compact uses for its own auto-compaction trigger, |
| 3365 | without duplicating the env var's default value. |
| 3366 | """ |
| 3367 | return _append_compact_min_rows() |
| 3368 | |
| 3369 | |
| 3370 | def _maybe_flag_auto_compact(path: Path, *, physical_row_count: int, live_row_count: int) -> None: |
| 3371 | """Flag a collection for compaction on its NEXT WRITE. |
| 3372 | |
| 3373 | Never compacts here -- this runs from the read/parse path, and reads |
| 3374 | must stay read-only (docs/append-only-storage-design.md Compaction). |
| 3375 | Triggers when the physical file is at least DBBASIC_APPEND_COMPACT_ |
| 3376 | MIN_ROWS rows (so a small collection's ordinary churn never matters) |
| 3377 | AND superseded-or-deleted rows outnumber live rows. |
| 3378 | """ |
| 3379 | if physical_row_count <= _append_compact_min_rows(): |
| 3380 | return |
| 3381 | stale_row_count = physical_row_count - live_row_count |
| 3382 | if stale_row_count > live_row_count: |
| 3383 | _PENDING_COMPACTION.add(str(path.resolve(strict=False))) |
| 3384 | |
| 3385 | |
| 3386 | def _physical_header(path: Path) -> list[str] | None: |
| 3387 | """Return the raw on-disk header (leading `_op` included, if present). |
| 3388 | |
| 3389 | None when the file doesn't exist or is empty. Cheap: reads only the |
| 3390 | first physical line, not the whole file. |
| 3391 | """ |
| 3392 | if not path.exists(): |
| 3393 | return None |
| 3394 | with path.open(newline="") as handle: |
| 3395 | reader = csv.reader(handle, delimiter="\t") |
| 3396 | try: |
| 3397 | return next(reader) |
| 3398 | except StopIteration: |
| 3399 | return None |
| 3400 | |
| 3401 | |
| 3402 | def _write_collection_records( |
| 3403 | collection: str, |
| 3404 | path: Path, |
| 3405 | fields: list[str], |
| 3406 | records: list[dict[str, str]], |
| 3407 | *, |
| 3408 | cache_fields: list[str] | None = None, |
| 3409 | ) -> None: |
| 3410 | """Rewrite the whole records file atomically (temp file + replace). |
| 3411 | |
| 3412 | `fields` is the PHYSICAL header to write -- for an append-mode full |
| 3413 | rewrite (transition-in, compaction, or the new-field-fallback rewrite; |
| 3414 | see _persist_write) this includes a leading `_op` column, which every |
| 3415 | record in `records` implicitly projects to "" (upsert) since none of |
| 3416 | them carry an `_op` key (docs/append-only-storage-design.md). |
| 3417 | `cache_fields`, when given, is the LOGICAL field list (without `_op`) |
| 3418 | to store in the module cache instead of `fields` -- callers writing an |
| 3419 | append-format file must pass this, or `_op` would leak into the cache |
| 3420 | and, from there, into API responses (get/list/create/update all |
| 3421 | return cache-derived data). Classic-mode callers omit it and the |
| 3422 | written `fields` doubles as the cache's fields, exactly as before this |
| 3423 | parameter existed. |
| 3424 | """ |
| 3425 | if "id" not in fields: |
| 3426 | fields = ["id", *fields] |
| 3427 | |
| 3428 | path.parent.mkdir(parents=True, exist_ok=True) |
| 3429 | temp_path = path.with_name(f".{path.name}.{os.getpid()}.{threading.get_ident()}.tmp") |
| 3430 | try: |
| 3431 | with temp_path.open("w", newline="") as handle: |
| 3432 | writer = csv.DictWriter( |
| 3433 | handle, |
| 3434 | fieldnames=fields, |
| 3435 | delimiter="\t", |
| 3436 | lineterminator="\n", |
| 3437 | extrasaction="ignore", |
| 3438 | quoting=(csv.QUOTE_ALL if _rows_need_full_quoting(records) else csv.QUOTE_MINIMAL), |
| 3439 | ) |
| 3440 | writer.writeheader() |
| 3441 | for record in records: |
| 3442 | writer.writerow(_project_record(record, fields)) |
| 3443 | temp_path.replace(path) |
| 3444 | finally: |
| 3445 | if temp_path.exists(): |
| 3446 | temp_path.unlink() |
| 3447 | |
| 3448 | _refresh_records_cache(collection, path, cache_fields if cache_fields is not None else fields, records) |
| 3449 | |
| 3450 | |
| 3451 | def _refresh_records_cache( |
| 3452 | collection: str, |
| 3453 | path: Path, |
| 3454 | fields: list[str], |
| 3455 | records: list[dict[str, str]], |
| 3456 | ) -> None: |
| 3457 | """Populate the module cache with the content just written to `path`. |
| 3458 | |
| 3459 | Called immediately after the atomic replace above, under the caller's |
| 3460 | _records_file_lock, so this process's view of the file is authoritative |
| 3461 | right now. Storing the new content (rather than merely invalidating) |
| 3462 | means the next read for this collection -- often the same request, |
| 3463 | returning its own write -- skips re-parsing the file it just wrote. |
| 3464 | |
| 3465 | If the post-write stat can't be trusted (the file vanished, or some |
| 3466 | other OSError), skip caching entirely rather than caching something |
| 3467 | stale or guessed: the next reader will just parse fresh, same as |
| 3468 | before this change existed. |
| 3469 | |
| 3470 | Honors the same DBBASIC_RECORDS_CACHE_MAX_ROWS threshold as |
| 3471 | _cache_entry: a write that grows a collection past the threshold is |
| 3472 | not cached (and any stale smaller-collection entry under this key is |
| 3473 | dropped), so a single giant write can't occupy an LRU slot. |
| 3474 | """ |
| 3475 | signature = _stat_signature(path) |
| 3476 | if signature is None: |
| 3477 | return |
| 3478 | |
| 3479 | cache_key = str(path.resolve(strict=False)) |
| 3480 | if len(records) > _records_cache_max_rows(): |
| 3481 | _RECORDS_CACHE.pop(cache_key, None) |
| 3482 | return |
| 3483 | |
| 3484 | # Project every record to the full field set before caching, so a |
| 3485 | # cache hit yields exactly what a fresh parse of this file would |
| 3486 | # yield (same as what was just written: `_project_record` fills any |
| 3487 | # field missing from a given record with "", matching how |
| 3488 | # csv.DictWriter/extrasaction wrote that row). |
| 3489 | cached_records = [_project_record(record, fields) for record in records] |
| 3490 | id_index = _build_id_index(cached_records) |
| 3491 | _store_records_cache(cache_key, signature, list(fields), cached_records, id_index, signature[1]) |
| 3492 | |
| 3493 | |
| 3494 | def _refresh_records_cache_after_append( |
| 3495 | collection: str, |
| 3496 | path: Path, |
| 3497 | fields: list[str], |
| 3498 | delta_op: str, |
| 3499 | delta_id: str, |
| 3500 | projected_row: dict[str, str], |
| 3501 | *, |
| 3502 | start_offset: int, |
| 3503 | ) -> bool: |
| 3504 | """Incrementally update the cache after a fast append. Returns True if |
| 3505 | it did (the caller then skips the full _refresh_records_cache rebuild). |
| 3506 | |
| 3507 | `start_offset` is the byte offset at which this append's row begins |
| 3508 | (what _append_records_rows returned). The prior entry is only built on |
| 3509 | when it covers the file exactly up to that offset, on the same inode -- |
| 3510 | i.e. when it described the file as it stood just before this append. |
| 3511 | If ANOTHER PROCESS appended in between, the prior entry stops short of |
| 3512 | `start_offset`, and deriving the new entry from it would produce a |
| 3513 | list that is missing their rows yet carries the file's current |
| 3514 | signature: a stale entry that passes its own freshness check. That |
| 3515 | shipped. Their record then did not exist in this process -- not in a |
| 3516 | list, not by id -- and the duplicate-id check passed for it, so a |
| 3517 | create with their id was accepted and (append mode folds a repeated id |
| 3518 | as an update) overwrote their record. _update_oidx_after_append, the |
| 3519 | sidecar's twin of this function, has always had this check. |
| 3520 | A prior entry that stops short is left exactly as it is: its old |
| 3521 | signature no longer matches, so the next read goes to |
| 3522 | _try_incremental_cache_entry, which folds everything after its |
| 3523 | covered_bytes -- their rows and this one -- which is what that function |
| 3524 | is for. A prior entry that claims to cover PAST `start_offset` (it was |
| 3525 | parsed while a torn tail was on disk, since truncated) describes bytes |
| 3526 | that are gone, and is dropped. |
| 3527 | |
| 3528 | The entire point of the fast-append path is O(1) disk work -- calling |
| 3529 | the general _refresh_records_cache after every append would silently |
| 3530 | reintroduce an O(n) cost per write, just moved from disk I/O to cache |
| 3531 | bookkeeping (a full re-projection of every record plus a full |
| 3532 | id_index rebuild). This instead derives the new cache entry from the |
| 3533 | PRIOR entry plus this one delta: |
| 3534 | |
| 3535 | - create (an id not already in the index): `old_records + [row]` |
| 3536 | and `dict(old_id_index)` plus one new key -- still technically |
| 3537 | O(n) (a fresh list/dict must be built; nothing cached is ever |
| 3538 | mutated in place, see the ALIASING SAFETY note on |
| 3539 | _RECORDS_CACHE), but as bulk C-level copies (list concat, dict |
| 3540 | copy) rather than a Python-level per-record rebuild. |
| 3541 | - update (an id already in the index -- always at the SAME |
| 3542 | position, since _fold_append_rows updates in place): `list( |
| 3543 | old_records)` with one element replaced; the id_index is REUSED |
| 3544 | UNCHANGED (no copy at all), since no id's position moved. |
| 3545 | - delete: a genuine O(n) Python-level index rebuild (removing a |
| 3546 | position means every later position shifts down by one) -- the |
| 3547 | one case this doesn't make cheap. Deletes are the rare case for |
| 3548 | the append-shaped workloads this feature targets (game-server |
| 3549 | state, impression logs, price history), so this is an accepted, |
| 3550 | documented trade rather than a gap. |
| 3551 | |
| 3552 | Returns False when there is no usable prior entry to build on -- cold |
| 3553 | cache, evicted, over the row-count cache threshold, or (defensively) |
| 3554 | a fields mismatch. The caller (_persist_write's fast-append branch) |
| 3555 | does NOT force a full rebuild in that case (an earlier version of |
| 3556 | this code did, via folded_records_fn() + _refresh_records_cache -- |
| 3557 | exactly the O(n)-per-write cost the id->offset sidecar, docs/append- |
| 3558 | only-storage-design.md item 4, exists to eliminate for a collection |
| 3559 | too large to be a "usable prior entry" in the first place). A False |
| 3560 | return simply leaves _RECORDS_CACHE as it was: the next reader either |
| 3561 | hits the sidecar (if the file is append-physical and over threshold) |
| 3562 | or pays one full fold on a genuine cold/small-collection miss, same |
| 3563 | as any other cache miss elsewhere in this module. |
| 3564 | """ |
| 3565 | signature = _stat_signature(path) |
| 3566 | if signature is None: |
| 3567 | return True # nothing to cache either way; nothing left to do |
| 3568 | |
| 3569 | cache_key = str(path.resolve(strict=False)) |
| 3570 | prior = _RECORDS_CACHE.get(cache_key) |
| 3571 | if prior is None or prior[1] != fields: |
| 3572 | return False |
| 3573 | |
| 3574 | prior_signature, _prior_fields, old_records, old_id_index, prior_covered = prior |
| 3575 | if prior_covered != start_offset or prior_signature[2] != signature[2]: |
| 3576 | if prior_covered > start_offset: |
| 3577 | _RECORDS_CACHE.pop(cache_key, None) |
| 3578 | return False |
| 3579 | if len(old_records) > _records_cache_max_rows(): |
| 3580 | _RECORDS_CACHE.pop(cache_key, None) |
| 3581 | return True |
| 3582 | |
| 3583 | if delta_op == OP_DELETE: |
| 3584 | idx = old_id_index.get(delta_id) |
| 3585 | if idx is None: |
| 3586 | return False |
| 3587 | new_records = old_records[:idx] + old_records[idx + 1:] |
| 3588 | new_id_index = { |
| 3589 | key: (value if value < idx else value - 1) |
| 3590 | for key, value in old_id_index.items() |
| 3591 | if key != delta_id |
| 3592 | } |
| 3593 | else: |
| 3594 | idx = old_id_index.get(delta_id) |
| 3595 | if idx is not None: |
| 3596 | new_records = list(old_records) |
| 3597 | new_records[idx] = projected_row |
| 3598 | new_id_index = old_id_index |
| 3599 | else: |
| 3600 | new_records = old_records + [projected_row] |
| 3601 | new_id_index = dict(old_id_index) |
| 3602 | new_id_index[delta_id] = len(old_records) |
| 3603 | |
| 3604 | if len(new_records) > _records_cache_max_rows(): |
| 3605 | _RECORDS_CACHE.pop(cache_key, None) |
| 3606 | return True |
| 3607 | |
| 3608 | # This process just performed the append that produced `signature`, so |
| 3609 | # it authoritatively covers the whole current file, same as any other |
| 3610 | # fully-covering entry (see the covered_bytes bullet in the |
| 3611 | # _RECORDS_CACHE block comment above). |
| 3612 | _store_records_cache(cache_key, signature, list(fields), new_records, new_id_index, signature[1]) |
| 3613 | return True |
| 3614 | |
| 3615 | |
| 3616 | def _repair_torn_tail_lines(path: Path) -> None: |
| 3617 | """Trim a torn trailing LINE from a line-oriented file (the sidecar). |
| 3618 | |
| 3619 | Backward rfind(b"\n") -- quote-BLIND, and correct HERE, for exactly one |
| 3620 | reason: an idx line can never contain a literal tab or newline inside a |
| 3621 | field (ids are restricted to _RECORD_ID_RE; offsets and op are plain |
| 3622 | digits/literals), so "the file ends with \n" really is a complete |
| 3623 | completeness signal for the sidecar. |
| 3624 | |
| 3625 | It is NOT correct for records.tsv, whose quoted cells may hold |
| 3626 | newlines. That distinction is why this is now a separate function: the |
| 3627 | data file's repair below is quote-aware and costs a scan, and pointing |
| 3628 | the sidecar at it would spend that scan on every append to buy nothing. |
| 3629 | Do not "unify" these; they were one function once, and the shared body |
| 3630 | was wrong for one caller and slow for the other. |
| 3631 | """ |
| 3632 | try: |
| 3633 | size = path.stat().st_size |
| 3634 | except OSError: |
| 3635 | return |
| 3636 | if size == 0: |
| 3637 | return |
| 3638 | |
| 3639 | with path.open("rb+") as handle: |
| 3640 | handle.seek(size - 1) |
| 3641 | if handle.read(1) == b"\n": |
| 3642 | return |
| 3643 | |
| 3644 | window = 8192 |
| 3645 | read_from = size |
| 3646 | while read_from > 0: |
| 3647 | read_from = max(0, read_from - window) |
| 3648 | handle.seek(read_from) |
| 3649 | chunk = handle.read(size - read_from) |
| 3650 | idx = chunk.rfind(b"\n") |
| 3651 | if idx >= 0: |
| 3652 | handle.truncate(read_from + idx + 1) |
| 3653 | return |
| 3654 | window *= 2 |
| 3655 | handle.truncate(0) |
| 3656 | |
| 3657 | |
| 3658 | def _repair_torn_tail(path: Path) -> None: |
| 3659 | """Ensure records.tsv ends at a committed CSV row boundary before an |
| 3660 | append lands. QUOTE-AWARE -- substrate bug #2's write side, fixed. |
| 3661 | |
| 3662 | A write interrupted mid-row leaves a fragment; appending after it |
| 3663 | would concatenate the next row onto the fragment -- and if the |
| 3664 | fragment holds an unclosed quoted field, silently swallow that next |
| 3665 | row. The previous body found "the last row boundary" with |
| 3666 | rfind(b"\n"), which mistakes a newline INSIDE a quoted multi-line |
| 3667 | field for a boundary; worse, its fast path returned immediately |
| 3668 | whenever the file's last byte was "\n" -- including a newline inside |
| 3669 | an unclosed quote -- so the very case that needed repair was the case |
| 3670 | it skipped. Exposure was ~97% of a multi-line row's write window. |
| 3671 | |
| 3672 | ## Why the first fix was reverted, and what this one does differently |
| 3673 | |
| 3674 | The 2026-07-20 attempt gated correctness on _RECORDS_CACHE's |
| 3675 | covered_bytes. That value lives ONLY in process memory -- the on-disk |
| 3676 | sidecar header records just the inode -- so the gate read state the |
| 3677 | test harness happened to share: under pytest one interpreter runs the |
| 3678 | whole suite and the cache was warm from other tests' files; standalone |
| 3679 | it was cold every time. "Fails in pytest, passes standalone" was never |
| 3680 | a race; it was a correctness decision delegated to a cache. And a torn |
| 3681 | tail only exists after a process DIED, which is exactly when no cache |
| 3682 | exists. |
| 3683 | |
| 3684 | So the rule here, stated so nobody re-learns it: **a cache may only |
| 3685 | ever SKIP this repair, never choose where it truncates.** |
| 3686 | |
| 3687 | ## How it works |
| 3688 | |
| 3689 | 1. SKIP (sound): a warm _OIDX_CACHE entry, inode-matched, whose |
| 3690 | covered_bytes equals the file's size right now. Every covered value |
| 3691 | in that cache is a genuine committed row boundary (from |
| 3692 | _scan_append_tail, which excludes torn tails, or from this |
| 3693 | process's own completed append), so EOF landing exactly on one |
| 3694 | proves the file is clean. _RECORDS_CACHE is deliberately NOT |
| 3695 | consulted -- see the inline comment for why its covered_bytes lies |
| 3696 | about exactly the files that need repair, which is the probable |
| 3697 | mechanism of the original revert. |
| 3698 | 2. ANCHOR (cheap): the same sidecar-cache covered, when it is short of |
| 3699 | EOF, is a boundary to scan forward from instead of from zero. |
| 3700 | Append-mode files only ever grow in place (any rewrite is an atomic |
| 3701 | rename and changes the inode), and a correct repair never truncates |
| 3702 | below the last committed boundary, so bytes before a recorded |
| 3703 | boundary are stable under a matching inode. |
| 3704 | 3. SCAN: decode the tail with errors="surrogateescape" and take |
| 3705 | _committed_prefix_len -- THE quote-aware answer, the same single |
| 3706 | implementation the read path and object_backup_index use, because a |
| 3707 | second copy of this logic is how the backup module silently carried |
| 3708 | the bug for months. The char prefix is re-encoded to recover the |
| 3709 | exact byte length (surrogateescape round-trips arbitrary bytes). |
| 3710 | 4. Truncate to the last committed boundary found. With no anchor this |
| 3711 | is a full O(n) scan -- paid on the first append after a restart, |
| 3712 | which is the one moment a torn tail can actually exist. |
| 3713 | |
| 3714 | Deliberately NOT trusted: the on-disk sidecar's row_end offsets. They |
| 3715 | would be a durable anchor, but files damaged by the OLD repair may |
| 3716 | carry sidecar offsets that no longer sit on real boundaries, and |
| 3717 | anchoring the fix to state the bug may have corrupted would rebuild |
| 3718 | the bug. Process-local anchors are attested by this process's own |
| 3719 | reads and writes. |
| 3720 | |
| 3721 | The three strict-xfail acceptance tests that held this behaviour map |
| 3722 | the trigger surface; they were rewritten into regression guards when |
| 3723 | this landed. |
| 3724 | """ |
| 3725 | signature = _stat_signature(path) |
| 3726 | if signature is None: |
| 3727 | return |
| 3728 | size = signature[1] |
| 3729 | if size == 0: |
| 3730 | return |
| 3731 | |
| 3732 | cache_key = str(path.resolve(strict=False)) |
| 3733 | anchor = 0 |
| 3734 | |
| 3735 | # ONLY the sidecar cache. _RECORDS_CACHE is deliberately not consulted, |
| 3736 | # and the reason is the probable mechanism of the original revert: a |
| 3737 | # FULL parse stores covered_bytes = signature[1] -- the whole file size |
| 3738 | # -- even when that parse dropped a torn tail (the read fold "accounts |
| 3739 | # for" the torn bytes by knowing they are torn). So on precisely the |
| 3740 | # file that needs repair, a warm records-cache entry reports |
| 3741 | # covered == size and looks like proof of a clean boundary. Warm cache |
| 3742 | # -> skip -> regression; cold cache -> scan -> correct. Under pytest |
| 3743 | # the cache is warm; standalone it is cold. That is the whole |
| 3744 | # "fails in pytest, passes standalone". |
| 3745 | # |
| 3746 | # _OIDX_CACHE's covered comes from _scan_append_tail, which returns the |
| 3747 | # offset up to which parsing is AUTHORITATIVE -- torn tails excluded -- |
| 3748 | # or from handle.tell() after this process's own completed append. |
| 3749 | # Every value in it is a genuine committed row boundary. |
| 3750 | oidx = _OIDX_CACHE.get(cache_key) |
| 3751 | if oidx is not None: |
| 3752 | oidx_ino, oidx_covered, _offsets = oidx |
| 3753 | if oidx_ino == signature[2] and 0 < oidx_covered <= size: |
| 3754 | if oidx_covered == size: |
| 3755 | return # EOF sits exactly on a recorded boundary |
| 3756 | anchor = oidx_covered |
| 3757 | |
| 3758 | with path.open("rb+") as handle: |
| 3759 | handle.seek(anchor) |
| 3760 | data = handle.read(size - anchor) |
| 3761 | text = data.decode("utf-8", errors="surrogateescape") |
| 3762 | keep_chars = _committed_prefix_len(text) |
| 3763 | committed = anchor + len( |
| 3764 | text[:keep_chars].encode("utf-8", errors="surrogateescape") |
| 3765 | ) |
| 3766 | if committed < size: |
| 3767 | handle.truncate(committed) |
| 3768 | |
| 3769 | |
| 3770 | def _append_records_rows( |
| 3771 | path: Path, |
| 3772 | physical_fields: list[str], |
| 3773 | rows: list[dict[str, str]], |
| 3774 | ) -> list[tuple[int, int]]: |
| 3775 | """Append one or more pre-built physical rows to an append-format file. |
| 3776 | |
| 3777 | Each row in `rows` must already carry an `_op` key (OP_UPSERT or |
| 3778 | OP_DELETE). Self-heals a torn tail first (_repair_torn_tail) so the |
| 3779 | new row(s) always land as clean, complete physical lines, then writes |
| 3780 | via csv.writer (not DictWriter -- rows are already fully projected) |
| 3781 | on a text-mode "a" handle, flushing once at the end. Same dialect as |
| 3782 | _write_collection_records: tab-delimited, "\\n" line terminator, |
| 3783 | QUOTE_MINIMAL. |
| 3784 | |
| 3785 | Returns the (row_start_offset, row_end_offset) byte span written for |
| 3786 | each row, in order -- _persist_write hands these straight to the id |
| 3787 | sidecar (_update_oidx_after_append) so it never has to re-derive them |
| 3788 | with a separate stat or scan. `handle.tell()` on a text-mode stream is |
| 3789 | only reliably a byte offset when nothing has been read from it in |
| 3790 | this session (reading with a stateful decoder can return an opaque |
| 3791 | cookie instead); a pure sequential-write "a" session like this one |
| 3792 | never reads, so it's exact here -- verified empirically (UTF-8, |
| 3793 | non-ASCII content, mid-stream tell() calls all matched the file's |
| 3794 | actual byte length). |
| 3795 | """ |
| 3796 | _repair_torn_tail(path) |
| 3797 | offsets: list[tuple[int, int]] = [] |
| 3798 | with path.open("a", newline="") as handle: |
| 3799 | writer = csv.writer( |
| 3800 | handle, delimiter="\t", lineterminator="\n", |
| 3801 | quoting=(csv.QUOTE_ALL if _rows_need_full_quoting(rows) else csv.QUOTE_MINIMAL), |
| 3802 | ) |
| 3803 | if handle.tell() == 0: |
| 3804 | # The file has no committed content -- most likely the repair |
| 3805 | # above found a TORN HEADER (intact bytes, no terminating |
| 3806 | # newline: external truncation clipping exactly the trailing |
| 3807 | # byte) and correctly truncated to zero. Appending a bare data |
| 3808 | # row here would leave a headerless file every subsequent read |
| 3809 | # rejects with an uncaught ValueError, having REPORTED SUCCESS |
| 3810 | # for this write -- the torn-header finding in |
| 3811 | # tests/test_durability_torn_write_characterization.py. The |
| 3812 | # header is fully determined by physical_fields, so restore it |
| 3813 | # rather than manufacturing a poisoned file. |
| 3814 | csv.writer(handle, delimiter="\t", lineterminator="\n").writerow( |
| 3815 | physical_fields |
| 3816 | ) |
| 3817 | for row in rows: |
| 3818 | start = handle.tell() |
| 3819 | projected = _project_record(row, physical_fields) |
| 3820 | writer.writerow([projected[field] for field in physical_fields]) |
| 3821 | offsets.append((start, handle.tell())) |
| 3822 | handle.flush() |
| 3823 | return offsets |
| 3824 | |
| 3825 | |
| 3826 | # --------------------------------------------------------------------------- |
| 3827 | # id -> byte-offset sidecar (docs/append-only-storage-design.md item 4). |
| 3828 | # |
| 3829 | # SCOPE: every function below is reached only from append-physical code |
| 3830 | # paths -- _fast_record_lookup only looks past a _peek_records_cache miss |
| 3831 | # into the sidecar when `_physical_header(path)[0] == OP_FIELD`, and |
| 3832 | # _persist_write/_write_collection_records only call _update_oidx_after_ |
| 3833 | # append/_discard_oidx on the append-mode branches. A collection that has |
| 3834 | # never been append-mode (no schema ever set "storage": "append") never |
| 3835 | # executes a line past that header check: its _physical_header is a plain |
| 3836 | # ["id", ...] with no leading `_op`, so the guard is false every time. |
| 3837 | # --------------------------------------------------------------------------- |
| 3838 | |
| 3839 | |
| 3840 | def _oidx_path(records_path: Path) -> Path: |
| 3841 | return records_path.with_name(OIDX_FILE) |
| 3842 | |
| 3843 | |
| 3844 | def _store_oidx_cache( |
| 3845 | cache_key: str, |
| 3846 | data_ino: int, |
| 3847 | covered_bytes: int, |
| 3848 | id_offsets: dict[str, int], |
| 3849 | ) -> None: |
| 3850 | _OIDX_CACHE[cache_key] = (data_ino, covered_bytes, id_offsets) |
| 3851 | _OIDX_CACHE.move_to_end(cache_key) |
| 3852 | max_entries = _oidx_cache_max_entries() |
| 3853 | while len(_OIDX_CACHE) > max_entries: |
| 3854 | _OIDX_CACHE.popitem(last=False) |
| 3855 | |
| 3856 | |
| 3857 | def _records_header_length(path: Path) -> int: |
| 3858 | """Byte length of records.tsv's own physical header line (newline |
| 3859 | included), or 0 if the file is empty/missing. Reads only the first |
| 3860 | physical line -- cheap regardless of file size.""" |
| 3861 | try: |
| 3862 | with path.open("rb") as handle: |
| 3863 | return len(handle.readline()) |
| 3864 | except OSError: |
| 3865 | return 0 |
| 3866 | |
| 3867 | |
| 3868 | def _scan_append_rows_for_offsets( |
| 3869 | path: Path, |
| 3870 | physical_fields: list[str], |
| 3871 | start_byte: int, |
| 3872 | ) -> tuple[list[tuple[int, int, str, str]], int, int]: |
| 3873 | """Scan records.tsv from `start_byte` to EOF for complete physical |
| 3874 | rows, returning (entries, covered_bytes, row_count). |
| 3875 | |
| 3876 | `entries` is one (row_start, row_end, op, id) per row found with a |
| 3877 | non-empty id (blank-id rows -- reachable only via a hand-edited file, |
| 3878 | see _fold_append_rows -- can't be looked up by id, so are simply never |
| 3879 | indexed, though they DO count towards `row_count`, matching |
| 3880 | _parse_append_body's physical_row_count exactly); `covered_bytes` is |
| 3881 | the byte offset up to which scanning is authoritative (>= start_byte, |
| 3882 | equal to it when nothing new/complete was found). `start_byte` must |
| 3883 | land exactly on a row boundary -- every offset this module ever hands |
| 3884 | back here (a prior scan's covered_bytes, or the records-header |
| 3885 | length) always does, since it is always either 0 or a previous |
| 3886 | row_end. |
| 3887 | |
| 3888 | Torn-tail tolerant exactly like _parse_append_body: a trailing |
| 3889 | unterminated physical line is dropped first (_drop_torn_tail), and a |
| 3890 | row that still fails to parse (or reports more fields than the header |
| 3891 | -- a real corruption, not a torn write) stops consumption at that |
| 3892 | point rather than raising. This function must NEVER raise: it is the |
| 3893 | sidecar's own scan, and the sidecar is never allowed to be less |
| 3894 | tolerant than the reader it exists to speed up (any row it can't |
| 3895 | make sense of just isn't indexed yet -- the caller's `coherent` flag, |
| 3896 | derived from comparing covered_bytes to the file's actual size, |
| 3897 | reports that honestly rather than guessing). |
| 3898 | |
| 3899 | Delegates the actual scan to _scan_append_tail (shared with the |
| 3900 | records-cache's tail-delta incremental fold, _append_tail_delta_ |
| 3901 | records) and projects each full physical row down to just (op, id) |
| 3902 | plus its byte span -- all this function's callers need. |
| 3903 | """ |
| 3904 | scanned, covered_bytes = _scan_append_tail(path, physical_fields, start_byte) |
| 3905 | entries: list[tuple[int, int, str, str]] = [] |
| 3906 | row_count = 0 |
| 3907 | for row_start, row_end, record in scanned: |
| 3908 | row_count += 1 |
| 3909 | record_id = record.get("id", "") |
| 3910 | if not record_id: |
| 3911 | continue |
| 3912 | op = record.get(OP_FIELD, OP_UPSERT) |
| 3913 | entries.append((row_start, row_end, op, record_id)) |
| 3914 | |
| 3915 | return entries, covered_bytes, row_count |
| 3916 | |
| 3917 | |
| 3918 | def _fold_oidx_entries( |
| 3919 | entries: list[tuple[int, int, str, str]], |
| 3920 | *, |
| 3921 | base: dict[str, int] | None = None, |
| 3922 | ) -> dict[str, int]: |
| 3923 | """Fold sidecar entries last-wins into {id: row_start_offset}, |
| 3924 | dropping deleted ids -- the same rule _fold_append_rows applies to |
| 3925 | full rows, applied here to bare offsets. |
| 3926 | |
| 3927 | Mutates and returns `base` directly when given, rather than copying |
| 3928 | it first: every call site's `base` is either freshly built moments |
| 3929 | earlier with nothing else referencing it (_load_oidx_body's return), |
| 3930 | or is _OIDX_CACHE's own entry being brought up to date in a catch-up |
| 3931 | that is about to replace that same cache slot anyway (see the |
| 3932 | matching note on _update_oidx_after_append for why this dict is safe |
| 3933 | to mutate in place: it's never exposed outside this module). A copy |
| 3934 | here would be a one-time-per-catch-up cost rather than a per-write |
| 3935 | one, so it's lower-stakes than the bug that note describes -- but |
| 3936 | there's no reason to pay even that when nothing needs the old |
| 3937 | version preserved. |
| 3938 | """ |
| 3939 | result = base if base is not None else {} |
| 3940 | for row_start, _row_end, op, record_id in entries: |
| 3941 | if op == OP_DELETE: |
| 3942 | result.pop(record_id, None) |
| 3943 | else: |
| 3944 | result[record_id] = row_start |
| 3945 | return result |
| 3946 | |
| 3947 | |
| 3948 | def _write_oidx_file( |
| 3949 | oidx_path: Path, data_ino: int, entries: list[tuple[int, int, str, str]] |
| 3950 | ) -> None: |
| 3951 | """Write a fresh sidecar from scratch (REBUILD), atomically (temp file |
| 3952 | + replace) so a concurrent reader never observes a half-written file |
| 3953 | mid-rebuild -- unlike the steady-state append path |
| 3954 | (_append_oidx_lines), which is cheap specifically because it skips |
| 3955 | this.""" |
| 3956 | oidx_path.parent.mkdir(parents=True, exist_ok=True) |
| 3957 | temp_path = oidx_path.with_name(f".{oidx_path.name}.{os.getpid()}.{threading.get_ident()}.tmp") |
| 3958 | try: |
| 3959 | with temp_path.open("w", newline="") as handle: |
| 3960 | handle.write(f"{OIDX_HEADER_TAG}\t{data_ino}\n") |
| 3961 | handle.writelines( |
| 3962 | f"{row_start}\t{row_end}\t{op}\t{record_id}\n" |
| 3963 | for row_start, row_end, op, record_id in entries |
| 3964 | ) |
| 3965 | temp_path.replace(oidx_path) |
| 3966 | finally: |
| 3967 | if temp_path.exists(): |
| 3968 | temp_path.unlink() |
| 3969 | |
| 3970 | |
| 3971 | def _append_oidx_lines( |
| 3972 | oidx_path: Path, data_ino: int, entries: list[tuple[int, int, str, str]] |
| 3973 | ) -> None: |
| 3974 | """Append idx lines to an existing sidecar whose header ino the |
| 3975 | caller has already confirmed matches `data_ino`. Self-heals a torn |
| 3976 | idx tail first (same helper the data file uses -- the format needs no |
| 3977 | CSV awareness to repair: an idx line can never contain a literal tab |
| 3978 | or newline inside a field, since ids are restricted to _RECORD_ID_RE |
| 3979 | and offsets/op are plain digits/literals, so "does the file end with |
| 3980 | \\n" is exactly as reliable a completeness signal here as it is for |
| 3981 | records.tsv).""" |
| 3982 | if not entries: |
| 3983 | return |
| 3984 | _repair_torn_tail_lines(oidx_path) |
| 3985 | with oidx_path.open("a", newline="") as handle: |
| 3986 | handle.writelines( |
| 3987 | f"{row_start}\t{row_end}\t{op}\t{record_id}\n" |
| 3988 | for row_start, row_end, op, record_id in entries |
| 3989 | ) |
| 3990 | handle.flush() |
| 3991 | |
| 3992 | |
| 3993 | def _read_oidx_header(oidx_path: Path) -> int | None: |
| 3994 | """Return the data_ino recorded in the sidecar's header line, or None |
| 3995 | when the file is missing, empty, or its header doesn't parse (all |
| 3996 | treated identically by the caller: rebuild).""" |
| 3997 | try: |
| 3998 | with oidx_path.open("r", newline="") as handle: |
| 3999 | first_line = handle.readline() |
| 4000 | except (OSError, UnicodeDecodeError, ValueError): |
| 4001 | # A sidecar corrupted with non-UTF-8 bytes must read as "header |
| 4002 | # does not parse" -> rebuild, per _load_oidx's own contract |
| 4003 | # ("100% best-effort and NEVER raises"). Catching only OSError |
| 4004 | # here let a garbage sidecar crash every read of the collection |
| 4005 | # instead of self-healing -- the atomicity characterization's |
| 4006 | # sidecar finding. |
| 4007 | return None |
| 4008 | parts = first_line.rstrip("\n").split("\t") |
| 4009 | if len(parts) != 2 or parts[0] != OIDX_HEADER_TAG: |
| 4010 | return None |
| 4011 | try: |
| 4012 | return int(parts[1]) |
| 4013 | except ValueError: |
| 4014 | return None |
| 4015 | |
| 4016 | |
| 4017 | def _load_oidx_body( |
| 4018 | oidx_path: Path, |
| 4019 | ) -> tuple[dict[str, int], int | None, int] | None: |
| 4020 | """Parse a sidecar's data lines (everything after the header) into |
| 4021 | ({id: offset}, covered_bytes, indexed_row_count). Returns None when the |
| 4022 | file can't be trusted at all (missing, or a data line doesn't have |
| 4023 | exactly the 4 expected columns / non-integer offsets -- genuine |
| 4024 | corruption, not a torn write, so this doesn't try to salvage a prefix: |
| 4025 | the caller rebuilds instead of guessing). |
| 4026 | |
| 4027 | covered_bytes is None when there are no data lines yet (a header-only |
| 4028 | sidecar, e.g. right after this collection's very first indexed |
| 4029 | write): the caller supplies the real baseline in that case |
| 4030 | (_records_header_length), since a brand-new sidecar covers exactly |
| 4031 | the data file's own header bytes, not zero. |
| 4032 | |
| 4033 | indexed_row_count is the number of body lines parsed -- one per |
| 4034 | PHYSICAL row of records.tsv this sidecar has indexed (create, update, |
| 4035 | and delete rows all count; only the blank-id rows |
| 4036 | _scan_append_rows_for_offsets never indexes are excluded, per that |
| 4037 | function's docstring). Exists for object_records.append_collection_ |
| 4038 | stats' cheap physical-row-count path (a "pure line-count read of the |
| 4039 | sidecar", avoiding a full fold of records.tsv) -- no other caller |
| 4040 | needs it, so it costs this function nothing beyond incrementing a |
| 4041 | counter already being iterated for the fold below. |
| 4042 | |
| 4043 | A torn last line (the file doesn't end with "\\n") is dropped, same |
| 4044 | rule as everywhere else: an idx line, like a data row, is only |
| 4045 | trustworthy once its own newline lands. |
| 4046 | """ |
| 4047 | try: |
| 4048 | text = oidx_path.read_text() |
| 4049 | except OSError: |
| 4050 | return None |
| 4051 | lines = text.split("\n") |
| 4052 | if not lines or not lines[0].startswith(f"{OIDX_HEADER_TAG}\t"): |
| 4053 | return None |
| 4054 | |
| 4055 | body_lines = lines[1:] |
| 4056 | if body_lines and body_lines[-1] == "": |
| 4057 | body_lines = body_lines[:-1] # file ends with \n -- drop the trailing empty split |
| 4058 | elif body_lines: |
| 4059 | body_lines = body_lines[:-1] # torn last line -- drop it, unindexed |
| 4060 | |
| 4061 | result: dict[str, int] = {} |
| 4062 | covered_bytes: int | None = None |
| 4063 | indexed_row_count = 0 |
| 4064 | for line in body_lines: |
| 4065 | if not line: |
| 4066 | continue |
| 4067 | parts = line.split("\t") |
| 4068 | if len(parts) != 4: |
| 4069 | return None |
| 4070 | try: |
| 4071 | row_start = int(parts[0]) |
| 4072 | row_end = int(parts[1]) |
| 4073 | except ValueError: |
| 4074 | return None |
| 4075 | op, record_id = parts[2], parts[3] |
| 4076 | if op == OP_DELETE: |
| 4077 | result.pop(record_id, None) |
| 4078 | else: |
| 4079 | result[record_id] = row_start |
| 4080 | covered_bytes = row_end |
| 4081 | indexed_row_count += 1 |
| 4082 | |
| 4083 | return result, covered_bytes, indexed_row_count |
| 4084 | |
| 4085 | |
| 4086 | def _oidx_get_row( |
| 4087 | path: Path, physical_fields: list[str], offset: int |
| 4088 | ) -> dict[str, str] | None: |
| 4089 | """Seek to `offset` in records.tsv and parse exactly the one physical |
| 4090 | row starting there, returning the LOGICAL record (id + fields, `_op` |
| 4091 | stripped) -- or None if the row can't be read/parsed cleanly, which |
| 4092 | the caller treats as "sidecar inconclusive, fall back to a full |
| 4093 | fold" rather than as "record missing".""" |
| 4094 | # Read the full LOGICAL row via csv, not a raw readline(). A row whose |
| 4095 | # value contains an embedded newline (a quoted field spanning several |
| 4096 | # physical lines -- e.g. multi-line text, or pretty-printed JSON) must be |
| 4097 | # consumed to its real row terminator; a readline() would stop at the |
| 4098 | # first '\n' byte and silently return a truncated (often unparseable) |
| 4099 | # value. csv.reader over the file from `offset` handles the quoted-field |
| 4100 | # continuation exactly as the full-fold path (_parse_append_body) does, |
| 4101 | # keeping the by-id read consistent with it. Any read/parse trouble -> |
| 4102 | # None, so the caller falls back to a full fold rather than trusting a |
| 4103 | # partial row. |
| 4104 | try: |
| 4105 | handle = path.open("rb") |
| 4106 | except OSError: |
| 4107 | return None |
| 4108 | try: |
| 4109 | handle.seek(offset) |
| 4110 | text = io.TextIOWrapper(handle, encoding="utf-8", newline="") |
| 4111 | row = next(csv.reader(text, delimiter="\t")) |
| 4112 | except (OSError, UnicodeDecodeError, StopIteration, csv.Error): |
| 4113 | return None |
| 4114 | finally: |
| 4115 | handle.close() |
| 4116 | field_count = len(physical_fields) |
| 4117 | if not row or len(row) > field_count: |
| 4118 | return None |
| 4119 | record = { |
| 4120 | physical_fields[i]: (row[i] if i < len(row) else "") |
| 4121 | for i in range(field_count) |
| 4122 | } |
| 4123 | return {key: value for key, value in record.items() if key != OP_FIELD} |
| 4124 | |
| 4125 | |
| 4126 | def _load_oidx(path: Path) -> tuple[dict[str, int], bool]: |
| 4127 | """Return ({id: row_start_offset}, coherent) for `path`'s CURRENT |
| 4128 | append-mode content, using and maintaining the on-disk sidecar plus |
| 4129 | the small in-memory _OIDX_CACHE LRU. |
| 4130 | |
| 4131 | `coherent` is True exactly when the returned dict accounts for every |
| 4132 | byte of the file as observed by this call's own stat -- i.e. it is |
| 4133 | safe to treat "id not in the dict" as proof the id doesn't currently |
| 4134 | exist. False means only a best-effort snapshot could be produced |
| 4135 | (normally: a torn tail at EOF from a write that crashed before |
| 4136 | self-healing) and callers must not treat an absence -- or, to be |
| 4137 | conservative, even a presence -- as authoritative; see |
| 4138 | _fast_record_lookup, the only caller, which falls all the way back to |
| 4139 | a full fold whenever this is False. |
| 4140 | |
| 4141 | 100% best-effort and NEVER raises: any inconsistency (missing sidecar, |
| 4142 | corrupt sidecar, inode mismatch, a data file that shrank under a |
| 4143 | stable inode -- e.g. a torn-tail repair truncation) triggers a |
| 4144 | rebuild (one sequential scan of records.tsv) rather than propagating |
| 4145 | an error, per docs/append-only-storage-design.md: the sidecar is |
| 4146 | "never required for correctness." |
| 4147 | """ |
| 4148 | try: |
| 4149 | st = path.stat() |
| 4150 | except OSError: |
| 4151 | return {}, False |
| 4152 | data_ino = st.st_ino |
| 4153 | data_size = st.st_size |
| 4154 | cache_key = str(path.resolve(strict=False)) |
| 4155 | |
| 4156 | cached = _OIDX_CACHE.get(cache_key) |
| 4157 | if cached is not None: |
| 4158 | cached_ino, cached_covered, cached_dict = cached |
| 4159 | if cached_ino == data_ino and cached_covered <= data_size: |
| 4160 | if cached_covered == data_size: |
| 4161 | _OIDX_CACHE.move_to_end(cache_key) |
| 4162 | return cached_dict, True |
| 4163 | physical_fields = _physical_header(path) |
| 4164 | if physical_fields and physical_fields[0] == OP_FIELD: |
| 4165 | entries, new_covered, _row_count = _scan_append_rows_for_offsets( |
| 4166 | path, physical_fields, cached_covered |
| 4167 | ) |
| 4168 | new_dict = _fold_oidx_entries(entries, base=cached_dict) |
| 4169 | _append_oidx_lines(_oidx_path(path), data_ino, entries) |
| 4170 | _store_oidx_cache(cache_key, data_ino, new_covered, new_dict) |
| 4171 | return new_dict, new_covered == data_size |
| 4172 | # ino mismatch, or the file shrank under a stable inode: this |
| 4173 | # in-memory snapshot can't be trusted as a base -- drop it and |
| 4174 | # fall through to the on-disk / rebuild path below. |
| 4175 | _OIDX_CACHE.pop(cache_key, None) |
| 4176 | |
| 4177 | physical_fields = _physical_header(path) |
| 4178 | if not physical_fields or physical_fields[0] != OP_FIELD: |
| 4179 | return {}, False |
| 4180 | |
| 4181 | oidx_path = _oidx_path(path) |
| 4182 | header_ino = _read_oidx_header(oidx_path) |
| 4183 | if header_ino == data_ino: |
| 4184 | loaded = _load_oidx_body(oidx_path) |
| 4185 | if loaded is not None: |
| 4186 | body_dict, body_covered, _body_row_count = loaded |
| 4187 | covered = body_covered if body_covered is not None else _records_header_length(path) |
| 4188 | if covered <= data_size: |
| 4189 | if covered < data_size: |
| 4190 | entries, covered, _row_count = _scan_append_rows_for_offsets( |
| 4191 | path, physical_fields, covered |
| 4192 | ) |
| 4193 | body_dict = _fold_oidx_entries(entries, base=body_dict) |
| 4194 | _append_oidx_lines(oidx_path, data_ino, entries) |
| 4195 | _store_oidx_cache(cache_key, data_ino, covered, body_dict) |
| 4196 | return body_dict, covered == data_size |
| 4197 | # covered > data_size: the data file shrank under a stable |
| 4198 | # ino -- fall through to a full rebuild rather than trust a |
| 4199 | # sidecar that claims to know about bytes no longer there. |
| 4200 | |
| 4201 | # REBUILD: a full sequential scan of records.tsv from its own header, |
| 4202 | # functionally equivalent to the classic full-fold parse this branch |
| 4203 | # replaces for an over-threshold collection -- so, like that parse |
| 4204 | # (_parse_records_file -> _maybe_flag_auto_compact), it's also the |
| 4205 | # right place to (re-)evaluate auto-compaction. Incremental catch-up |
| 4206 | # above deliberately does NOT re-flag: this is a documented, narrower |
| 4207 | # trigger window than the pre-sidecar behavior (every full fold used |
| 4208 | # to re-check on every cold read) -- a collection gets an accurate |
| 4209 | # check whenever its sidecar needs rebuilding (first use past the |
| 4210 | # cache threshold, or any time compaction/a mode switch/corruption |
| 4211 | # invalidates it) but not on every subsequent catch-up scan. Flagging |
| 4212 | # on every catch-up too would need a persisted running physical-row |
| 4213 | # count in the sidecar itself; not worth the format complexity for a |
| 4214 | # threshold heuristic that self-corrects the next time a rebuild does |
| 4215 | # happen. |
| 4216 | header_bytes = _records_header_length(path) |
| 4217 | entries, covered, row_count = _scan_append_rows_for_offsets(path, physical_fields, header_bytes) |
| 4218 | fresh_dict = _fold_oidx_entries(entries) |
| 4219 | _write_oidx_file(oidx_path, data_ino, entries) |
| 4220 | _store_oidx_cache(cache_key, data_ino, covered, fresh_dict) |
| 4221 | if covered == data_size: |
| 4222 | _maybe_flag_auto_compact(path, physical_row_count=row_count, live_row_count=len(fresh_dict)) |
| 4223 | return fresh_dict, covered == data_size |
| 4224 | |
| 4225 | |
| 4226 | def _discard_oidx(path: Path) -> None: |
| 4227 | """Drop any sidecar tracking (in-memory and on-disk) for `path` -- |
| 4228 | called after a full rewrite of an append-physical file (compaction, a |
| 4229 | mode-transition rewrite in either direction, or the new-field |
| 4230 | fallback rewrite): the rewrite gives the file a new inode via |
| 4231 | temp+rename, which would make any existing sidecar's header ino stale |
| 4232 | even without this (the next _load_oidx would detect the mismatch and |
| 4233 | rebuild on its own) -- this just does it eagerly so a compacted or |
| 4234 | mode-switched collection's directory doesn't carry a permanently |
| 4235 | orphaned `.records.oidx` around |
| 4236 | (docs/append-only-storage-design.md Sidecars: "delete or rebuild |
| 4237 | sidecar after the rewrite"). Never called for a collection with no |
| 4238 | append-mode history -- see the SCOPE note above this section -- so a |
| 4239 | purely classic collection's write path never reaches here. Best- |
| 4240 | effort: an unlink failure is not a correctness problem, so this never |
| 4241 | raises. |
| 4242 | """ |
| 4243 | cache_key = str(path.resolve(strict=False)) |
| 4244 | _OIDX_CACHE.pop(cache_key, None) |
| 4245 | try: |
| 4246 | _oidx_path(path).unlink() |
| 4247 | except OSError: |
| 4248 | pass |
| 4249 | |
| 4250 | |
| 4251 | def _update_oidx_after_append( |
| 4252 | path: Path, |
| 4253 | rows: list[dict[str, str]], |
| 4254 | offsets: list[tuple[int, int]], |
| 4255 | ) -> None: |
| 4256 | """Keep the sidecar in sync with a fast append, in O(1): appends |
| 4257 | matching idx line(s) to the on-disk sidecar and updates the in-memory |
| 4258 | _OIDX_CACHE entry -- but ONLY when that entry is already warm for |
| 4259 | this path. When it isn't, this does nothing at all: a write must |
| 4260 | never pay to build or maintain a sidecar nobody is currently reading |
| 4261 | through (see _load_oidx, which lazily builds/catches-up on the next |
| 4262 | point op that actually needs it -- "Sidecar builds lazily on first |
| 4263 | over-threshold op"). |
| 4264 | |
| 4265 | `offsets` are exactly what _append_records_rows just returned for |
| 4266 | `rows` (same order, same length) -- no re-derivation (stat or scan) |
| 4267 | needed to keep this O(1) regardless of collection size. |
| 4268 | |
| 4269 | Mutates `cached_dict` IN PLACE rather than copying it first, UNLIKE |
| 4270 | _refresh_records_cache_after_append's equivalent step for |
| 4271 | _RECORDS_CACHE (which always copies, even on its "fast" path -- see |
| 4272 | that function's docstring). That copy is safe there because |
| 4273 | _RECORDS_CACHE's records/id_index are handed across the public API |
| 4274 | (get/list return values, directly or via one more copy) and so must |
| 4275 | never be mutated out from under an earlier caller -- and it's AFFORD- |
| 4276 | ABLE there because _RECORDS_CACHE only ever holds collections at or |
| 4277 | under DBBASIC_RECORDS_CACHE_MAX_ROWS. Neither holds for this dict: it |
| 4278 | is never exposed outside this module (every public entry point that |
| 4279 | might have sourced data from it -- get/create/update/delete via |
| 4280 | _fast_record_lookup -- only ever calls dict.get() on it and returns a |
| 4281 | freshly-parsed ROW, never the dict itself), and it exists specifically |
| 4282 | FOR collections too large for a copy to be the cheap operation it is |
| 4283 | for _RECORDS_CACHE (a 1M-entry dict copy alone was measured to add |
| 4284 | ~35-40ms to every single write here -- see the sidecar benchmark |
| 4285 | report -- reintroducing real per-write cost in exactly the size |
| 4286 | regime this feature exists to make O(1) again). A concurrent |
| 4287 | lock-free reader's dict.get() racing this mutation is benign under |
| 4288 | the GIL (each op is atomic; a race can only return a value from |
| 4289 | just-before or just-after the write, never corrupt memory or raise) |
| 4290 | -- the same class of eventual-consistency already documented and |
| 4291 | accepted for _RECORDS_CACHE's own CONCURRENCY note above. |
| 4292 | """ |
| 4293 | cache_key = str(path.resolve(strict=False)) |
| 4294 | cached = _OIDX_CACHE.get(cache_key) |
| 4295 | if cached is None: |
| 4296 | return |
| 4297 | cached_ino, cached_covered, cached_dict = cached |
| 4298 | if cached_covered != offsets[0][0]: |
| 4299 | # The cached view doesn't start exactly where this append starts |
| 4300 | # (should not happen -- writes are serialized under the caller's |
| 4301 | # file lock and this cache is only ever advanced by this same |
| 4302 | # process's own writes/reads) -- rather than risk recording wrong |
| 4303 | # offsets, drop it; the next _load_oidx call resyncs or rebuilds. |
| 4304 | _OIDX_CACHE.pop(cache_key, None) |
| 4305 | return |
| 4306 | |
| 4307 | entries: list[tuple[int, int, str, str]] = [] |
| 4308 | for row, (start, end) in zip(rows, offsets, strict=True): |
| 4309 | op = row.get(OP_FIELD, OP_UPSERT) |
| 4310 | record_id = row.get("id", "") |
| 4311 | entries.append((start, end, op, record_id)) |
| 4312 | if op == OP_DELETE: |
| 4313 | cached_dict.pop(record_id, None) |
| 4314 | else: |
| 4315 | cached_dict[record_id] = start |
| 4316 | |
| 4317 | _append_oidx_lines(_oidx_path(path), cached_ino, entries) |
| 4318 | _store_oidx_cache(cache_key, cached_ino, offsets[-1][1], cached_dict) |
| 4319 | |
| 4320 | |
| 4321 | def _fast_record_lookup( |
| 4322 | collection: str, |
| 4323 | path: Path, |
| 4324 | record_id: str, |
| 4325 | *, |
| 4326 | need_row: bool, |
| 4327 | ) -> tuple[ |
| 4328 | list[str], |
| 4329 | bool, |
| 4330 | dict[str, str] | None, |
| 4331 | list[dict[str, str]] | None, |
| 4332 | dict[str, int] | None, |
| 4333 | ]: |
| 4334 | """Resolve (fields, exists, existing_row, records_ref, id_index_ref) |
| 4335 | for one record id -- the shared point-op resolver behind get/create/ |
| 4336 | update/delete, in increasing order of cost: |
| 4337 | |
| 4338 | 1. A warm _RECORDS_CACHE hit (_peek_records_cache) -- the ordinary |
| 4339 | fast path for any collection at or under |
| 4340 | DBBASIC_RECORDS_CACHE_MAX_ROWS once touched once. records_ref/ |
| 4341 | id_index_ref are the module cache's own objects (never mutate -- |
| 4342 | see the _RECORDS_CACHE ALIASING SAFETY note). |
| 4343 | 2. On a miss, if the file is append-physical: the id->offset |
| 4344 | sidecar (_load_oidx). Answers in O(1) without ever folding the |
| 4345 | file -- this is the whole point of the sidecar (docs/append- |
| 4346 | only-storage-design.md item 4): a collection too large for |
| 4347 | _RECORDS_CACHE no longer pays an O(n) fold on every write. |
| 4348 | Trusted only when _load_oidx reports `coherent` -- otherwise |
| 4349 | (a torn tail at EOF from an unfinished write) this falls all the |
| 4350 | way through to step 3 rather than risk a wrong answer. |
| 4351 | records_ref/id_index_ref are None in this case: the fast-append |
| 4352 | write path this enables never needs the full record list (see |
| 4353 | _persist_write's folded_records_fn, which forces its own full |
| 4354 | fold via _cache_entry lazily, only if a rare full-rewrite path |
| 4355 | is chosen instead of a fast append). |
| 4356 | 3. _cache_entry -- the original full fold, unchanged, used for |
| 4357 | classic-mode files, a genuinely cold/small collection's first |
| 4358 | touch, and any sidecar-inconclusive case above. |
| 4359 | |
| 4360 | fields is always the LOGICAL field list (no `_op`). `existing_row`, |
| 4361 | when requested via need_row and the id exists, is always a fresh, |
| 4362 | independent copy safe to hand across the public API or mutate. |
| 4363 | """ |
| 4364 | cached = _peek_records_cache(path) |
| 4365 | if cached is not None: |
| 4366 | fields, records_ref, id_index_ref = cached |
| 4367 | index = id_index_ref.get(record_id) |
| 4368 | existing_row = dict(records_ref[index]) if (need_row and index is not None) else None |
| 4369 | return fields, index is not None, existing_row, records_ref, id_index_ref |
| 4370 | |
| 4371 | physical_header = _physical_header(path) |
| 4372 | if physical_header and physical_header[0] == OP_FIELD: |
| 4373 | id_offsets, coherent = _load_oidx(path) |
| 4374 | if coherent: |
| 4375 | offset = id_offsets.get(record_id) |
| 4376 | if offset is None: |
| 4377 | return physical_header[1:], False, None, None, None |
| 4378 | if not need_row: |
| 4379 | return physical_header[1:], True, None, None, None |
| 4380 | row = _oidx_get_row(path, physical_header, offset) |
| 4381 | if row is not None: |
| 4382 | return physical_header[1:], True, row, None, None |
| 4383 | # Row unreadable at its recorded offset despite a coherent |
| 4384 | # sidecar -- shouldn't happen; be conservative and fall |
| 4385 | # through to the authoritative full fold below. |
| 4386 | |
| 4387 | fields, records_ref, id_index_ref = _cache_entry(collection, path) |
| 4388 | index = id_index_ref.get(record_id) |
| 4389 | existing_row = dict(records_ref[index]) if (need_row and index is not None) else None |
| 4390 | return fields, index is not None, existing_row, records_ref, id_index_ref |
| 4391 | |
| 4392 | |
| 4393 | def _collection_storage_mode( |
| 4394 | collection: str, |
| 4395 | *, |
| 4396 | base_dir: Path | str, |
| 4397 | roots: Iterable[Path] | None, |
| 4398 | ) -> str: |
| 4399 | """Return a collection's storage mode from its schema's `storage` key. |
| 4400 | |
| 4401 | Defaults to classic when the schema has no `storage` key, is derived |
| 4402 | (no manual schema file), or doesn't exist yet -- see |
| 4403 | object_schemas.normalize_schema, which validates the key at schema- |
| 4404 | write time, so any value reaching here is already known-good, but this |
| 4405 | stays defensive rather than trusting that unconditionally. |
| 4406 | """ |
| 4407 | try: |
| 4408 | schema = object_schemas.get_schema(collection, base_dir=base_dir, roots=roots) |
| 4409 | except object_schemas.SchemaNotFoundError: |
| 4410 | return object_schemas.STORAGE_CLASSIC |
| 4411 | mode = schema.get("storage", object_schemas.STORAGE_CLASSIC) |
| 4412 | return mode if mode in object_schemas.VALID_STORAGE_MODES else object_schemas.STORAGE_CLASSIC |
| 4413 | |
| 4414 | |
| 4415 | def _persist_write( |
| 4416 | collection: str, |
| 4417 | path: Path, |
| 4418 | *, |
| 4419 | base_dir: Path | str, |
| 4420 | roots: Iterable[Path] | None, |
| 4421 | prior_fields: list[str], |
| 4422 | merged_fields: list[str], |
| 4423 | folded_records_fn, |
| 4424 | delta_row: dict[str, str] | None, |
| 4425 | delta_op: str, |
| 4426 | delta_id: str, |
| 4427 | ) -> None: |
| 4428 | """Persist one create/update/delete, choosing the write strategy. |
| 4429 | |
| 4430 | `folded_records_fn` is a zero-argument callable that builds the FULL |
| 4431 | folded record set after this op (a fresh, safe-to-mutate copy -- see |
| 4432 | the callers in create/update/delete_collection_record). It is called |
| 4433 | LAZILY, only on a full-rewrite path, and never on the fast-append |
| 4434 | path: the whole point of a fast append is O(1) work, and building |
| 4435 | that full copy is an O(n) cost callers can otherwise skip entirely |
| 4436 | (see _refresh_records_cache_after_append, which updates the cache |
| 4437 | from its own prior entry plus this one delta instead). `delta_row`/ |
| 4438 | `delta_op`/`delta_id` describe just this one op's row, used only by |
| 4439 | the fast-append path. Chooses among (see |
| 4440 | docs/append-only-storage-design.md and the Decisions this module's |
| 4441 | implementation is bound by): |
| 4442 | |
| 4443 | - FAST APPEND: storage is "append", the file is already physically |
| 4444 | in append format, this write doesn't introduce a field the |
| 4445 | current header lacks, and no auto-compaction is pending for this |
| 4446 | collection -- append one row, then update whichever of |
| 4447 | _RECORDS_CACHE / the id->offset sidecar (docs/append-only- |
| 4448 | storage-design.md item 4) is already warm for this path, in O(1), |
| 4449 | via _refresh_records_cache_after_append / _update_oidx_after_ |
| 4450 | append. Neither is FORCED warm here: a collection too large for |
| 4451 | _RECORDS_CACHE (the case the sidecar exists for) is left |
| 4452 | uncached by design, and a sidecar nobody has read through yet is |
| 4453 | left unbuilt (see _update_oidx_after_append) -- either would mean |
| 4454 | paying the exact O(n) fold-per-write cost this branch exists to |
| 4455 | avoid, just moved from "on every write" to "on every write that |
| 4456 | happens to miss the cache," which is most of them for a |
| 4457 | write-hot, over-threshold collection. |
| 4458 | - TRANSITION-IN: storage is "append" but the file isn't (yet) in |
| 4459 | append format (including a brand new collection) -- one full |
| 4460 | rewrite that adds the `_op` header column, applying this op in |
| 4461 | the same pass. |
| 4462 | - NEW-FIELD FALLBACK / AUTO-COMPACT: storage is "append", the file |
| 4463 | is already append-format, but this write needs a header column |
| 4464 | the file doesn't have yet, or a prior read flagged this |
| 4465 | collection for compaction -- a full rewrite that folds current |
| 4466 | content, applies this op, and (in the new-field case) extends the |
| 4467 | header. Still `_op`-columned. |
| 4468 | - COMPACT-TO-CLASSIC: storage is "classic" but the file is still |
| 4469 | physically in append format (opt-out just happened) -- one full |
| 4470 | rewrite that folds current content, applies this op, and drops |
| 4471 | the `_op` column. |
| 4472 | - CLASSIC: storage is "classic" and the file already is (or never |
| 4473 | was anything but) classic format -- the original full-rewrite |
| 4474 | behavior, completely unchanged. |
| 4475 | """ |
| 4476 | desired_mode = _collection_storage_mode(collection, base_dir=base_dir, roots=roots) |
| 4477 | physical_header = _physical_header(path) |
| 4478 | file_is_append_physical = bool(physical_header) and physical_header[0] == OP_FIELD |
| 4479 | cache_key = str(path.resolve(strict=False)) |
| 4480 | new_field_introduced = merged_fields != prior_fields |
| 4481 | pending_compaction = cache_key in _PENDING_COMPACTION |
| 4482 | |
| 4483 | if ( |
| 4484 | desired_mode == object_schemas.STORAGE_APPEND |
| 4485 | and file_is_append_physical |
| 4486 | and not new_field_introduced |
| 4487 | and not pending_compaction |
| 4488 | ): |
| 4489 | physical_fields = [OP_FIELD, *merged_fields] |
| 4490 | row = dict(delta_row) if delta_row is not None else {} |
| 4491 | row["id"] = delta_id |
| 4492 | row[OP_FIELD] = delta_op |
| 4493 | offsets = _append_records_rows(path, physical_fields, [row]) |
| 4494 | projected_row = _project_record(row, merged_fields) |
| 4495 | _refresh_records_cache_after_append( |
| 4496 | collection, path, merged_fields, delta_op, delta_id, projected_row, |
| 4497 | start_offset=offsets[0][0], |
| 4498 | ) |
| 4499 | _update_oidx_after_append(path, [row], offsets) |
| 4500 | return |
| 4501 | |
| 4502 | if file_is_append_physical: |
| 4503 | _discard_oidx(path) |
| 4504 | # folded_records_fn() is called BEFORE the discard below (not after, |
| 4505 | # as it may look more natural) because, on the sidecar-sourced lookup |
| 4506 | # path, it can itself force a fresh full fold (_cache_entry -> |
| 4507 | # _parse_records_file), which re-evaluates and can re-set auto-compact |
| 4508 | # flagging for this same cache_key from the PRE-write content. This |
| 4509 | # write is about to make that stale regardless of what it flagged |
| 4510 | # (append: compacting; classic/transition: rewriting from scratch |
| 4511 | # either way), so the discard must be the last word. |
| 4512 | folded_records = folded_records_fn() |
| 4513 | _PENDING_COMPACTION.discard(cache_key) |
| 4514 | if desired_mode == object_schemas.STORAGE_APPEND: |
| 4515 | physical_fields = [OP_FIELD, *merged_fields] |
| 4516 | _write_collection_records( |
| 4517 | collection, path, physical_fields, folded_records, cache_fields=merged_fields |
| 4518 | ) |
| 4519 | else: |
| 4520 | _write_collection_records(collection, path, merged_fields, folded_records) |
| 4521 | |
| 4522 | |
| 4523 | @contextmanager |
| 4524 | def _records_file_lock(records_file: Path): |
| 4525 | """Use a best-effort advisory lock for collection record mutations.""" |
| 4526 | lock_path = records_file.with_name(f".{records_file.name}.lock") |
| 4527 | lock_path.parent.mkdir(parents=True, exist_ok=True) |
| 4528 | |
| 4529 | with lock_path.open("a") as lock_file: |
| 4530 | try: |
| 4531 | import fcntl |
| 4532 | except ImportError: |
| 4533 | fcntl = None |
| 4534 | |
| 4535 | if fcntl is not None: |
| 4536 | fcntl.flock(lock_file, fcntl.LOCK_EX) |
| 4537 | |
| 4538 | _LOCK_STATE.file_depth = getattr(_LOCK_STATE, "file_depth", 0) + 1 |
| 4539 | try: |
| 4540 | yield |
| 4541 | finally: |
| 4542 | _LOCK_STATE.file_depth -= 1 |
| 4543 | if fcntl is not None: |
| 4544 | fcntl.flock(lock_file, fcntl.LOCK_UN) |
| 4545 | |
| 4546 | |
| 4547 | # --- locked checks --------------------------------------------------------------- |
| 4548 | # |
| 4549 | # A schema's `locked_checks` names read-only functions that decide a write |
| 4550 | # from rows in OTHER collections (a sum against a ceiling). A pre-write hook |
| 4551 | # can make that decision only before the write lock, so it is advisory: a |
| 4552 | # writer that lands between the hook's read and the write -- or one that |
| 4553 | # never reaches a hook at all -- is not seen. A locked check is called by |
| 4554 | # create/update/delete_collection_record themselves, so every writer meets |
| 4555 | # it, and it is called holding two things: |
| 4556 | # |
| 4557 | # 1. the CHECK LOCK named by the entry (`lock`), a flock on |
| 4558 | # <data>/.locks/<lock>.lock. Every write to the declaring collection AND |
| 4559 | # to every collection in `reads` takes that lock first, so nothing the |
| 4560 | # check reads can change between its read and the write it decides. |
| 4561 | # 2. the declaring collection's own file lock, as every write does. |
| 4562 | # |
| 4563 | # Lock order, which is what makes this deadlock-free: a write takes ALL the |
| 4564 | # check locks it will need, in sorted order, before it takes any file lock, |
| 4565 | # and never waits for a check lock while holding a file lock. "All it will |
| 4566 | # need" is the locks covering the collection written plus those covering the |
| 4567 | # collections its rollups refresh (the only writes nested inside a write), so |
| 4568 | # a nested write finds its locks already held (re-entrant per thread). A |
| 4569 | # thread waiting for a check lock therefore holds only check locks that sort |
| 4570 | # before it and no file lock; a thread waiting for a file lock holds every |
| 4571 | # check lock it will take. No cycle can form across check locks (sorted), or |
| 4572 | # between a check lock and a file lock (check locks always first). File lock |
| 4573 | # waits among themselves are the pre-existing child -> rollup-parent order, |
| 4574 | # unchanged. The same holds across processes: flock is per open file. |
| 4575 | |
| 4576 | |
| 4577 | def in_locked_check() -> str | None: |
| 4578 | """The name of the locked check running on this thread, or None. |
| 4579 | Anything that would write or run another object asks this first.""" |
| 4580 | return getattr(_LOCK_STATE, "in_check", None) |
| 4581 | |
| 4582 | |
| 4583 | def _refuse_write_in_check(collection: str) -> None: |
| 4584 | running = in_locked_check() |
| 4585 | if running is not None: |
| 4586 | raise LockedCheckWriteError( |
| 4587 | f"Locked check {running!r} tried to write {collection}; a check only reads." |
| 4588 | ) |
| 4589 | |
| 4590 | |
| 4591 | def _check_lock_timeout() -> float: |
| 4592 | raw = os.environ.get(CHECK_LOCK_TIMEOUT_ENV) |
| 4593 | if raw: |
| 4594 | try: |
| 4595 | value = float(raw) |
| 4596 | except ValueError: |
| 4597 | value = 0.0 |
| 4598 | if value > 0: |
| 4599 | return value |
| 4600 | return _DEFAULT_CHECK_LOCK_TIMEOUT_SECONDS |
| 4601 | |
| 4602 | |
| 4603 | def _check_lock_path(base_dir: Path | str, name: str) -> str: |
| 4604 | return str((Path(base_dir) / CHECK_LOCKS_DIR / f"{name}.lock").resolve(strict=False)) |
| 4605 | |
| 4606 | |
| 4607 | @contextmanager |
| 4608 | def _check_locks(names: Iterable[str], *, base_dir: Path | str, collection: str): |
| 4609 | """Hold the named check locks for the duration: the ones this thread |
| 4610 | does not hold yet are taken in sorted order. See the block comment |
| 4611 | above for the order rule this enforces.""" |
| 4612 | held: dict[str, Any] = getattr(_LOCK_STATE, "held", None) |
| 4613 | if held is None: |
| 4614 | held = _LOCK_STATE.held = {} |
| 4615 | wanted = sorted({_check_lock_path(base_dir, name): name for name in names}.items()) |
| 4616 | missing = [(path, name) for path, name in wanted if path not in held] |
| 4617 | if missing: |
| 4618 | if getattr(_LOCK_STATE, "file_depth", 0): |
| 4619 | raise CheckLockOrderError( |
| 4620 | f"A write to {collection} needs check lock(s) " |
| 4621 | f"{', '.join(name for _, name in missing)} while a collection file lock is " |
| 4622 | "held; refusing rather than risk a deadlock." |
| 4623 | ) |
| 4624 | if held and missing[0][0] < max(held): |
| 4625 | raise CheckLockOrderError( |
| 4626 | f"A write to {collection} needs check lock {missing[0][1]} out of order." |
| 4627 | ) |
| 4628 | acquired: list[str] = [] |
| 4629 | try: |
| 4630 | for path, name in missing: |
| 4631 | held[path] = _acquire_check_lock(path, name, collection=collection) |
| 4632 | acquired.append(path) |
| 4633 | yield |
| 4634 | finally: |
| 4635 | # Only what this frame took: a lock an outer write holds stays held. |
| 4636 | for path in reversed(acquired): |
| 4637 | _release_check_lock(held.pop(path)) |
| 4638 | |
| 4639 | |
| 4640 | def _acquire_check_lock(path: str, name: str, *, collection: str): |
| 4641 | try: |
| 4642 | import fcntl |
| 4643 | except ImportError: # no flock on this platform: file locks are best-effort too |
| 4644 | fcntl = None |
| 4645 | Path(path).parent.mkdir(parents=True, exist_ok=True) |
| 4646 | lock_file = open(path, "a") |
| 4647 | if fcntl is None: |
| 4648 | return lock_file |
| 4649 | deadline = time.monotonic() + _check_lock_timeout() |
| 4650 | pause = 0.0005 |
| 4651 | try: |
| 4652 | while True: |
| 4653 | try: |
| 4654 | fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB) |
| 4655 | return lock_file |
| 4656 | except BlockingIOError: |
| 4657 | pass |
| 4658 | if time.monotonic() >= deadline: |
| 4659 | raise CheckRefusedError( |
| 4660 | f"The {name} lock that writes to {collection} wait on was not free in " |
| 4661 | f"{_check_lock_timeout():g}s. Nothing was written; try again.", |
| 4662 | collection=collection, check=name, status=503, code="check_unavailable", |
| 4663 | ) |
| 4664 | time.sleep(pause) |
| 4665 | pause = min(pause * 2, 0.005) |
| 4666 | except BaseException: |
| 4667 | lock_file.close() |
| 4668 | raise |
| 4669 | |
| 4670 | |
| 4671 | def _release_check_lock(lock_file) -> None: |
| 4672 | try: |
| 4673 | import fcntl |
| 4674 | fcntl.flock(lock_file, fcntl.LOCK_UN) |
| 4675 | except ImportError: |
| 4676 | pass |
| 4677 | finally: |
| 4678 | lock_file.close() |
| 4679 | |
| 4680 | |
| 4681 | def _locked_check_specs( |
| 4682 | collection: str, *, base_dir: Path | str, roots: Iterable[Path] | None |
| 4683 | ) -> list[dict[str, Any]]: |
| 4684 | try: |
| 4685 | schema = object_schemas.get_schema(collection, base_dir=base_dir, roots=roots) |
| 4686 | except object_schemas.SchemaNotFoundError: |
| 4687 | return [] |
| 4688 | return list(schema.get("locked_checks") or []) |
| 4689 | |
| 4690 | |
| 4691 | def _build_check_lock_index( |
| 4692 | base_dir: Path | str, roots: Iterable[Path] | None |
| 4693 | ) -> dict[str, tuple[str, ...]]: |
| 4694 | """{collection: sorted check lock names a write to it must take}: the |
| 4695 | locks of every check declared ON it and every check that READS it. |
| 4696 | |
| 4697 | A schema file that does not load contributes no lock. That is safe, not |
| 4698 | lenient: a lock exists to hold a collection still for the checked |
| 4699 | writes of the schema that declares it, and that schema's collection |
| 4700 | cannot be written at all while its schema does not load (every write |
| 4701 | reads it first). Refusing every OTHER write on the box because one |
| 4702 | unrelated schema file is mid-edit would be an outage, not a gate.""" |
| 4703 | schema_dir = Path(base_dir) / "schemas" |
| 4704 | names = sorted(path.stem for path in schema_dir.glob("*.json")) |
| 4705 | covered: dict[str, set[str]] = {} |
| 4706 | for name in names: |
| 4707 | if not object_schemas.validate_schema_name(name): |
| 4708 | continue |
| 4709 | try: |
| 4710 | checks = _locked_check_specs(name, base_dir=base_dir, roots=roots) |
| 4711 | except Exception: # noqa: BLE001 -- see the docstring |
| 4712 | continue |
| 4713 | for check in checks: |
| 4714 | for member in (name, *check["reads"]): |
| 4715 | covered.setdefault(member, set()).add(check["lock"]) |
| 4716 | return {member: tuple(sorted(locks)) for member, locks in covered.items()} |
| 4717 | |
| 4718 | |
| 4719 | def _write_plan( |
| 4720 | collection: str, *, base_dir: Path | str, roots: Iterable[Path] | None |
| 4721 | ) -> tuple[tuple[str, ...], list[tuple[str, list[dict[str, Any]]]]]: |
| 4722 | """(the check locks a write to `collection` takes, its rollup parents). |
| 4723 | |
| 4724 | One look at the schemas per write, shared by the lock plan and the |
| 4725 | rollup refresh. The locks include those of the rollup parents, because |
| 4726 | the refresh writes them while this write's file lock is held (see the |
| 4727 | lock-order note above).""" |
| 4728 | indexes = _schema_write_indexes(base_dir, roots) |
| 4729 | if indexes is None: |
| 4730 | lock_index = _build_check_lock_index(base_dir, roots) |
| 4731 | # The scan skips a schema that does not load, as the lock index |
| 4732 | # does, so the parents planned here are the ones the refresh writes |
| 4733 | # and their locks are taken. It raises nothing a schema file can |
| 4734 | # cause; anything else leaves the refresh to look again. |
| 4735 | try: |
| 4736 | parents = _scan_rollup_parents_for_source(collection, base_dir=base_dir, roots=roots) |
| 4737 | except Exception: # noqa: BLE001 |
| 4738 | return tuple(sorted(lock_index.get(collection, ()))), None |
| 4739 | else: |
| 4740 | rollup_index, lock_index = indexes |
| 4741 | parents = [ |
| 4742 | (parent, list(specs)) |
| 4743 | for parent, specs in rollup_index.get(collection, ()) |
| 4744 | if parent != collection |
| 4745 | ] |
| 4746 | locks = set(lock_index.get(collection, ())) |
| 4747 | for parent, _specs in parents: |
| 4748 | locks.update(lock_index.get(parent, ())) |
| 4749 | return tuple(sorted(locks)), parents |
| 4750 | |
| 4751 | |
| 4752 | def _write_checks_plan( |
| 4753 | collection: str, *, base_dir: Path | str, roots: Iterable[Path] | None |
| 4754 | ) -> tuple[list[dict[str, Any]], tuple[str, ...], list[tuple[str, list[dict[str, Any]]]]]: |
| 4755 | """(this collection's locked checks, every check lock the write takes, |
| 4756 | its rollup parents) -- planned before any lock is taken.""" |
| 4757 | checks = _locked_check_specs(collection, base_dir=base_dir, roots=roots) |
| 4758 | locks, parents = _write_plan(collection, base_dir=base_dir, roots=roots) |
| 4759 | if checks: |
| 4760 | locks = tuple(sorted(set(locks) | {check["lock"] for check in checks})) |
| 4761 | return checks, locks, parents |
| 4762 | |
| 4763 | |
| 4764 | def _check_selected(spec: Mapping[str, Any], action: str, |
| 4765 | existing: Mapping[str, Any] | None, record: Mapping[str, Any] | None) -> bool: |
| 4766 | on = spec["on"] |
| 4767 | if action != "update": |
| 4768 | return bool(on[action]) |
| 4769 | update = on["update"] |
| 4770 | if update is False: |
| 4771 | return False |
| 4772 | before = existing or {} |
| 4773 | after = record or {} |
| 4774 | names = (set(before) | set(after)) if update is True else update |
| 4775 | return any(str(before.get(name, "") or "") != str(after.get(name, "") or "") for name in names) |
| 4776 | |
| 4777 | |
| 4778 | def _load_check_function(spec: Mapping[str, Any], *, roots: Iterable[Path] | None): |
| 4779 | """The check's function, from its installed object; None when the object |
| 4780 | or the function is not there (the caller refuses: a declared gate that |
| 4781 | is missing is not 'no gate').""" |
| 4782 | import object_namespace # lazy: object_namespace is above this layer |
| 4783 | import python_object_runtime |
| 4784 | |
| 4785 | path = object_namespace.resolve_object_id(spec["object"], roots) |
| 4786 | if path is None: |
| 4787 | return None |
| 4788 | try: |
| 4789 | info = os.stat(path) |
| 4790 | except OSError: |
| 4791 | return None |
| 4792 | signature = (info.st_mtime_ns, info.st_ctime_ns, info.st_size, info.st_ino) |
| 4793 | key = str(path) |
| 4794 | cached = _CHECK_MODULES.get(key) |
| 4795 | if cached is not None and cached[0] == signature: |
| 4796 | module = cached[1] |
| 4797 | else: |
| 4798 | module = python_object_runtime._load_module(Path(path), spec["object"]) |
| 4799 | with _CHECK_MODULES_LOCK: |
| 4800 | if len(_CHECK_MODULES) >= 64: |
| 4801 | _CHECK_MODULES.clear() |
| 4802 | _CHECK_MODULES[key] = (signature, module) |
| 4803 | function = getattr(module, spec["function"], None) |
| 4804 | return function if callable(function) else None |
| 4805 | |
| 4806 | |
| 4807 | def _run_locked_checks( |
| 4808 | specs: list[dict[str, Any]], |
| 4809 | collection: str, |
| 4810 | action: str, |
| 4811 | *, |
| 4812 | existing: Mapping[str, Any] | None, |
| 4813 | record: Mapping[str, Any] | None, |
| 4814 | base_dir: Path | str, |
| 4815 | roots: Iterable[Path] | None, |
| 4816 | ) -> None: |
| 4817 | """Call every selected locked check; raise CheckRefusedError on the |
| 4818 | first that does not allow the write. |
| 4819 | |
| 4820 | MUST be called holding every check lock in `specs` and the collection's |
| 4821 | file lock, after everything else that can refuse the write and before |
| 4822 | anything is written. `existing` is the row read under the file lock |
| 4823 | (surfaced), `record` the row that would be stored (surfaced); for a |
| 4824 | delete, `record` is the row being removed. |
| 4825 | |
| 4826 | The contract a check function is held to (CHECK(request)): |
| 4827 | request = {collection, action, record, existing, check, reads, base_dir} |
| 4828 | returns None or {} to allow; {"error": str, "status": 4xx or 503} to |
| 4829 | refuse. It may read any collection through object_records (the |
| 4830 | `reads` it declared are the ones held still); it may not write or run |
| 4831 | another object (LockedCheckWriteError, answered 500). An exception is |
| 4832 | 'could not decide' (503); any other answer is a broken check (500). |
| 4833 | """ |
| 4834 | for spec in specs: |
| 4835 | if not _check_selected(spec, action, existing, record): |
| 4836 | continue |
| 4837 | name = spec["name"] |
| 4838 | |
| 4839 | def refuse(message: str, status: int, code: str) -> CheckRefusedError: |
| 4840 | return CheckRefusedError(message, collection=collection, check=name, |
| 4841 | status=status, code=code) |
| 4842 | |
| 4843 | try: |
| 4844 | function = _load_check_function(spec, roots=roots) |
| 4845 | except Exception as exc: # noqa: BLE001 -- a check that does not load is closed |
| 4846 | raise refuse(f"The {name} check on {collection} could not be loaded " |
| 4847 | f"({type(exc).__name__}); nothing was written.", 503, |
| 4848 | "check_unavailable") from exc |
| 4849 | if function is None: |
| 4850 | raise refuse(f"The {name} check on {collection} ({spec['object']}." |
| 4851 | f"{spec['function']}) is not installed; nothing was written.", 503, |
| 4852 | "check_unavailable") |
| 4853 | request = { |
| 4854 | "collection": collection, |
| 4855 | "action": action, |
| 4856 | "record": dict(record) if record is not None else None, |
| 4857 | "existing": dict(existing) if existing is not None else None, |
| 4858 | "check": name, |
| 4859 | "reads": list(spec["reads"]), |
| 4860 | "base_dir": os.fspath(base_dir), |
| 4861 | } |
| 4862 | previous = getattr(_LOCK_STATE, "in_check", None) |
| 4863 | _LOCK_STATE.in_check = name |
| 4864 | try: |
| 4865 | answer = function(request) |
| 4866 | except LockedCheckWriteError as exc: |
| 4867 | raise refuse(f"The {name} check on {collection} tried to write; nothing was " |
| 4868 | "written.", 500, "check_failed") from exc |
| 4869 | except Exception as exc: # noqa: BLE001 -- could not decide: closed |
| 4870 | raise refuse(f"The {name} check on {collection} could not decide " |
| 4871 | f"({type(exc).__name__}: {str(exc)[:160]}); nothing was written.", |
| 4872 | 503, "check_unavailable") from exc |
| 4873 | finally: |
| 4874 | _LOCK_STATE.in_check = previous |
| 4875 | if answer is None or answer == {}: |
| 4876 | continue |
| 4877 | if isinstance(answer, Mapping) and isinstance(answer.get("error"), str) \ |
| 4878 | and answer["error"].strip() and set(answer) <= {"error", "status"}: |
| 4879 | status = answer.get("status", 409) |
| 4880 | if status == 503: |
| 4881 | raise refuse(answer["error"], 503, "check_unavailable") |
| 4882 | if isinstance(status, int) and not isinstance(status, bool) and 400 <= status < 500: |
| 4883 | raise refuse(answer["error"], status, "check_refused") |
| 4884 | raise refuse(f"The {name} check on {collection} answered outside its contract; " |
| 4885 | "nothing was written.", 500, "check_failed") |
| 4886 | |
| 4887 | |
| 4888 | def _validate_header(collection: str, fields: list[str] | None) -> None: |
| 4889 | if not fields: |
| 4890 | raise ValueError(f"Collection records file is missing a header: {collection}") |
| 4891 | |
| 4892 | clean = [field.strip() for field in fields] |
| 4893 | if any(not field for field in clean): |
| 4894 | raise ValueError(f"Collection records file has an empty field name: {collection}") |
| 4895 | if clean != fields: |
| 4896 | raise ValueError(f"Collection records file has whitespace in field names: {collection}") |
| 4897 | if len(set(clean)) != len(clean): |
| 4898 | raise ValueError(f"Collection records file has duplicate field names: {collection}") |
| 4899 | if "id" not in clean: |
| 4900 | raise ValueError(f"Collection records file must include an id column: {collection}") |
| 4901 | |
| 4902 | |
| 4903 | def _normalize_record_payload(payload: dict[str, Any], *, require_id: bool) -> dict[str, str]: |
| 4904 | if not isinstance(payload, dict): |
| 4905 | raise InvalidRecordPayloadError("Record payload must be an object") |
| 4906 | generate_id = require_id and ( |
| 4907 | "id" not in payload |
| 4908 | or payload.get("id") is None |
| 4909 | or payload.get("id") == "" |
| 4910 | ) |
| 4911 | |
| 4912 | clean: dict[str, str] = {} |
| 4913 | for key, value in payload.items(): |
| 4914 | if not isinstance(key, str) or not key: |
| 4915 | raise InvalidRecordPayloadError("Record field names must be non-empty strings") |
| 4916 | if key.strip() != key: |
| 4917 | raise InvalidRecordPayloadError(f"Record field name has whitespace: {key!r}") |
| 4918 | if "\t" in key or "\n" in key or "\r" in key: |
| 4919 | raise InvalidRecordPayloadError(f"Record field name is not TSV-safe: {key!r}") |
| 4920 | if key == OP_FIELD: |
| 4921 | raise InvalidRecordPayloadError( |
| 4922 | f"Record field name is reserved for internal storage use: {key!r}" |
| 4923 | ) |
| 4924 | if key == EXTRA_FIELD: |
| 4925 | clean[key] = _normalize_extra_value(value) |
| 4926 | continue |
| 4927 | if value is None: |
| 4928 | clean[key] = "" |
| 4929 | elif isinstance(value, (str, int, float, bool)): |
| 4930 | clean[key] = str(value) |
| 4931 | else: |
| 4932 | raise InvalidRecordPayloadError( |
| 4933 | f"Record field value must be scalar or null: {key}" |
| 4934 | ) |
| 4935 | |
| 4936 | if generate_id: |
| 4937 | clean["id"] = object_ids.new_uuid4() |
| 4938 | elif require_id and "id" not in clean: |
| 4939 | raise InvalidRecordPayloadError("Record payload must include an id") |
| 4940 | |
| 4941 | return clean |
| 4942 | |
| 4943 | |
| 4944 | def _normalize_extra_value(value: Any) -> str: |
| 4945 | """Return a TSV-safe JSON-object string for the ``extra`` field. |
| 4946 | |
| 4947 | Unlike other record fields (scalar or null only), ``extra`` may be |
| 4948 | submitted as a dict (serialized here) or as a JSON string that must |
| 4949 | already parse to an object. Anything else is rejected. |
| 4950 | """ |
| 4951 | if isinstance(value, dict): |
| 4952 | return json.dumps(value, sort_keys=True) |
| 4953 | if isinstance(value, str): |
| 4954 | try: |
| 4955 | parsed = json.loads(value) |
| 4956 | except (TypeError, ValueError) as exc: |
| 4957 | raise InvalidRecordPayloadError( |
| 4958 | "Record field 'extra' must be a JSON object" |
| 4959 | ) from exc |
| 4960 | if not isinstance(parsed, dict): |
| 4961 | raise InvalidRecordPayloadError("Record field 'extra' must be a JSON object") |
| 4962 | return value |
| 4963 | raise InvalidRecordPayloadError( |
| 4964 | "Record field 'extra' must be an object or a JSON object string" |
| 4965 | ) |
| 4966 | |
| 4967 | |
| 4968 | def _apply_auto_created_at( |
| 4969 | collection: str, |
| 4970 | record: dict[str, str], |
| 4971 | submitted_fields: frozenset[str], |
| 4972 | *, |
| 4973 | base_dir: Path | str, |
| 4974 | roots: Iterable[Path] | None, |
| 4975 | ) -> dict[str, str]: |
| 4976 | """Server-set ``created_at`` on create when the schema declares it. |
| 4977 | |
| 4978 | A schema field named ``created_at`` (date/datetime) is filled with the |
| 4979 | current UTC time on create, unless the client supplied it. Because the |
| 4980 | server fills it (not the client), it can be ``read_only`` — clients can |
| 4981 | neither omit it nor spoof it — which is what lets generated lists show |
| 4982 | a trustworthy relative timestamp. |
| 4983 | """ |
| 4984 | if "created_at" in submitted_fields: |
| 4985 | return record |
| 4986 | for field in _schema_fields(collection, base_dir=base_dir, roots=roots): |
| 4987 | if field.get("name") != "created_at": |
| 4988 | continue |
| 4989 | field_type = str(field.get("type") or "").lower() |
| 4990 | now = datetime.now(timezone.utc) |
| 4991 | if field_type == "date": |
| 4992 | value = now.date().isoformat() |
| 4993 | elif field_type in {"datetime", "timestamp"}: |
| 4994 | value = now.isoformat().replace("+00:00", "Z") |
| 4995 | else: |
| 4996 | return record |
| 4997 | clean = dict(record) |
| 4998 | clean["created_at"] = value |
| 4999 | return clean |
| 5000 | return record |
| 5001 | |
| 5002 | |
| 5003 | def _apply_schema_defaults( |
| 5004 | collection: str, |
| 5005 | record: dict[str, str], |
| 5006 | *, |
| 5007 | base_dir: Path | str, |
| 5008 | roots: Iterable[Path] | None, |
| 5009 | ) -> dict[str, str]: |
| 5010 | fields = _schema_fields(collection, base_dir=base_dir, roots=roots) |
| 5011 | if not fields: |
| 5012 | return record |
| 5013 | |
| 5014 | clean = dict(record) |
| 5015 | for field in fields: |
| 5016 | name = field["name"] |
| 5017 | if name in clean and clean[name] != "": |
| 5018 | continue |
| 5019 | if _is_computed_or_read_only(field): |
| 5020 | continue |
| 5021 | if "default" not in field: |
| 5022 | continue |
| 5023 | clean[name] = _schema_scalar_to_string(field["default"], field_name=name) |
| 5024 | return clean |
| 5025 | |
| 5026 | |
| 5027 | # --------------------------------------------------------------------------- |
| 5028 | # Formula & rollup fields (plan/formula-rollup-spec.md): derived values, |
| 5029 | # MATERIALIZED at this storage layer so every writer (HTTP, daemon, seeds, |
| 5030 | # imports) keeps them consistent and every surface reads plain stored values. |
| 5031 | # Formulas recompute on writes of the record itself; rollups recompute on |
| 5032 | # writes/deletes in the source collection (single-hop, thread-local guarded). |
| 5033 | # A broken formula stores "" and never fails the write -- derived values are |
| 5034 | # non-authoritative, the opposite posture of pre-write hooks. |
| 5035 | # --------------------------------------------------------------------------- |
| 5036 | |
| 5037 | _ROLLUP_LOCAL = threading.local() |
| 5038 | |
| 5039 | |
| 5040 | def _apply_computed_fields( |
| 5041 | collection: str, |
| 5042 | record: dict[str, str], |
| 5043 | *, |
| 5044 | base_dir: Path | str, |
| 5045 | roots: Iterable[Path] | None, |
| 5046 | ) -> dict[str, str]: |
| 5047 | """Recompute this record's own derived values: rollups first (so a parent |
| 5048 | created/edited after its children exist is immediately correct), then |
| 5049 | formulas (which may reference the fresh rollup values).""" |
| 5050 | fields = _schema_fields(collection, base_dir=base_dir, roots=roots) |
| 5051 | if not fields: |
| 5052 | return record |
| 5053 | rollups = object_computed.rollup_fields(fields) |
| 5054 | formulas = object_computed.formula_fields(fields) |
| 5055 | if not rollups and not formulas: |
| 5056 | return record |
| 5057 | out = dict(record) |
| 5058 | for field in rollups: |
| 5059 | spec = field["rollup"] |
| 5060 | try: |
| 5061 | children = [ |
| 5062 | row |
| 5063 | for row in read_collection_records( |
| 5064 | spec["collection"], base_dir=base_dir, roots=roots |
| 5065 | ) |
| 5066 | if row.get(spec["fk_field"]) == out.get("id") |
| 5067 | ] |
| 5068 | except (object_collections.CollectionNotFoundError, OSError, ValueError): |
| 5069 | continue |
| 5070 | out[field["name"]] = object_computed.compute_rollup(spec, children) |
| 5071 | return object_computed.apply_formulas(fields, out) |
| 5072 | |
| 5073 | |
| 5074 | # Which schemas roll up which collection, one index per schemas directory: |
| 5075 | # {schemas dir: (signature, {source collection: ((parent, (field, ...)), ...)})}. |
| 5076 | # See _rollup_parent_index for the signature and for when an index is kept. |
| 5077 | _ROLLUP_PARENTS_CACHE: dict[str, tuple[tuple, tuple[dict[str, Any], dict[str, tuple[str, ...]]]]] = {} |
| 5078 | _ROLLUP_PARENTS_CACHE_LOCK = threading.Lock() |
| 5079 | _ROLLUP_PARENTS_CACHE_MAX_DIRS = 32 |
| 5080 | # A schema file (or the schemas directory) changed more recently than this |
| 5081 | # when the index was built is not cached: a second change inside the |
| 5082 | # filesystem's timestamp granularity would leave the same stat behind. The |
| 5083 | # margin object_identity's session cache uses. |
| 5084 | _ROLLUP_PARENTS_RACY_NS = 50_000_000 |
| 5085 | |
| 5086 | |
| 5087 | def _rollup_parents_for_source( |
| 5088 | source_collection: str, |
| 5089 | *, |
| 5090 | base_dir: Path | str, |
| 5091 | roots: Iterable[Path] | None, |
| 5092 | ) -> list[tuple[str, list[dict[str, Any]]]]: |
| 5093 | """(parent_collection, rollup_fields) pairs whose rollups aggregate the |
| 5094 | given source collection. Declared schemas only (the schemas dir); a |
| 5095 | collection cannot roll up itself (v1 loop guard). |
| 5096 | |
| 5097 | Every write asks this, and answering it meant loading every schema (102 |
| 5098 | on a 57-package install, about 8 ms) to find the two or three that |
| 5099 | declare a rollup. The answer for every source collection at once is |
| 5100 | built on the first ask and kept while the schemas directory and every |
| 5101 | schema file in it still have the stat they had (_rollup_parent_index). |
| 5102 | When no index can be vouched for -- a schema file that does not load, a |
| 5103 | symlink, a file changed a moment ago -- this falls back to the scan, |
| 5104 | which skips a schema that does not load (see its docstring). |
| 5105 | """ |
| 5106 | index = _rollup_parent_index(base_dir, roots) |
| 5107 | if index is None: |
| 5108 | return _scan_rollup_parents_for_source(source_collection, base_dir=base_dir, roots=roots) |
| 5109 | return [ |
| 5110 | (parent, list(specs)) |
| 5111 | for parent, specs in index.get(source_collection, ()) |
| 5112 | if parent != source_collection |
| 5113 | ] |
| 5114 | |
| 5115 | |
| 5116 | def _rollup_parent_index( |
| 5117 | base_dir: Path | str, |
| 5118 | roots: Iterable[Path] | None, |
| 5119 | ) -> dict[str, tuple[tuple[str, tuple[Any, ...]], ...]] | None: |
| 5120 | indexes = _schema_write_indexes(base_dir, roots) |
| 5121 | return None if indexes is None else indexes[0] |
| 5122 | |
| 5123 | |
| 5124 | def _schema_write_indexes( |
| 5125 | base_dir: Path | str, |
| 5126 | roots: Iterable[Path] | None, |
| 5127 | ) -> tuple[dict[str, tuple[tuple[str, tuple[Any, ...]], ...]], dict[str, tuple[str, ...]]] | None: |
| 5128 | """(rollup parents by source collection, check locks by collection) -- |
| 5129 | the two facts every write needs from ALL the schemas -- kept for this |
| 5130 | schemas directory and rebuilt when the disk moved; None when there is |
| 5131 | nothing safe to keep (the caller scans). |
| 5132 | |
| 5133 | Nothing tells this process that a schema changed: the API, the package |
| 5134 | installer, the daemon, another worker and an operator's editor all write |
| 5135 | these files. So every call stats the directory and every schema file |
| 5136 | again (about a hundred stats, a fraction of a millisecond) and rebuilds |
| 5137 | on any difference: |
| 5138 | |
| 5139 | - the directory's stat changes when a schema file is created, deleted |
| 5140 | or renamed (and its ctime when its mtime is set back by a restore); |
| 5141 | - a file's (mtime, ctime, size, inode, device) changes when it is |
| 5142 | edited in place or replaced. ctime is there because mtime can be set; |
| 5143 | inode because an atomic replace inside one timestamp tick keeps the |
| 5144 | mtime and can keep the size. |
| 5145 | |
| 5146 | Stats are taken BEFORE the files are read, so a write landing during |
| 5147 | the build leaves a signature older than the index and the next call |
| 5148 | rebuilds. An index is not kept at all when a stat cannot vouch for it: |
| 5149 | anything changed within _ROLLUP_PARENTS_RACY_NS of the build, an entry |
| 5150 | that is not a regular file (a symlink's target changes without touching |
| 5151 | it), or any schema that fails to load (errors are never cached). |
| 5152 | """ |
| 5153 | try: |
| 5154 | directory = os.path.join(os.fspath(base_dir), "schemas") |
| 5155 | except TypeError: |
| 5156 | return None |
| 5157 | cached = _ROLLUP_PARENTS_CACHE.get(directory) |
| 5158 | if cached is not None and _schemas_signature_holds(cached[0]): |
| 5159 | return cached[1] |
| 5160 | |
| 5161 | signature = _schemas_signature(directory) |
| 5162 | built_at = time.time_ns() |
| 5163 | index: tuple[Any, Any] | None = None |
| 5164 | if signature is not None and _schemas_signature_settled(signature, built_at): |
| 5165 | try: |
| 5166 | index = (_build_rollup_parent_index(base_dir, roots), |
| 5167 | _build_check_lock_index(base_dir, roots)) |
| 5168 | except Exception: # noqa: BLE001 - the scan the caller falls back to raises it |
| 5169 | index = None |
| 5170 | with _ROLLUP_PARENTS_CACHE_LOCK: |
| 5171 | if index is None: |
| 5172 | _ROLLUP_PARENTS_CACHE.pop(directory, None) |
| 5173 | else: |
| 5174 | if ( |
| 5175 | directory not in _ROLLUP_PARENTS_CACHE |
| 5176 | and len(_ROLLUP_PARENTS_CACHE) >= _ROLLUP_PARENTS_CACHE_MAX_DIRS |
| 5177 | ): |
| 5178 | _ROLLUP_PARENTS_CACHE.clear() |
| 5179 | _ROLLUP_PARENTS_CACHE[directory] = (signature, index) |
| 5180 | return index |
| 5181 | |
| 5182 | |
| 5183 | def _build_rollup_parent_index( |
| 5184 | base_dir: Path | str, |
| 5185 | roots: Iterable[Path] | None, |
| 5186 | ) -> dict[str, tuple[tuple[str, tuple[Any, ...]], ...]]: |
| 5187 | """One pass of the scan below for every source collection at once: |
| 5188 | the same names in the same order, the same fields in schema order.""" |
| 5189 | schema_dir = Path(base_dir) / "schemas" |
| 5190 | names = sorted(path.stem for path in schema_dir.glob("*.json")) |
| 5191 | found: dict[str, list[tuple[str, tuple[Any, ...]]]] = {} |
| 5192 | for name in names: |
| 5193 | fields = _schema_fields(name, base_dir=base_dir, roots=roots) |
| 5194 | by_source: dict[str, list[Any]] = {} |
| 5195 | for field in object_computed.rollup_fields(fields): |
| 5196 | source = field["rollup"]["collection"] |
| 5197 | if isinstance(source, str): # only a str can equal a collection name |
| 5198 | by_source.setdefault(source, []).append(field) |
| 5199 | for source, specs in by_source.items(): |
| 5200 | found.setdefault(source, []).append((name, tuple(specs))) |
| 5201 | return {source: tuple(parents) for source, parents in found.items()} |
| 5202 | |
| 5203 | |
| 5204 | def _schemas_signature(directory: str) -> tuple | None: |
| 5205 | """((directory, stat), (file, stat), ...) for the schemas directory and |
| 5206 | every `*.json` entry in it, or None when an entry is not a regular file |
| 5207 | or the directory cannot be read. A missing directory has a signature |
| 5208 | too: (directory, None) and no files.""" |
| 5209 | try: |
| 5210 | info = os.stat(directory) |
| 5211 | except OSError: |
| 5212 | return ((directory, None),) |
| 5213 | entries: list[tuple] = [ |
| 5214 | (directory, (info.st_mtime_ns, info.st_ctime_ns, info.st_ino, info.st_dev, info.st_mode)) |
| 5215 | ] |
| 5216 | try: |
| 5217 | names = sorted(name for name in os.listdir(directory) if name.endswith(".json")) |
| 5218 | except OSError: |
| 5219 | return None |
| 5220 | for name in names: |
| 5221 | path = os.path.join(directory, name) |
| 5222 | found = _schema_file_stat(path) |
| 5223 | if found is None: |
| 5224 | return None |
| 5225 | entries.append((path, found)) |
| 5226 | return tuple(entries) |
| 5227 | |
| 5228 | |
| 5229 | def _schema_file_stat(path: str) -> tuple[int, int, int, int, int] | None: |
| 5230 | """(mtime_ns, ctime_ns, size, inode, device) of a regular file; None |
| 5231 | for anything else, a symlink included (lstat does not follow).""" |
| 5232 | try: |
| 5233 | info = os.lstat(path) |
| 5234 | except OSError: |
| 5235 | return None |
| 5236 | if (info.st_mode & 0o170000) != 0o100000: |
| 5237 | return None |
| 5238 | return (info.st_mtime_ns, info.st_ctime_ns, info.st_size, info.st_ino, info.st_dev) |
| 5239 | |
| 5240 | |
| 5241 | def _schemas_signature_holds(signature: tuple) -> bool: |
| 5242 | directory, recorded = signature[0] |
| 5243 | try: |
| 5244 | info = os.stat(directory) |
| 5245 | except OSError: |
| 5246 | return recorded is None and len(signature) == 1 |
| 5247 | if recorded != (info.st_mtime_ns, info.st_ctime_ns, info.st_ino, info.st_dev, info.st_mode): |
| 5248 | return False |
| 5249 | for path, expected in signature[1:]: |
| 5250 | if _schema_file_stat(path) != expected: |
| 5251 | return False |
| 5252 | return True |
| 5253 | |
| 5254 | |
| 5255 | def _schemas_signature_settled(signature: tuple, built_at_ns: int) -> bool: |
| 5256 | for _path, recorded in signature: |
| 5257 | if recorded is not None and built_at_ns - max(recorded[0], recorded[1]) < _ROLLUP_PARENTS_RACY_NS: |
| 5258 | return False |
| 5259 | return True |
| 5260 | |
| 5261 | |
| 5262 | def _scan_rollup_parents_for_source( |
| 5263 | source_collection: str, |
| 5264 | *, |
| 5265 | base_dir: Path | str, |
| 5266 | roots: Iterable[Path] | None, |
| 5267 | ) -> list[tuple[str, list[dict[str, Any]]]]: |
| 5268 | """The uncached answer: load every schema and keep the ones that roll |
| 5269 | up `source_collection`. |
| 5270 | |
| 5271 | A schema file that does not load (invalid JSON, a name outside the |
| 5272 | schema-name rules, anything get_schema raises) is skipped, as the |
| 5273 | check-lock index skips it. This is asked after the write it serves has |
| 5274 | landed, so raising here told the caller a written row was refused |
| 5275 | (bug report 2026-11-29 11:07). A rollup the broken file declares cannot |
| 5276 | be honoured while it does not load -- nobody can read it -- and writes to |
| 5277 | that file's own collection are refused before anything is written. Its |
| 5278 | parent rows are brought current by the next write to one of their |
| 5279 | children once the file is fixed, or by recompute_computed_fields.""" |
| 5280 | parents: list[tuple[str, list[dict[str, Any]]]] = [] |
| 5281 | schema_dir = Path(base_dir) / "schemas" |
| 5282 | try: |
| 5283 | names = sorted(path.stem for path in schema_dir.glob("*.json")) |
| 5284 | except OSError: |
| 5285 | return parents |
| 5286 | for name in names: |
| 5287 | if name == source_collection or not object_schemas.validate_schema_name(name): |
| 5288 | continue |
| 5289 | try: |
| 5290 | fields = _schema_fields(name, base_dir=base_dir, roots=roots) |
| 5291 | except Exception: # noqa: BLE001 -- see the docstring |
| 5292 | continue |
| 5293 | specs = [ |
| 5294 | field |
| 5295 | for field in object_computed.rollup_fields(fields) |
| 5296 | if field["rollup"]["collection"] == source_collection |
| 5297 | ] |
| 5298 | if specs: |
| 5299 | parents.append((name, specs)) |
| 5300 | return parents |
| 5301 | |
| 5302 | |
| 5303 | def _recompute_rollups_for_source( |
| 5304 | source_collection: str, |
| 5305 | affected_rows: list[dict[str, str] | None], |
| 5306 | *, |
| 5307 | base_dir: Path | str, |
| 5308 | roots: Iterable[Path] | None, |
| 5309 | parents: list[tuple[str, list[dict[str, Any]]]] | None = None, |
| 5310 | ) -> None: |
| 5311 | """After a write/delete in source_collection, bring affected parents' |
| 5312 | rollup fields current. Single-hop: the parent update this performs never |
| 5313 | triggers further rollup scans (thread-local guard). Best-effort by design: |
| 5314 | a failed parent refresh must never fail the child's own write. |
| 5315 | |
| 5316 | `parents` is the write's own _write_plan answer when it has one: the |
| 5317 | same parents its check locks were planned for.""" |
| 5318 | if getattr(_ROLLUP_LOCAL, "active", False): |
| 5319 | return |
| 5320 | if parents is None: |
| 5321 | try: |
| 5322 | parents = _rollup_parents_for_source(source_collection, base_dir=base_dir, roots=roots) |
| 5323 | except Exception: # noqa: BLE001 -- the write has landed; never report it refused |
| 5324 | return |
| 5325 | if not parents: |
| 5326 | return |
| 5327 | _ROLLUP_LOCAL.active = True |
| 5328 | try: |
| 5329 | for parent_collection, specs in parents: |
| 5330 | fk_values: set[str] = set() |
| 5331 | for field in specs: |
| 5332 | fk_field = field["rollup"]["fk_field"] |
| 5333 | for row in affected_rows: |
| 5334 | if row and row.get(fk_field): |
| 5335 | fk_values.add(str(row[fk_field])) |
| 5336 | if not fk_values: |
| 5337 | continue |
| 5338 | try: |
| 5339 | source_rows = read_collection_records( |
| 5340 | source_collection, base_dir=base_dir, roots=roots |
| 5341 | ) |
| 5342 | except (object_collections.CollectionNotFoundError, OSError, ValueError): |
| 5343 | continue |
| 5344 | for parent_id in sorted(fk_values): |
| 5345 | try: |
| 5346 | parent = get_collection_record( |
| 5347 | parent_collection, parent_id, base_dir=base_dir, roots=roots |
| 5348 | ) |
| 5349 | except (RecordNotFoundError, object_collections.CollectionNotFoundError, |
| 5350 | InvalidRecordIdError, OSError, ValueError): |
| 5351 | continue |
| 5352 | changes: dict[str, str] = {} |
| 5353 | for field in specs: |
| 5354 | spec = field["rollup"] |
| 5355 | children = [ |
| 5356 | row for row in source_rows if row.get(spec["fk_field"]) == parent_id |
| 5357 | ] |
| 5358 | changes[field["name"]] = object_computed.compute_rollup(spec, children) |
| 5359 | if all(str(parent.get(k, "")) == v for k, v in changes.items()): |
| 5360 | continue |
| 5361 | try: |
| 5362 | update_collection_record( |
| 5363 | parent_collection, |
| 5364 | parent_id, |
| 5365 | changes, |
| 5366 | base_dir=base_dir, |
| 5367 | roots=roots, |
| 5368 | actor="system:rollup", |
| 5369 | allow_computed_submission=True, |
| 5370 | ) |
| 5371 | except Exception: |
| 5372 | continue |
| 5373 | finally: |
| 5374 | _ROLLUP_LOCAL.active = False |
| 5375 | |
| 5376 | |
| 5377 | def recompute_computed_fields( |
| 5378 | collection: str, |
| 5379 | *, |
| 5380 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 5381 | roots: Iterable[Path] | None = None, |
| 5382 | ) -> int: |
| 5383 | """Backfill/refresh every derived value in a collection; returns how many |
| 5384 | records changed. For definition changes and first adoption -- called |
| 5385 | explicitly (install migration, admin action, cron), never automatically in |
| 5386 | a runtime loop (docs: no runtime object rewriting; same spirit for data).""" |
| 5387 | fields = _schema_fields(collection, base_dir=base_dir, roots=roots) |
| 5388 | computed_names = { |
| 5389 | field["name"] |
| 5390 | for field in object_computed.rollup_fields(fields) |
| 5391 | + object_computed.formula_fields(fields) |
| 5392 | } |
| 5393 | if not computed_names: |
| 5394 | return 0 |
| 5395 | changed = 0 |
| 5396 | for row in read_collection_records(collection, base_dir=base_dir, roots=roots): |
| 5397 | desired = _apply_computed_fields(collection, dict(row), base_dir=base_dir, roots=roots) |
| 5398 | delta = { |
| 5399 | name: desired.get(name, "") |
| 5400 | for name in computed_names |
| 5401 | if str(row.get(name, "")) != str(desired.get(name, "")) |
| 5402 | } |
| 5403 | if not delta: |
| 5404 | continue |
| 5405 | update_collection_record( |
| 5406 | collection, |
| 5407 | row["id"], |
| 5408 | delta, |
| 5409 | base_dir=base_dir, |
| 5410 | roots=roots, |
| 5411 | actor="system:recompute", |
| 5412 | allow_computed_submission=True, |
| 5413 | ) |
| 5414 | changed += 1 |
| 5415 | return changed |
| 5416 | |
| 5417 | |
| 5418 | def _validate_field_transitions( |
| 5419 | collection: str, |
| 5420 | existing: dict[str, str], |
| 5421 | updated: dict[str, str], |
| 5422 | *, |
| 5423 | base_dir: Path | str, |
| 5424 | roots: Iterable[Path] | None, |
| 5425 | subject: object_permissions.PermissionSubject | None = None, |
| 5426 | ) -> None: |
| 5427 | """Enforce declared value transitions on update. |
| 5428 | |
| 5429 | A field may declare which values each current value can move to. Each |
| 5430 | list entry is either a plain string, allowed for any caller who may |
| 5431 | update the record, or a guarded object: |
| 5432 | |
| 5433 | {"name": "status", "type": "enum", "enum": [...], |
| 5434 | "transitions": { |
| 5435 | "open": ["assigned", {"to": "cancelled", "when": {"owner_id": "$user_id"}}], |
| 5436 | ... |
| 5437 | }} |
| 5438 | |
| 5439 | A guarded move is allowed only once every ``when`` clause matches the |
| 5440 | record's CURRENT stored values (``existing``, before this update) |
| 5441 | against the resolved subject variable or literal -- the same closed |
| 5442 | set and matching rules row filters use (see |
| 5443 | object_permissions.record_matches_filter). |
| 5444 | |
| 5445 | This is deliberately data plus one check — not a state machine |
| 5446 | framework: no hooks, no side effects, no transition callbacks. A |
| 5447 | current value missing from the map cannot change; an empty existing |
| 5448 | value may move anywhere. |
| 5449 | |
| 5450 | Guards are enforced only when ``subject`` is supplied. The HTTP update |
| 5451 | path resolves and plumbs the request subject once permissions have |
| 5452 | already run (see update_collection_record); direct library callers |
| 5453 | with no subject -- daemon, CLI, tests -- are trusted callers: a |
| 5454 | guarded move is still checked for validity (its "to" is in the list) |
| 5455 | but the "when" clause is not enforced. |
| 5456 | """ |
| 5457 | fields = _schema_fields(collection, base_dir=base_dir, roots=roots) |
| 5458 | for field in fields: |
| 5459 | transitions = field.get("transitions") |
| 5460 | if not isinstance(transitions, dict): |
| 5461 | continue |
| 5462 | name = field["name"] |
| 5463 | old_value = existing.get(name, "") |
| 5464 | new_value = updated.get(name, "") |
| 5465 | if old_value == new_value or _is_empty(old_value): |
| 5466 | continue |
| 5467 | |
| 5468 | entries = transitions.get(old_value) |
| 5469 | entries = entries if isinstance(entries, list) else [] |
| 5470 | |
| 5471 | allowed_values: list[str] = [] |
| 5472 | move_is_valid = False |
| 5473 | guard_failed = False |
| 5474 | for entry in entries: |
| 5475 | if isinstance(entry, str): |
| 5476 | to_value, when = entry, None |
| 5477 | elif isinstance(entry, dict): |
| 5478 | to_value, when = str(entry.get("to", "")), entry.get("when") or {} |
| 5479 | else: |
| 5480 | continue |
| 5481 | |
| 5482 | if to_value and to_value not in allowed_values: |
| 5483 | allowed_values.append(to_value) |
| 5484 | if to_value != new_value: |
| 5485 | continue |
| 5486 | |
| 5487 | if when is None or subject is None: |
| 5488 | move_is_valid = True |
| 5489 | elif object_permissions.record_matches_filter(existing, when, subject): |
| 5490 | move_is_valid = True |
| 5491 | else: |
| 5492 | guard_failed = True |
| 5493 | |
| 5494 | if move_is_valid: |
| 5495 | continue |
| 5496 | |
| 5497 | options = ", ".join(allowed_values) if allowed_values else "none" |
| 5498 | if guard_failed: |
| 5499 | raise TransitionNotAllowedError( |
| 5500 | f"Record field '{name}' cannot move from '{old_value}' to " |
| 5501 | f"'{new_value}' for this subject (allowed: {options})" |
| 5502 | ) |
| 5503 | raise InvalidRecordPayloadError( |
| 5504 | f"Record field '{name}' cannot move from '{old_value}' to " |
| 5505 | f"'{new_value}' (allowed: {options})" |
| 5506 | ) |
| 5507 | |
| 5508 | |
| 5509 | def _canonicalize_schema_values( |
| 5510 | collection: str, |
| 5511 | record: dict[str, str], |
| 5512 | *, |
| 5513 | base_dir: Path | str, |
| 5514 | roots: Iterable[Path] | None, |
| 5515 | ) -> dict[str, str]: |
| 5516 | """Store schema-typed values in one canonical form. |
| 5517 | |
| 5518 | Boolean fields accept several spellings on input ("True", "1", "yes") |
| 5519 | but must be stored as "true"/"false" so permission row filters like |
| 5520 | {"is_public": "true"} match by string comparison. Runs after |
| 5521 | validation, so every value here is known to parse. |
| 5522 | """ |
| 5523 | fields = _schema_fields(collection, base_dir=base_dir, roots=roots) |
| 5524 | if not fields: |
| 5525 | return record |
| 5526 | |
| 5527 | clean = dict(record) |
| 5528 | for field in fields: |
| 5529 | name = field["name"] |
| 5530 | value = clean.get(name) |
| 5531 | if _is_empty(value): |
| 5532 | continue |
| 5533 | field_type = str(field.get("type") or "text").lower() |
| 5534 | if field_type in _BOOLEAN_TYPES: |
| 5535 | clean[name] = "true" if _parse_boolean(value, field_name=name) else "false" |
| 5536 | return clean |
| 5537 | |
| 5538 | |
| 5539 | def _validate_record_against_schema( |
| 5540 | collection: str, |
| 5541 | record: dict[str, str], |
| 5542 | *, |
| 5543 | submitted_fields: frozenset[str], |
| 5544 | base_dir: Path | str, |
| 5545 | roots: Iterable[Path] | None, |
| 5546 | allow_read_only_submission: bool = False, |
| 5547 | allow_computed_submission: bool = False, |
| 5548 | ) -> None: |
| 5549 | fields = _schema_fields(collection, base_dir=base_dir, roots=roots) |
| 5550 | if not fields: |
| 5551 | return |
| 5552 | |
| 5553 | for field in fields: |
| 5554 | name = field["name"] |
| 5555 | value = record.get(name, "") |
| 5556 | |
| 5557 | if name in submitted_fields and _is_computed_or_read_only(field): |
| 5558 | is_computed = _is_computed_field(field) |
| 5559 | permitted = ( |
| 5560 | (allow_computed_submission and is_computed) |
| 5561 | or (allow_read_only_submission and not is_computed) |
| 5562 | ) |
| 5563 | if not permitted: |
| 5564 | raise InvalidRecordPayloadError( |
| 5565 | f"Record field '{name}' is computed or read-only and cannot be written" |
| 5566 | ) |
| 5567 | |
| 5568 | if _field_is_required(field) and not _is_computed_or_read_only(field) and _is_empty(value): |
| 5569 | raise InvalidRecordPayloadError(f"Record field '{name}' is required") |
| 5570 | |
| 5571 | if _is_empty(value): |
| 5572 | continue |
| 5573 | |
| 5574 | _validate_field_type(field, value) |
| 5575 | _validate_field_enum(field, value) |
| 5576 | _validate_field_rules(field, value) |
| 5577 | _validate_field_relation(field, value, base_dir=base_dir) |
| 5578 | |
| 5579 | _check_required_when(fields, record, collection=collection, base_dir=base_dir, roots=roots) |
| 5580 | |
| 5581 | |
| 5582 | def _check_field_storable(record: dict[str, Any]) -> None: |
| 5583 | """Reject a write whose any field value cannot be safely stored in the |
| 5584 | canonical plain-text TSV substrate, surfacing every case as a clean |
| 5585 | InvalidRecordPayloadError (a 4xx) rather than letting a raw stdlib |
| 5586 | _csv.Error or UnicodeEncodeError escape the public API. Three unstorable |
| 5587 | classes: |
| 5588 | |
| 5589 | - **Too large** (> MAX_TSV_FIELD_BYTES): without this, an oversize cell |
| 5590 | silently empties an append-mode collection on read. |
| 5591 | - **NUL (0x00)**: Python's csv writer literally cannot represent a NUL |
| 5592 | under QUOTE_ALL/MINIMAL ("need to escape, but no escapechar set"), and a |
| 5593 | NUL corrupts the text tooling the plain-text-durability guarantee rests |
| 5594 | on -- it is not text. Legitimate JSON escapes NUL to \\u0000, so real |
| 5595 | structured data never carries a raw one. |
| 5596 | - **Unencodable UTF-8** (a lone surrogate, e.g. from bad input or |
| 5597 | json.dumps(ensure_ascii=False) over broken data): can't be written at |
| 5598 | all. |
| 5599 | |
| 5600 | Enforced on create/update (the entry points for new/changed data); |
| 5601 | internal rewrites (compaction, transition) don't pass here -- they only |
| 5602 | re-serialize data that already passed this gate. Iterates the record's own |
| 5603 | values, so it guards schemaless collections and the packed `extra` blob |
| 5604 | too. |
| 5605 | """ |
| 5606 | for name, value in record.items(): |
| 5607 | if value is None: |
| 5608 | continue |
| 5609 | text = str(value) |
| 5610 | if "\x00" in text: |
| 5611 | raise InvalidRecordPayloadError( |
| 5612 | f"Record field '{name}' contains a NUL byte, which cannot be " |
| 5613 | f"stored in the plain-text substrate (JSON encodes NUL as " |
| 5614 | f"\\u0000)" |
| 5615 | ) |
| 5616 | try: |
| 5617 | size = len(text.encode("utf-8")) |
| 5618 | except UnicodeEncodeError as exc: |
| 5619 | raise InvalidRecordPayloadError( |
| 5620 | f"Record field '{name}' is not valid UTF-8 (unencodable " |
| 5621 | f"surrogate) and cannot be stored: {exc}" |
| 5622 | ) from exc |
| 5623 | if size > MAX_TSV_FIELD_BYTES: |
| 5624 | raise InvalidRecordPayloadError( |
| 5625 | f"Record field '{name}' is {size} bytes, exceeding the " |
| 5626 | f"{MAX_TSV_FIELD_BYTES}-byte per-field maximum" |
| 5627 | ) |
| 5628 | |
| 5629 | |
| 5630 | # A bare carriage return -- "\r" NOT immediately followed by "\n". csv's |
| 5631 | # QUOTE_MINIMAL does not quote a field for a lone CR (it quotes only for the |
| 5632 | # delimiter, the quotechar, and "\n"), but csv.reader treats a bare CR in an |
| 5633 | # UNQUOTED field as a row terminator -- silently splitting one row into two |
| 5634 | # (and, in append mode, hiding every later record from the fold path). "\r\n" |
| 5635 | # and lone "\n" are already handled by QUOTE_MINIMAL (both contain "\n"). |
| 5636 | _BARE_CR_RE = re.compile(r"\r(?!\n)") |
| 5637 | |
| 5638 | |
| 5639 | def _rows_need_full_quoting(rows: Iterable[dict[str, Any]]) -> bool: |
| 5640 | """True if any field value in `rows` contains a bare CR (see _BARE_CR_RE). |
| 5641 | |
| 5642 | When it does, that write uses csv.QUOTE_ALL so every field is quoted and |
| 5643 | the CR round-trips intact; the overwhelming common case (no bare CR) stays |
| 5644 | QUOTE_MINIMAL and byte-identical to before. This keeps the compact |
| 5645 | plain-text format for normal data while making a lone CR lossless instead |
| 5646 | of silently corrupting -- no format change for anyone who never stores a |
| 5647 | bare CR. Readers parse quoted and unquoted rows alike, so a file may mix |
| 5648 | both. Note: values destined for the packed `extra` JSON blob have their CR |
| 5649 | escaped by json.dumps, so scanning raw values here only ever OVER-detects |
| 5650 | (a harmless extra-quoted write), never misses a CR that reaches a column. |
| 5651 | """ |
| 5652 | for row in rows: |
| 5653 | for value in row.values(): |
| 5654 | if value is None: |
| 5655 | continue |
| 5656 | text = str(value) |
| 5657 | if "\r" in text and _BARE_CR_RE.search(text): |
| 5658 | return True |
| 5659 | return False |
| 5660 | |
| 5661 | |
| 5662 | def _schema_fields( |
| 5663 | collection: str, |
| 5664 | *, |
| 5665 | base_dir: Path | str, |
| 5666 | roots: Iterable[Path] | None, |
| 5667 | ) -> list[dict[str, Any]]: |
| 5668 | try: |
| 5669 | schema = object_schemas.get_schema(collection, base_dir=base_dir, roots=roots) |
| 5670 | except object_schemas.SchemaNotFoundError: |
| 5671 | return [] |
| 5672 | fields = schema.get("fields", []) |
| 5673 | if not isinstance(fields, list): |
| 5674 | return [] |
| 5675 | return [field for field in fields if isinstance(field, dict) and "name" in field] |
| 5676 | |
| 5677 | |
| 5678 | def _field_is_required(field: dict[str, Any]) -> bool: |
| 5679 | validation = field.get("validation") if isinstance(field.get("validation"), dict) else {} |
| 5680 | return bool(field.get("required") or validation.get("required") or validation.get("not_null")) |
| 5681 | |
| 5682 | |
| 5683 | def _is_computed_or_read_only(field: dict[str, Any]) -> bool: |
| 5684 | field_type = str(field.get("type", "")).lower() |
| 5685 | return bool( |
| 5686 | field_type == "computed" |
| 5687 | or field.get("computed") |
| 5688 | or field.get("read_only") |
| 5689 | or field.get("readonly") |
| 5690 | or field.get("readOnly") |
| 5691 | ) |
| 5692 | |
| 5693 | |
| 5694 | def _is_computed_field(field: dict[str, Any]) -> bool: |
| 5695 | """Return True for a server-derived formula field, as opposed to a |
| 5696 | field that is merely ``read_only`` (client can't set it, but nothing |
| 5697 | computes its value -- see ``preserve_read_only`` on |
| 5698 | ``create_collection_record``).""" |
| 5699 | field_type = str(field.get("type", "")).lower() |
| 5700 | return bool(field_type == "computed" or field.get("computed")) |
| 5701 | |
| 5702 | |
| 5703 | def _is_empty(value: str | None) -> bool: |
| 5704 | return value is None or value == "" |
| 5705 | |
| 5706 | |
| 5707 | def _schema_scalar_to_string(value: Any, *, field_name: str) -> str: |
| 5708 | if value is None: |
| 5709 | return "" |
| 5710 | if isinstance(value, (str, int, float, bool)): |
| 5711 | return str(value) |
| 5712 | raise InvalidRecordPayloadError(f"Schema default for '{field_name}' must be scalar or null") |
| 5713 | |
| 5714 | |
| 5715 | def _validate_field_type(field: dict[str, Any], value: str) -> None: |
| 5716 | name = field["name"] |
| 5717 | field_type = str(field.get("type") or "text").lower() |
| 5718 | if field_type in _INTEGER_TYPES: |
| 5719 | _parse_integer(value, field_name=name) |
| 5720 | elif field_type in _FLOAT_TYPES: |
| 5721 | _parse_float(value, field_name=name) |
| 5722 | elif field_type in _BOOLEAN_TYPES: |
| 5723 | _parse_boolean(value, field_name=name) |
| 5724 | elif field_type == "date": |
| 5725 | _parse_date(value, field_name=name) |
| 5726 | elif field_type in {"datetime", "timestamp"}: |
| 5727 | _parse_datetime(value, field_name=name) |
| 5728 | elif field_type == "enum": |
| 5729 | _validate_field_enum(field, value, required=True) |
| 5730 | |
| 5731 | |
| 5732 | def _validate_field_enum(field: dict[str, Any], value: str, *, required: bool = False) -> None: |
| 5733 | enum_payload = field.get("enum") |
| 5734 | validation = field.get("validation") if isinstance(field.get("validation"), dict) else {} |
| 5735 | if enum_payload is None: |
| 5736 | enum_payload = validation.get("choices", validation.get("in")) |
| 5737 | values = _enum_values(enum_payload) |
| 5738 | if not values: |
| 5739 | if required: |
| 5740 | raise InvalidRecordPayloadError(f"Record field '{field['name']}' enum has no values") |
| 5741 | return |
| 5742 | if value not in values: |
| 5743 | allowed = ", ".join(values) |
| 5744 | raise InvalidRecordPayloadError( |
| 5745 | f"Record field '{field['name']}' must be one of: {allowed}" |
| 5746 | ) |
| 5747 | |
| 5748 | |
| 5749 | def _enum_values(enum_payload: Any) -> list[str]: |
| 5750 | if enum_payload is None: |
| 5751 | return [] |
| 5752 | if isinstance(enum_payload, dict): |
| 5753 | enum_payload = enum_payload.get("values") |
| 5754 | if not isinstance(enum_payload, list): |
| 5755 | return [] |
| 5756 | values = [] |
| 5757 | for item in enum_payload: |
| 5758 | if isinstance(item, (str, int, float, bool)): |
| 5759 | values.append(str(item)) |
| 5760 | return values |
| 5761 | |
| 5762 | |
| 5763 | def _validate_field_relation( |
| 5764 | field: dict[str, Any], |
| 5765 | value: str, |
| 5766 | *, |
| 5767 | base_dir: Path | str, |
| 5768 | ) -> None: |
| 5769 | """Require relation values to be existing record ids in the target collection. |
| 5770 | |
| 5771 | A relation is a validated pointer plus a display hint — deliberately not |
| 5772 | an association framework: no joins, no lazy loading, no cascades. |
| 5773 | """ |
| 5774 | relation = field.get("relation") |
| 5775 | if relation is None: |
| 5776 | return |
| 5777 | |
| 5778 | name = field["name"] |
| 5779 | if isinstance(relation, str): |
| 5780 | target = relation |
| 5781 | elif isinstance(relation, dict): |
| 5782 | target = relation.get("collection") |
| 5783 | else: |
| 5784 | raise InvalidRecordPayloadError( |
| 5785 | f"Record field '{name}' relation must be a collection name or object" |
| 5786 | ) |
| 5787 | |
| 5788 | if not isinstance(target, str) or not object_collections.validate_collection_name(target): |
| 5789 | raise InvalidRecordPayloadError( |
| 5790 | f"Record field '{name}' relation has an invalid collection" |
| 5791 | ) |
| 5792 | |
| 5793 | try: |
| 5794 | get_collection_record(target, value, base_dir=base_dir) |
| 5795 | except (object_collections.CollectionNotFoundError, RecordNotFoundError) as exc: |
| 5796 | raise InvalidRecordPayloadError( |
| 5797 | f"Record field '{name}' references a missing record: {target}/{value}" |
| 5798 | ) from exc |
| 5799 | except InvalidRecordIdError as exc: |
| 5800 | raise InvalidRecordPayloadError( |
| 5801 | f"Record field '{name}' relation value is not a valid record id" |
| 5802 | ) from exc |
| 5803 | |
| 5804 | |
| 5805 | def _validate_field_rules(field: dict[str, Any], value: str) -> None: |
| 5806 | validation = field.get("validation") |
| 5807 | if not isinstance(validation, dict): |
| 5808 | return |
| 5809 | |
| 5810 | name = field["name"] |
| 5811 | if "min_length" in validation and len(value) < _rule_int(validation["min_length"], name, "min_length"): |
| 5812 | raise InvalidRecordPayloadError(f"Record field '{name}' is shorter than min_length") |
| 5813 | if "max_length" in validation and len(value) > _rule_int(validation["max_length"], name, "max_length"): |
| 5814 | raise InvalidRecordPayloadError(f"Record field '{name}' is longer than max_length") |
| 5815 | |
| 5816 | pattern = validation.get("pattern", validation.get("regex")) |
| 5817 | if pattern is not None: |
| 5818 | if not isinstance(pattern, str): |
| 5819 | raise InvalidRecordPayloadError(f"Record field '{name}' validation pattern must be a string") |
| 5820 | try: |
| 5821 | matches = object_schemas.pattern_matches(pattern, value) |
| 5822 | except re.error as exc: |
| 5823 | raise InvalidRecordPayloadError( |
| 5824 | f"Record field '{name}' validation pattern is invalid" |
| 5825 | ) from exc |
| 5826 | if not matches: |
| 5827 | raise InvalidRecordPayloadError(f"Record field '{name}' does not match pattern") |
| 5828 | |
| 5829 | if "min" in validation: |
| 5830 | if _parse_float(value, field_name=name) < _rule_float(validation["min"], name, "min"): |
| 5831 | raise InvalidRecordPayloadError(f"Record field '{name}' is below min") |
| 5832 | if "max" in validation: |
| 5833 | if _parse_float(value, field_name=name) > _rule_float(validation["max"], name, "max"): |
| 5834 | raise InvalidRecordPayloadError(f"Record field '{name}' is above max") |
| 5835 | # Strict bounds, compared exactly (Decimal, not float): "greater than |
| 5836 | # zero" must refuse 0 and must admit 0.0000001. Declared strictly at |
| 5837 | # schema load (object_schemas._normalize_validation_declarations). |
| 5838 | if "exclusive_min" in validation: |
| 5839 | if _exact_number(value, name) <= _exact_bound(validation["exclusive_min"], name, "exclusive_min"): |
| 5840 | raise InvalidRecordPayloadError( |
| 5841 | f"Record field '{name}' must be greater than {validation['exclusive_min']}" |
| 5842 | ) |
| 5843 | if "exclusive_max" in validation: |
| 5844 | if _exact_number(value, name) >= _exact_bound(validation["exclusive_max"], name, "exclusive_max"): |
| 5845 | raise InvalidRecordPayloadError( |
| 5846 | f"Record field '{name}' must be less than {validation['exclusive_max']}" |
| 5847 | ) |
| 5848 | |
| 5849 | |
| 5850 | def _exact_number(value: str, name: str) -> Decimal: |
| 5851 | """The stored text as an exact Decimal, after the same checks `min` |
| 5852 | makes (a number, finite).""" |
| 5853 | number = _parse_float(value, field_name=name) |
| 5854 | try: |
| 5855 | return Decimal(value.strip()) |
| 5856 | except InvalidOperation: |
| 5857 | return Decimal(repr(number)) # float() reads forms Decimal does not |
| 5858 | |
| 5859 | |
| 5860 | def _exact_bound(value: Any, name: str, rule_name: str) -> Decimal: |
| 5861 | _rule_float(value, name, rule_name) |
| 5862 | return Decimal(str(value).strip()) |
| 5863 | |
| 5864 | |
| 5865 | def _required_when_conditions(field: dict[str, Any]) -> dict[str, list[str]] | None: |
| 5866 | validation = field.get("validation") |
| 5867 | if not isinstance(validation, dict): |
| 5868 | return None |
| 5869 | conditions = validation.get("required_when") |
| 5870 | if not isinstance(conditions, dict) or not conditions: |
| 5871 | return None |
| 5872 | return { |
| 5873 | key: [wanted] if isinstance(wanted, str) else list(wanted) |
| 5874 | for key, wanted in conditions.items() |
| 5875 | } |
| 5876 | |
| 5877 | |
| 5878 | def _check_required_when( |
| 5879 | fields: list[dict[str, Any]], |
| 5880 | record: dict[str, str], |
| 5881 | *, |
| 5882 | collection: str, |
| 5883 | base_dir: Path | str, |
| 5884 | roots: Iterable[Path] | None, |
| 5885 | ) -> None: |
| 5886 | """Refuse a record that matches a field's ``validation.required_when`` |
| 5887 | and leaves the field blank. |
| 5888 | |
| 5889 | Judged on the record as it will be STORED (an update's merged row, booleans |
| 5890 | in their canonical "true"/"false"), so the write that sets the condition |
| 5891 | must also set the field, and a write that blanks the field while the |
| 5892 | condition holds is refused. Blank means empty or only whitespace. |
| 5893 | """ |
| 5894 | declared = [(field, _required_when_conditions(field)) for field in fields] |
| 5895 | declared = [(field, when) for field, when in declared if when] |
| 5896 | if not declared: |
| 5897 | return |
| 5898 | stored = _canonicalize_schema_values(collection, record, base_dir=base_dir, roots=roots) |
| 5899 | for field, when in declared: |
| 5900 | if str(stored.get(field["name"]) or "").strip(): |
| 5901 | continue |
| 5902 | if all(str(stored.get(other) or "") in wanted for other, wanted in when.items()): |
| 5903 | condition = " and ".join( |
| 5904 | f"{other} is {wanted[0]}" if len(wanted) == 1 |
| 5905 | else f"{other} is one of {', '.join(wanted)}" |
| 5906 | for other, wanted in when.items() |
| 5907 | ) |
| 5908 | raise InvalidRecordPayloadError( |
| 5909 | f"Record field '{field['name']}' is required when {condition}" |
| 5910 | ) |
| 5911 | |
| 5912 | |
| 5913 | def _parse_integer(value: str, *, field_name: str) -> int: |
| 5914 | try: |
| 5915 | if value.strip() != value or not re.fullmatch(r"[+-]?\d+", value): |
| 5916 | raise ValueError |
| 5917 | return int(value) |
| 5918 | except ValueError as exc: |
| 5919 | raise InvalidRecordPayloadError(f"Record field '{field_name}' must be an integer") from exc |
| 5920 | |
| 5921 | |
| 5922 | def _parse_float(value: str, *, field_name: str) -> float: |
| 5923 | try: |
| 5924 | number = float(value) |
| 5925 | except ValueError as exc: |
| 5926 | raise InvalidRecordPayloadError(f"Record field '{field_name}' must be a number") from exc |
| 5927 | if not math.isfinite(number): |
| 5928 | raise InvalidRecordPayloadError(f"Record field '{field_name}' must be a finite number") |
| 5929 | return number |
| 5930 | |
| 5931 | |
| 5932 | def _parse_boolean(value: str, *, field_name: str) -> bool: |
| 5933 | text = value.lower() |
| 5934 | if text in _TRUE_VALUES: |
| 5935 | return True |
| 5936 | if text in _FALSE_VALUES: |
| 5937 | return False |
| 5938 | raise InvalidRecordPayloadError(f"Record field '{field_name}' must be a boolean") |
| 5939 | |
| 5940 | |
| 5941 | def _parse_date(value: str, *, field_name: str) -> date: |
| 5942 | try: |
| 5943 | return date.fromisoformat(value) |
| 5944 | except ValueError as exc: |
| 5945 | raise InvalidRecordPayloadError(f"Record field '{field_name}' must be a date") from exc |
| 5946 | |
| 5947 | |
| 5948 | def _parse_datetime(value: str, *, field_name: str) -> datetime: |
| 5949 | try: |
| 5950 | return datetime.fromisoformat(value.replace("Z", "+00:00")) |
| 5951 | except ValueError as exc: |
| 5952 | raise InvalidRecordPayloadError(f"Record field '{field_name}' must be a datetime") from exc |
| 5953 | |
| 5954 | |
| 5955 | def _rule_int(value: Any, field_name: str, rule_name: str) -> int: |
| 5956 | try: |
| 5957 | return int(value) |
| 5958 | except (TypeError, ValueError) as exc: |
| 5959 | raise InvalidRecordPayloadError( |
| 5960 | f"Record field '{field_name}' validation {rule_name} must be an integer" |
| 5961 | ) from exc |
| 5962 | |
| 5963 | |
| 5964 | def _rule_float(value: Any, field_name: str, rule_name: str) -> float: |
| 5965 | try: |
| 5966 | number = float(value) |
| 5967 | except (TypeError, ValueError) as exc: |
| 5968 | raise InvalidRecordPayloadError( |
| 5969 | f"Record field '{field_name}' validation {rule_name} must be a number" |
| 5970 | ) from exc |
| 5971 | if not math.isfinite(number): |
| 5972 | raise InvalidRecordPayloadError( |
| 5973 | f"Record field '{field_name}' validation {rule_name} must be finite" |
| 5974 | ) |
| 5975 | return number |
| 5976 | |
| 5977 | |
| 5978 | def _extra_field_names( |
| 5979 | collection: str, |
| 5980 | *, |
| 5981 | base_dir: Path | str, |
| 5982 | roots: Iterable[Path] | None, |
| 5983 | ) -> set[str]: |
| 5984 | """Return the names of schema fields whose value lives inside ``extra``.""" |
| 5985 | fields = _schema_fields(collection, base_dir=base_dir, roots=roots) |
| 5986 | return {field["name"] for field in fields if field.get("store") == EXTRA_FIELD} |
| 5987 | |
| 5988 | |
| 5989 | def _parse_extra_blob(value: str | None) -> dict[str, Any]: |
| 5990 | """Parse an ``extra`` TSV cell into a dict, tolerating missing/invalid data.""" |
| 5991 | if not value: |
| 5992 | return {} |
| 5993 | try: |
| 5994 | parsed = json.loads(value) |
| 5995 | except (TypeError, ValueError): |
| 5996 | return {} |
| 5997 | return parsed if isinstance(parsed, dict) else {} |
| 5998 | |
| 5999 | |
| 6000 | def _route_extra( |
| 6001 | record: dict[str, str], |
| 6002 | *, |
| 6003 | existing_blob: dict[str, Any], |
| 6004 | extra_names: set[str], |
| 6005 | ) -> dict[str, str]: |
| 6006 | """Fold ``extra`` and any ``store: extra`` view fields into one JSON blob. |
| 6007 | |
| 6008 | Pure: builds on ``existing_blob`` (so a partial update never wipes |
| 6009 | untouched blob keys), shallow-merges any client-submitted ``extra`` |
| 6010 | object into it, then pulls each declared view field out of the |
| 6011 | top-level record and into the blob. The record keeps a single |
| 6012 | ``extra`` TSV column holding the serialized blob (or no column at all |
| 6013 | when the blob is empty), never the view field's own column. |
| 6014 | """ |
| 6015 | blob = dict(existing_blob) |
| 6016 | if EXTRA_FIELD in record: |
| 6017 | blob.update(_parse_extra_blob(record.pop(EXTRA_FIELD))) |
| 6018 | for name in extra_names: |
| 6019 | if name in record: |
| 6020 | blob[name] = record.pop(name) |
| 6021 | |
| 6022 | if blob: |
| 6023 | serialized = json.dumps(blob, sort_keys=True) |
| 6024 | if "\t" in serialized or "\n" in serialized or "\r" in serialized: |
| 6025 | raise InvalidRecordPayloadError("Record field 'extra' is not TSV-safe") |
| 6026 | record[EXTRA_FIELD] = serialized |
| 6027 | else: |
| 6028 | record.pop(EXTRA_FIELD, None) |
| 6029 | return record |
| 6030 | |
| 6031 | |
| 6032 | def _surface_extra(record: dict[str, str], *, extra_names: set[str]) -> dict[str, str]: |
| 6033 | """Expose each declared ``store: extra`` view field at the top level. |
| 6034 | |
| 6035 | Pure: ``record["extra"]`` is left as-is (still the raw JSON string) so |
| 6036 | undeclared blob data stays reachable. A no-op when there are no view |
| 6037 | fields and no ``extra`` column. |
| 6038 | """ |
| 6039 | if not extra_names: |
| 6040 | return record |
| 6041 | blob = _parse_extra_blob(record.get(EXTRA_FIELD)) |
| 6042 | for name in extra_names: |
| 6043 | record[name] = str(blob.get(name, "")) |
| 6044 | return record |
| 6045 | |
| 6046 | |
| 6047 | def _merge_fields(existing_fields: list[str], record: dict[str, str]) -> list[str]: |
| 6048 | fields = list(existing_fields) if existing_fields else ["id"] |
| 6049 | if "id" not in fields: |
| 6050 | fields.insert(0, "id") |
| 6051 | for field in record: |
| 6052 | if field not in fields: |
| 6053 | fields.append(field) |
| 6054 | return fields |
| 6055 | |
| 6056 | |
| 6057 | def _project_record(record: dict[str, str], fields: list[str]) -> dict[str, str]: |
| 6058 | return {field: record.get(field, "") for field in fields} |
| 6059 | |
| 6060 | |
| 6061 | def _validate_page(*, limit: int, offset: int) -> None: |
| 6062 | if limit < 1: |
| 6063 | raise ValueError("Record limit must be at least 1") |
| 6064 | if limit > MAX_RECORD_LIMIT: |
| 6065 | raise ValueError(f"Record limit must be at most {MAX_RECORD_LIMIT}") |
| 6066 | if offset < 0: |
| 6067 | raise ValueError("Record offset must be at least 0") |