From f6050f5d9222d847a899899434d3a74cc20eb969 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 09:40:36 -0800 Subject: [PATCH 1/8] docs(specs): design for storing a pipeline in SpiralDB (ITL-1446) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1446-spiral-columns.md | 533 ++++++++++++++++++++ docs/dev/specs/itl-1446/prototype-output.md | 42 ++ docs/dev/specs/itl-1446/prototype.py | 526 +++++++++++++++++++ docs/dev/specs/itl-1446/stored-columns.md | 218 ++++++++ docs/dev/specs/itl-1446/stored_columns.py | 213 ++++++++ 5 files changed, 1532 insertions(+) create mode 100644 docs/dev/specs/itl-1446-spiral-columns.md create mode 100644 docs/dev/specs/itl-1446/prototype-output.md create mode 100644 docs/dev/specs/itl-1446/prototype.py create mode 100644 docs/dev/specs/itl-1446/stored-columns.md create mode 100644 docs/dev/specs/itl-1446/stored_columns.py diff --git a/docs/dev/specs/itl-1446-spiral-columns.md b/docs/dev/specs/itl-1446-spiral-columns.md new file mode 100644 index 000000000..51e217bdf --- /dev/null +++ b/docs/dev/specs/itl-1446-spiral-columns.md @@ -0,0 +1,533 @@ +# ITL-1446: storing a pipeline in SpiralDB + +Status: **proposal, nothing implemented.** Section 8 lists the decisions the developer makes. +Covers ITL-1176, ITL-1164, ITL-1100 (names, tables) and ITL-1190 (metadata races). + +How each statement below is known: + +- **Measured**: run on `main` at `7a2248bf` on the disk fake (`tests/test_databases/fake_pyspiral.py`) + by the scripts in [`itl-1446/`](itl-1446/). The fake is a model, not the service. +- **Read**: from the installed pyspiral 0.16.33 (its Python source, stubs, or the text of its + native library). Reading says what the client offers, not what the server does. +- **Seen live**: an earlier live session, cited by issue. +- **To probe**: not known; section 7 lists one live probe for each. No SpiralDB was used here. + +## 0. Summary + +- **Recommendation: option (a).** A SpiralDB store maps column names, types and table names when + it writes and restores them when it reads. Nothing above the database changes: no hash, record + path, layout version or golden value moves. +- A prototype of (a) runs a job (join, filter, function, group by, second function, side effect) + on the fake with rows, schemas, system tags and content hashes equal to the in-memory store's, + and an unchanged rerun calls nothing (Measured, [`prototype.py`](itl-1446/prototype.py)). +- Column names are the small part. Reading the code and running the prototype found five things + the issue does not list, each of which must be in the first version: + +| # | Finding | How known | Section | +|---|---|---|---| +| F1 | **Table names are too long.** pyspiral types a table name as at most 128 characters of `[a-zA-Z0-9_-]`. A function pipeline table's name is 181 characters today. `unstorable_table_name_reason` says SpiralDB holds every name | Read, Measured | 5 | +| F2 | **Table names collide, and a collision serves wrong results.** `function_name="my-fn"` and `"my_fn"` share one result table; the second function is given the first one's values | Measured | 5 | +| F3 | **Row order is lost.** SpiralDB returns rows in key order, and the key is a hash. `Batch(2)` over a `CachedSource` gives other batches than on Delta and in memory | Measured | 3.6 | +| F4 | **Result record ids are not content derived.** A function result's id is a random UUIDv7; a pipeline record's id leaves out the result it names. "Same id, same content" holds only for operator caches and cached sources, and not bit for bit | Read | 6 | +| F5 | **The fake accepts what the client refuses**: `fixed_size_binary` and `duration` (pyspiral's own `Schema.from_arrow` raises) and probably a `null` column (the native library has an error for it). The connector says it stores all three | Measured (client, offline) and Read | 3.4 | + +## 1. Every stored column + +[`stored-columns.md`](itl-1446/stored-columns.md) is generated by +[`stored_columns.py`](itl-1446/stored_columns.py): a job writes every table kind, each +`add_records` call is recorded, and each column is given to +`SpiralDBConnector.unstorable_column_reason` and written alone through the fake. It has names, +Arrow types, nullability, the reason for each refusal, and what the fake does. 153 columns, 57 +refused. + +| Table kind | Columns refused today | Reason | +|---|---|---| +| Function pipeline (`pdb_v1`) | the 11 bookkeeping columns: `__data_id`, `__node_content_hash`, `__input_data_hash`, `__output_data_hash`, `__data_context`, `__computed`, `__is_ephemeral`, `__pipeline_base_entry_id`, `__pipeline_recomputation_index`, `__pipeline_run_id`, `__recorded_at` | `__` prefix; `__recorded_at` also has a time zone | +| Function result (`rdb_v1`) | 13: `__input_data_hash`, six `__pf_var_*`, four `__pf_exec_*`, `__pod_ts`, `__data_context` | `__` prefix; `__pod_ts` also has a time zone | +| ... its outputs | `datetime`, `Path`, a user class, `list[UUID]` | time zone; logical (extension) type | +| Side-effect log (`tdb_v1`) | `executed_at`, `__data_context` | time zone; `__` prefix | +| Operator cache (`odb_v1`) | `__node_content_hash`, `__data_context`, and user columns by type | `__` prefix | +| Cached source (`sdb_v1`) | `__data_context`, and user columns by type | `__` prefix | +| Observer tables (opt-in) | none | but `_log_id` / `_status_id` are `fixed_size_binary[16]`, which the client refuses (F5) | + +A second point the list shows: the reason given is the first one found. `__recorded_at` and +`__pod_ts` fail twice, so fixing names alone does not make them storable. + +## 2. Options + +| | (a) map in the store | (b) rename the stored columns everywhere | (c) mixed | +|---|---|---|---| +| What changes | a SpiralDB store encodes on write and decodes on read | `SYSTEM_COLUMN_PREFIX` becomes a prefix SpiralDB accepts, for every store | (b) for Orcapod's own columns, (a) for user columns | +| Hashes, paths, golden | **none** | `__input_data_hash` and `__pipeline_recomputation_index` are column names in hashed preimages (`_build_record_id_preimage`), and `__node_content_hash` is in the operator cache's hashed row: every pipeline entry id, base entry id, side-effect id and operator record id moves | as (b) | +| Layouts | none | all five layout versions and the Python function type's revision | as (b) | +| Time zones, logical types, dotted names, table names, row order | handled by the same mechanism | **not handled**; (a) is needed anyway | (a) is needed anyway | +| Existing stores | untouched | Delta stores of 0.4.0rc1 are no longer read | as (b) | +| What other SpiralDB readers see | `ox___data_context` for `__data_context` | a plain name | a plain name | + +(b) and (c) pay the cost of moving hashes and still need (a). **Recommended: (a).** + +Where (a) lives: in `SpiralDBConnector`, for a table it creates through +`create_table_if_not_exists`, which is where `ConnectorArrowDatabase` learns a table is new. A +table is an *Orcapod store table* when its key-value metadata holds a manifest (3.3); every other +table is read and written exactly as today, without decoding. + +## 3. Columns: the exact encoding + +### 3.1 Names + +`E(c)`, the stored name of a value column `c`: + +1. `c` is **plain** when it is not empty, does not start with `__` or `ox_`, and holds none of + `.`, `$`, `*` and the ASCII control characters (0-31, 127). A plain name is stored as it is. +2. Any other name is stored as `ox_` followed by `c` with each of `.`, `$`, `*`, `;` and each + control character written as `;` and two upper-case hex digits. + +| Orcapod name | Stored name | +|---|---| +| `x`, `_source_x`, `_tag_source_id::`, `a;b`, `é`, `a b` | unchanged | +| `__data_context` | `ox___data_context` | +| `a.b` | `ox_a;2Eb` | +| `a;2Eb` | `a;2Eb` (plain) | +| `ox_a;2Eb` (a user's column that looks encoded) | `ox_ox_a;3B2Eb` | +| `ox_` | `ox_ox_` | +| the empty name | `ox_` | + +`D(s)`: if `s` does not start with `ox_`, `s`; otherwise drop `ox_` and replace each `;HH`. + +**Injective, proof.** A plain name does not start with `ox_`, so it never equals an encoded one, +and plain names map to themselves. Among encoded names, the escape replaces single characters by +codes that start with `;`, and a literal `;` is itself escaped, so reading left to right every `;` +starts a code of exactly two digits and every other character is literal: `D(E(c)) = c`. So `E` is +injective. **Accepted by SpiralDB's known rules**: no `.` remains, and no stored value column +starts with `__` or `$`. The prototype checks round trip, injectivity and these rules on 200,000 +adversarial names; the implementation keeps that as a property test. + +Why these characters: `:` `::` space, `-`, `;`, `"`, `/`, upper case, non-ASCII letters and JSON +text were accepted live (ITL-1164). `%` was never tried, so the escape is `;`, not `%`. `$` is +"reserved for key columns" (Read: native library text). `*` selects all columns in +pyspiral's expressions (`Expr.__getitem__`). + +- **Key column.** `__record_id` is stored as it is: SpiralDB accepts `__` on a key column. + `E` never yields a name that starts with `__`, so a value column cannot collide with it. +- **Store-only columns.** A name that starts with `ox_` and is not any `E(c)` is free for the + store. `ox_order` (3.6) is such a name: `order` is plain, and `E("ox_order")` is `ox_ox_order`. +- **Unicode.** Characters are kept as code points, with no normalisation. To probe: whether + SpiralDB normalises (`é` as one or two code points) or folds case. If it does, two names that + it merges are refused before writing; the rule is written from the probe, not guessed. +- **Length.** An encoded name adds 3 characters and 2 per escaped one. No client limit was found + (Read); to probe. The longest names Orcapod writes are a join's system tags: + `_tag_record_id::<64 hex>::<64 hex>:0` is 148 characters after one join (section 1's list), and + each nested join adds 68. +- **Nested names.** SpiralDB stores a struct column as a column group, and its name rules are + stated for "column group columns", so a struct field named `a.b` or `__x` may be refused or + split. The same `E` is applied to struct field names at every depth. + +### 3.2 What is kept, per Arrow type + +The store writes a *physical* column and restores the *logical* one from the manifest. All +physical fields are declared nullable (SpiralDB stores a null in a non-null struct field as the +type's zero, seen live, ITL-936); the logical flags are checked before a write and after a read, +as the nullability record does today. + +| Logical type | Physical | Restored by | First version | +|---|---|---|---| +| timestamp with a zone, top level or nested | the same integers, `timestamp[unit]` without a zone | a zero-copy view under the recorded type. Exact for every zone and unit the physical type keeps: Arrow stores UTC instants | yes | +| logical (extension) type, top level | its storage type, mapped by this table | the recorded extension name and metadata; a live type when it is registered, else field metadata | yes | +| logical type in a list (`list[UUID]`) | a native container is itself one top-level extension type over its storage | as above | yes | +| logical type nested in a plain list or struct | Orcapod refuses it at definition (`require_storable_in_struct_field`); one that reaches the store is refused | - | refuse | +| logical data-tag | as a top-level column; the data-tag marker is field metadata, and the manifest keeps field metadata at every depth | manifest | yes | +| `large_string` / `large_binary` / lists | native | large normalisation, as today | yes | +| `fixed_size_binary[n]` | `large_binary` | recorded width; another width is refused on read (as Delta) | yes (F5) | +| `duration` | `int64` | view | yes (F5) | +| `null` column | `int8`, all null | recorded type | yes (F5) | +| struct | struct with encoded field names. SpiralDB returns the fields sorted by name (seen live, ITL-1367) | fields matched by name, in recorded order | yes | +| **null struct** | refused today (`UnsupportedValueError`), at flush, after the function ran | later: a hidden presence field | refuse, but when rows are added (`validate_records`), before anything is buffered | +| map with fields `key` / `value` | native | recorded key order flag, nullability and metadata | keep if the live matrix keeps it, else refuse | +| renamed map | IPC renames the fields, so the record cannot hold them | - | refuse, as today | +| `interval`, union, list view, dictionary, run-end encoded | - | - | refuse (the client refuses an interval; streams refuse the others) | +| `decimal256`, `float16`, `date64`, `time` | native (the client accepts them, offline) | recorded type | by live matrix; a lossy one is refused | +| float bits (`-0.0`, NaN payloads) | native | - | by live matrix; a lossy one is recorded as an integer or refused | + +"Kept" must be shown twice: on the fake by the type matrix, and live by the same matrix. A row +is kept in the first version only when **both** keep it. + +### 3.3 The manifest, against today's two records + +| | nullability record (ITL-936) | Arrow metadata (ITL-471) | manifest (proposed) | +|---|---|---|---| +| Holds | non-null paths | field and schema metadata | the whole logical schema: names, order, types, nullability, metadata; the record path; the encoding version | +| Size | chunked, under 8 KiB each | **one entry: over 8 KiB the write raises** (Measured: 200 columns with a 40-byte metadata value) | chunked | +| Written | first write | before **every** write | once | +| After a failed first write | removed (races, ITL-1190) | previous value put back (races) | stays | +| Two writers | last header wins | last entry wins | a set: both stay, and a difference is found | + +Format: header key `__orcapod_store__/` with `{"format", "version", "chunks", "sha256"}`, +and chunk keys `__orcapod_store__//`. The payload is JSON: encoding version, record +path, and the Arrow schema in storage form (logical types as `ARROW:extension:*` field metadata, +`canonical_form.storage_form_schema`) as base64 IPC. Chunks go first, then the header. + +- **No write ever replaces or removes a manifest** (a grow-only set of digests), so two writers + cannot lose one another's. Manifests are compared as decoded schemas, field by field at every + depth (Arrow's own type equality ignores nested names), so bytes that differ only by pyarrow + version agree. +- **Two different manifests in one table** are refused, on read and write, naming both. Data is + never decoded by the wrong one. The pipeline determines a node's columns, so this should not + happen; if it does it is a bug or another Orcapod version, and stopping is right. +- **A manifest without rows** (a first write that failed) is inert: the table reads as having + those columns and zero rows. The next writer of the same schema just writes. +- A writer compares its rows' schema with the manifest before buffering; the check costs nothing + after the first time (the manifest of a table id does not change). +- To probe: whether parallel `set_metadata` calls on **different** keys keep both. pyspiral says + entries are upserted and parallel calls race "to set a value". If the server replaces the + whole map, the manifest goes to a table of its own (the registry of section 5.4), where a write + is an upsert of one row. + +Limits: 1,024 entries a table, 8 KiB a pair, 255 characters a key. A key here is at most 90 +characters. A 1 MiB schema fits in about 130 entries. + +### 3.4 The fake must be made as strict as the client first + +F5 means that today's "kept" in the SpiralDB column of `docs/reference/database-types.md` is not +evidence for `fixed_size_binary`, `duration` and `null`. The fake's other gaps that matter here: +struct fields keep their order (live: sorted), every table name is accepted (client: 128 +characters, `[a-zA-Z_][a-zA-Z0-9_-]*`), `$` is accepted, duplicate keys in one write are +accepted (native text: "Duplicate keys found in input batch"), and a write of key columns only is +accepted (native text: "Write array contains only key columns"). The first PR makes the fake +refuse these, so the suite fails where the service would. + +### 3.5 Tables of another program, other readers, pushdown + +- **A table another program wrote** has no manifest: names, types and nullability are read as + today, so a user's column called `ox_a` stays `ox_a`. `SpiralDBTableSource` is unaffected. The + store refuses to write into a table without a manifest that has value columns. +- **Another SpiralDB reader of a store table** (CLI, Polars, DuckDB, spiral-sdk) sees `ox___pod_ts` + as a timestamp without a zone (UTC instants), a logical type as its storage, a `File` or user + class as its struct with sorted fields, and `ox_order`. Plain user columns, tags and + `_source_*` are readable under their own names. Documented, with the encoding version. +- **A `SpiralDBTableSource` over a store table** must not silently show encoded names: it reads + the manifest, so it shows Orcapod's names, and refuses a manifest version it does not know. +- **Writes by another program into a store table** cannot be prevented. A read checks every + batch against the manifest: a missing or retyped column, or a null in a non-null one, raises + naming it; an extra column not in the manifest raises too. +- **Pushdown.** A predicate on an Orcapod column is built on `E(name)`, its literal converted as + the column is (a zone-aware instant to its UTC timestamp; a logical column is not pushed down). + Encoding removes `.` from names, which `table["a.b"]` would split. Store lookups use only + binary, text and boolean columns, so nothing else is needed at first. + +### 3.6 Order + +**Column order.** SpiralDB stores value columns sorted by name. A read puts them in the +manifest's order, so a table reads back in the order of its first write, as on Delta. + +**Row order.** SpiralDB returns key order. The key is a hash, so stored rows come back shuffled +(Measured): + +| Store | `CachedSource` over k = 0..5 reads | `Batch(2)` gives y | +|---|---|---| +| in memory, Delta | 0, 1, 2, 3, 4, 5 | [0, 1], [2, 3], [4, 5] | +| SpiralDB (prototype) | 4, 5, 1, 2, 3, 0 | [4, 5], [1, 2], [3, 0] | + +This is a difference in computed results, not presentation. The raw pipeline table also comes +back in another order; `as_source()` of a function node happened to agree (6 and 60 rows), which +is not a guarantee. + +Design: a store-only column `ox_order` (`int64`). A handle gives a batch consecutive values from +`max(last + 1, time.time_ns())`, in row order. A read sorts by (`ox_order`, `__record_id`) and +drops the column. One writer: exactly the order written. Several writers: deterministic for a +given store content; interleaved by their clocks, as concurrent Delta commits are by commit. It +is in no hash, never leaves the store, and costs 8 bytes a row and a sort per read. + +### 3.7 Does anything move? + +No. Hashes, `record_path` tuples, system-tag column names, layout versions, data function type +revisions and golden values are computed above the database, from Orcapod names and types. The +manifest's SHA-256 and the table name's SHA-256 (section 5) are in names; both get a row in the +hash site inventory ("in a name"). The store's own format is versioned by the manifest's +`version`, independent of `pdb_v1` and the others. The implementing PRs run `--check` on golden. + +## 4. Lookups + +### 4.1 What a run costs today + +SpiralDB calls of the six-step job of `prototype.py` with today's lookups (Measured on the fake; +each is at least one round trip on the service): + +| Rows | Run | list tables | look up table | metadata reads | writes | whole-table scans | +|---|---|---|---|---|---|---| +| 2 | first | 35 | 15 | 5 | 5 | 3 | +| 50 | first | 227 | 15 | 5 | 5 | 3 | +| 50 | unchanged rerun | 10 | 14 | 7 | 0 | 7 | +| 50 | 10 rows added | 48 | 89 | 48 | 5 | 34 | + +Three separate problems: + +1. **`list_tables` per row** (4 per row on a first run): `ConnectorArrowDatabase` lists the whole + project to ask whether one table exists. At about 1 s a call (seen live, ITL-926: 1.2 s for + 27 tables) 50 rows spend minutes. +2. **A whole-table scan per new row and table.** `ResultCache.lookup` (by `__input_data_hash`) + and `add_pipeline_record` (by `__pipeline_base_entry_id`) are called once per row, through + `get_records_with_column_value`. N new rows read the table N times: quadratic. The issue's + "record-id lookup pushdown" covers neither, since both look up by another column; only the + side-effect log looks up by record id. +3. **Whole tables per node per run** (`_fetch_joined_records` reads the pipeline table and the + result table, payload included, whatever the inputs). + +### 4.2 What pyspiral 0.16.33 offers (Read) + +| Facility | Use | +|---|---| +| `scan(proj, where=expr)`; `==`, `!=`, `<` ..., `&`, `\|`, `~`, `is_null`; `expr.in_([...])` (a list literal: `list.contains`) | lookup by any column | +| `scan(proj).to_record_batches(key_table=keys)` | **take by key**: a table whose columns are exactly the key schema | +| `scan(..., asof=version)`, `last_modified_at()` | pin a read; one call says whether a table changed | +| `scan(table.select("a", "b"))` | read some columns only | +| `scan(..., key_ranges=[KeyRange])` | ranges; excludes `key_table` | +| `scan_keys` | keys only. The client says it reads keys of the referenced column groups; seen live, a scan of key columns alone was refused (ITL-926) | +| `Spiral.sample`, `enrich` | not needed | + +There is no conditional write, no read of "rows changed since a version", and no transaction over +two tables. Docs say an unsorted or repeated `key_table` is supported but slower; the native text +says "must be sorted by key". So keys are always sorted by bytes and made unique. + +### 4.3 Design, for SpiralDB only + +The protocol methods stay as they are. Three optional connector methods, which the database uses +when the connector has them (as `get_arrow_schema` today); SQLite and PostgreSQL keep their path: + +- `read_by_keys(table, ids)`: `key_table` of `{"__record_id": large_binary}` (cast to the key + type the table states: `binary` or `large_binary`), sorted and unique, 10,000 ids a batch (about + 0.6 MB of 60-byte ids; the size is a constant set by a live measurement). Serves + `get_record_by_id`, `get_records_by_ids` and `skip_existing` (which today scans the table and + converts it to Python). +- `read_where(table, pairs)`: equality on encoded names. Serves `get_records_with_column_value`. + Binary, text, boolean and integer columns only; anything else is filtered by Arrow on the + client, as today. +- `read_columns(table, names)`. + +That makes each lookup small, but still one round trip a row. At 0.7 to 1.7 s a scan (seen live) +1,000 new rows would take an hour. So lookups are answered from a **per-table index held for one +run**, as `DeltaTableDatabase` does with its `KeyIndex`: + +- On the first lookup in a table, read only the lookup columns of all rows with a pinned `asof` + (`__record_id`, `__input_data_hash`, `__data_context`, `__pod_ts`, `ox_order` for results; + `__record_id`, `__pipeline_base_entry_id`, `__pipeline_recomputation_index`, + `__node_content_hash`, `__data_context` for the pipeline). A miss needs no call. Hits read their + full rows by `read_by_keys`. +- Columns indexed are those a caller has filtered by, so the database needs no knowledge of + table kinds. +- Own commits extend the index. Pending rows are consulted as today. +- About 250 bytes a row: 1 M rows is about 250 MB and one scan. `read_where` per lookup is the + fallback above a limit (proposed: 2 M rows by `row_count_estimate`). + +Batch-loading the rows a run needs (problem 3) is a change in `_fetch_joined_records`: ask by the +run's base entry ids, then result ids, instead of `get_all_records`. It is a separate PR after the +store works, since it touches every store's path. + +**Staleness.** `refresh_table` is already called for each table of a function node at the start of +a run and at every read of what is stored (ITL-1408). On SpiralDB it becomes one +`last_modified_at` call: unchanged keeps the index, changed drops it. Within a run the handle +does not see another writer's rows, which costs at most a repeated computation, as on Delta; the +keyed check before a write (section 6) reads the latest version. + +**Table existence and handles.** `lookup_table` once per table and handle (the exact-name +listing), kept until `refresh_table`; "does not exist" is asked again at refresh and before +create. Expected calls per run: about 2 per table for an unchanged rerun, plus 2 to 4 per commit, +and none per row. The tests assert these counts on the fake. + +## 5. Table names + +### 5.1 Today + +Each path component has every character other than `[a-zA-Z0-9_]` replaced by `_`, joined by +`__`; `t_` in front of a digit. + +### 5.2 Collisions: disproved safe, by example + +| Path A | Path B | One name today | +|---|---|---| +| `job/_result/my-fn//v0/...` | `job/_result/my_fn//v0/...` | `job___result__my_fn____v0__...` | +| `job/_result/café//...` | `job/_result/cafè//...` | `job___result__caf_____...` | +| `run-1/add/pdb_v1` | `run_1/add/pdb_v1` (two job names) | `run_1__add__pdb_v1` | +| `a/b__c` | `a__b/c` | `a__b__c` | +| `a_/b` | `a/_b` | `a___b` | +| `1x` | `t_1x` | `t_1x` | + +The first is reachable with the public `function_name` argument, and the two functions need only +the same outputs and major version. Through the prototype, `my_fn` (3x) was given `my-fn`'s (2x) +stored `[0.0, 2.0]` for inputs `[0.0, 1.0]`: a result lookup matches the input hash and the data +context, not the function. On `main` no function table reaches a connector database, so nobody +has been given such a result; the same mapping serves SQLite and PostgreSQL, where it is latent +(decision 6). + +**Length** (Measured): 181 and 182 characters for the function pipeline tables of a job named +`proto` with functions `add` and `mean`, 123 and 124 for their result tables. Limit: 128 (Read, +`spiral/api/types.py`: `TableName`). Whether the server enforces 128 is to probe; the design +stays below it either way. + +### 5.3 The mapping + +`op--`: `` is the 64-hex SHA-256 of the compact JSON list of the full path +(base path included), and `` is the components that hold no 64-hex hash, joined by `_`, +sanitised as today and cut to 56 characters. At most 124 characters, always `[a-z]`-initial, only +`[a-zA-Z0-9_-]`. Two paths share a name only if SHA-256 collides, and the manifest's recorded path +is compared on first use of a table, so even then (or if SpiralDB folds case) the store refuses +rather than mixes. A bare digest in a name carries no label, per the hash label rule. + +A reversible escape (no digest) was considered: it cannot fit. Two 64-hex hashes are already 128 +characters. + +### 5.4 Finding tables by path: the registry + +`list_table_paths(prefix)` must give real paths, and a digest cannot be reversed. Reading every +table's manifest costs a call a table. Proposed: the developer's lookup table (ITL-1100), one +table `op-tables` with key `table_name` and value columns `path` (JSON) and `format`: + +- a row is upserted **before** its table is created, so no store table is missing from it; +- a row's content is a function of its key, so two writers write the same row: the one kind of + upsert that really is harmless; +- listing is one scan of the registry, joined with the project's table list (a row whose table + was never created or was dropped is left out). + +The prefix `op-` is the store's. A store table name that exists without a manifest and with value +columns is refused. Cleanup: the registry names every store table of a dataset. + +## 6. Concurrent writers and failed writes + +SpiralDB upserts by key. The client retries a transaction "after conflicts" (3 times by default) +and reports "failed to commit transaction due to conflict" (Read). What counts as a conflict is +to probe; nothing read suggests that two upserts of one key do. Assume: both commit, the later +commit wins, and no error is raised. + +### 6.1 Is "same id, same content" true? + +| Table | Record id | What a second write of the same id changes | Harmless? | +|---|---|---|---| +| Function result | **random UUIDv7** of the output datagram | cannot happen between writers. Two writers computing one input store **two** rows; a lookup takes the newest `__pod_ts` | yes for storage; both values stay, and a nondeterministic function can then serve either | +| Function pipeline | hash of system tags, input hash, recomputation index | `__data_id`, `__computed`, `__output_data_hash`, `__is_ephemeral`, `__pipeline_run_id`, `__recorded_at` | **no** (below) | +| ... its recomputation index | read, then write | two writers both take index `n`; one recomputation disappears from the history | **no** | +| Side-effect log | hash of the same preimage | `pipeline_run_id`, `executed_at` | the log is, the **delivery is not**: both delivered before either logged | +| Operator cache | hash of the row and node content hash | `ox_order`; float bits (below) | yes, up to float bits | +| Cached source | hash of the row with system tags | `ox_order`; float bits | yes, up to float bits | + +Every row of a table has the same `__node_content_hash` for one id only where that hash enters +the id: it does for the operator cache. For the pipeline table it is redundant with the path and +system tags by design, so the two writers' values agree unless two nodes share both. + +*Float bits*: the Arrow hash reads `-0.0` as `0.0` and every NaN alike (ITL-1179), so one id can +hold two bit patterns. The stored value is one of them; the same holds on Delta. + +**What an overwritten pipeline record breaks.** Writer A records entry `e` naming result `r_A`, +and its downstream nodes compute from `r_A`. Writer B overwrites `e`, naming `r_B`. Both results +stay, so nothing dangles, but: `trace` of A's downstream rows reaches result `r_A` with no +pipeline entry naming it; the entry's run id and time are B's, so A's run appears to have computed +nothing; and a reader that read `e` before and after sees history change. On Delta the first +committed record stays (insert when not matched), so a record once read never changes. + +### 6.2 What the design promises + +1. **A record id is stored once**, always: it is the table's key. *(holds under any race)* +2. **A pipeline record never names a result that was not stored.** The result table commits first + and `PendingCommit` withholds the records (ITL-1412). Each SpiralDB write is one atomic + transaction. *(holds under any race; needs a live test that a read after a commit sees it, + from another client)* +3. **A failed write leaves no half-written table**: chunks, then header, then rows, and no + rollback. *(holds under any race)* +4. **An existing record is not overwritten by a later run.** `skip_existing` is decided by + `read_by_keys` at the latest version just before the write. *(holds except in the window + between that read and the commit)* + +5. **Not promised**: first-writer-wins inside that window, exactly-once side effects, one + recomputation index per recomputation. + +### 6.3 Options for what is not promised + +| Option | Closes the window? | Costs | +|---|---|---| +| **A. One writer per table at a time, documented, and checked after each commit** (recommended first): after a commit, re-read the written ids' `ox_order`; another value means another writer overwrote them, and a warning names the table and the count | no; reports most cases (a later overwrite is missed) | one keyed read per commit (about 1 s) | +| B. The key becomes (`__record_id`, `ox_writer`), one UUIDv7 a handle: every writer's row stays, reads keep one per id by (`ox_order`, `ox_writer`) | no record is ever lost, and `trace` could show every one. The kept one can still change when a writer with an earlier clock commits late | rows grow with races; every read groups by id; `key_table` needs the whole key, so lookups use `where`; the key schema **cannot be changed later** | +| C. A lease in table metadata | no: no compare-and-set, so two can take it | - | +| D. A lock outside SpiralDB | yes | a service to run and configure | +| E. Wait for a conditional write (`spiral-sdk`, ITL-931) | yes | not available | + +A is recommended because one job writing one store at a time is the expected use, and because 1 to +3 hold regardless. B is the only choice that is hard to make later: a store made under A is +rebuilt to move to B. If several processes are expected to write one store soon (Ray workers do +not: the driver writes), choose B now. + +### 6.4 Failed writes + +| Failure | Today | Design | +|---|---|---| +| the write raises, nothing committed | `ConnectorArrowDatabase` **drops** the rows from its queue (`take_ready`, never restored) | restore them (`PendingCommits.restore`) and withdraw their dependents, as Delta does; a later flush retries. A refusal of the rows themselves still drops them | +| the commit is **ambiguous** (committed, but the reply is lost) | as above | results: a retry upserts the same UUIDs, harmless. Pipeline records: a retry is skipped by `skip_existing`. The run still reports failure | +| the result table commits, the pipeline table fails | results without records | the next run finds them by input hash, computes nothing, writes the records | +| a manifest or registry row without rows | - | inert | +| a side effect was delivered and its log row failed | the row is dropped: delivered again next run | the row stays queued; a crash still delivers again (at least once, as on Delta) | +| interrupted between two tables' commits | - | promise 2; the job reruns | + +Write-size limits and the time of one commit are to probe. `commit_every_rows=100` gives one +commit per table per 100 rows. Orcapod flushes per table, so several node tables are several +transactions; there is no transaction over tables. + +Observers write with `flush=True`, one SpiralDB transaction per event. They stay off a SpiralDB +store by default (give them an in-memory or Delta store) until they batch. + +## 7. Live probes (throwaway tables, agent workload; before PR 3) + +| # | Question | Decides | +|---|---|---| +| P1 | names: each ASCII character and class of 3.1, `ox_` names, 1 to 1,024 characters, case pairs, NFC/NFD pairs; nested field names | 3.1 | +| P2 | table name of 128 and 129 characters, case pair, `-` | 5.3 | +| P3 | the type matrix, physical forms; float bits; `null`; null struct; struct field order | 3.2 | +| P4 | `key_table` with `binary` and `large_binary`, unsorted, repeated, absent ids; 1 to 100,000 ids: time | 4.3 | +| P5 | `where` equality and `in_` on binary; time against a table of 10^3 to 10^6 rows | 4.3 | +| P6 | parallel `set_metadata` of different keys, 50 pairs | 3.3 | +| P7 | two clients write one key at once, 50 pairs: errors, winner; the same with a first write of new columns | 6 | +| P8 | read after commit from a second client, both at once and after `create_table(exist_ok=True)` raced by two | 6.2 | +| P9 | time of list, look up, metadata, commit (1, 100, 10,000 rows), and of a rerun | 4 | +| P10 | duplicate key in one write; a write killed midway | 6.4 | + +## 8. First working version, in order + +The **smallest working version is PRs 1 to 5**. Each is reviewable alone; a job is refused as +today until PR 5. + +| PR | Content | Tests | +|---|---|---| +| 1 | Fake as strict as the client (3.4); the connector refuses what it must (`fixed_size_binary`, `duration`, `null`, table names); `database-types.md` regenerated | each rule, with the native library's text; matrix | +| 2 | `spiral_store` codec: names, types, manifest, as pure functions with no pyspiral | property tests: names (adversarial alphabet, nested), schema round trip over the type matrix, chunk sizes, two manifests | +| 3 | Connector: store tables use the codec; `ox_order`; registry and table names; null struct refused when added; `ConnectorArrowDatabase` asks the connector for a table's name | matrix on the fake; column and row order; foreign tables unchanged; a failed first write; two connectors with an injected failure (ITL-1190's interleaving); collisions of 5.2 | +| 4 | Lookups (4.3): keyed and `where` reads, the run index, table handles; failed rows restored (6.4) | call counts per run asserted; equivalence with the whole-table path (`test_*_lookup_equivalence`); staleness by a second handle | +| 5 | Job: refusals removed where covered; the post-commit check (option A); docs (names, other readers, cleanup, permissions, single writer) | the pipeline store suites parametrised over the fake: first run, rerun, added rows, changed version, `run()` and `run_async()`, save and load, `load_only`, `clear_cache`, separate result database, `trace`; equal to Delta: sync exactly, async as sets | +| 6 | Live suite (the existing `spiral-integration` job): PR 5's job, the type matrix, P7, P8, cost printed; every table dropped | live | +| later | batched `_fetch_joined_records`; null structs; observers; maps if P3 refuses; option B or E | | + +ITL-1391 (load a saved connector database) and ITL-1381 (read before flush) are needed for save +and load in PR 5; both are in progress. A saved config has no credential today (`to_config`: +project, dataset, `overrides`); `overrides` is free-form client configuration, so PR 5 refuses to +save an override that is not a known non-secret key (`server.url`). + +### Decisions for the developer + +| # | Decision | Recommended | +|---|---|---| +| 1 | Where the mapping lives: (a) the store, (b) rename everywhere, (c) mixed | (a) | +| 2 | Concurrent writers: A (one writer, checked) or B (key with a writer id), which cannot be changed later without rebuilding stores | A | +| 3 | Row order: store `ox_order` so reads follow the written order | yes; otherwise results differ from Delta | +| 4 | Table names `op--` with the registry table `op-tables` (ITL-1100's lookup table) | yes | +| 5 | Two different manifests in one table stop the job, rather than one winning | stop | +| 6 | Use the collision-free path mapping for SQLite and PostgreSQL too (their existing tables would no longer be found) | yes, in its own PR before 0.4.0, while nobody has such a store | +| 7 | Null structs refused in the first version (a `T \| None` user-class output holding a null) | yes | +| 8 | Observers not on a SpiralDB store at first | yes | +| 9 | The 8 KiB failure of today's Arrow metadata entry on tables that are not store tables: fix now (chunks) or leave | fix in PR 2, same chunk code | +| 10 | Stay on pyspiral 0.16.33 for this (ITL-931 and ITL-1186 later). The codec, manifest and registry do not depend on the client | yes | + +## 9. Not verified here + +- Everything marked "to probe". The fake cannot answer timing, conflicts, visibility or server + limits. +- The prototype maps names and top-level types only, and its job has number and text columns and + UTC timestamps; it runs no logical type. It does not implement the manifest set, `ox_order`, the + registry, the proposed table names or the lookups. +- The async path, save and load, `load_only` and `trace` were not run through the prototype. +- The fake's and the matrix's behaviour for logical types nested at depth was read, not run + through the prototype. diff --git a/docs/dev/specs/itl-1446/prototype-output.md b/docs/dev/specs/itl-1446/prototype-output.md new file mode 100644 index 000000000..721b16658 --- /dev/null +++ b/docs/dev/specs/itl-1446/prototype-output.md @@ -0,0 +1,42 @@ +# Prototype output (generated: `PYTHONPATH=. uv run python docs/dev/specs/itl-1446/prototype.py`) + +```text +codec: 200000 distinct names -> 200000 stored names, all decoded +job: first run calls {'add': 6, 'mean': 2, 'notify': 2}, rerun calls {}; rows, schemas, system tags and content hashes equal the in-memory store's +order (6 rows): pipeline table equal False, as_source() equal True +order (60 rows): pipeline table equal False, as_source() equal True +cached source, in memory: k [0, 1, 2, 3, 4, 5], Batch(2) gives y [[0.0, 1.0], [2.0, 3.0], [4.0, 5.0]] +cached source, Delta: k [0, 1, 2, 3, 4, 5], Batch(2) gives y [[0.0, 1.0], [2.0, 3.0], [4.0, 5.0]] +cached source, SpiralDB: k [4, 5, 1, 2, 3, 0], Batch(2) gives y [[4.0, 5.0], [1.0, 2.0], [3.0, 0.0]] + +| Rows | Run | list tables | look up table | get metadata | set metadata | create table | write transaction | whole-table scan | +|---|---|---|---|---|---|---|---|---| +| 2 | first | 35 | 15 | 5 | 5 | 5 | 5 | 3 | +| 2 | unchanged rerun | 10 | 14 | 7 | 0 | 0 | 0 | 7 | +| 2 | 10 rows added | 48 | 89 | 48 | 0 | 5 | 5 | 34 | +| 10 | first | 67 | 15 | 5 | 5 | 5 | 5 | 3 | +| 10 | unchanged rerun | 10 | 14 | 7 | 0 | 0 | 0 | 7 | +| 10 | 10 rows added | 48 | 89 | 48 | 0 | 5 | 5 | 34 | +| 50 | first | 227 | 15 | 5 | 5 | 5 | 5 | 3 | +| 50 | unchanged rerun | 10 | 14 | 7 | 0 | 0 | 0 | 7 | +| 50 | 10 rows added | 48 | 89 | 48 | 0 | 5 | 5 | 34 | + +| Path A | Path B | Today's one name | Proposed names differ | +|---|---|---|---| +| `job/_result/my-fn/<64 hex>/v0/python.function.v1/rev1/rdb_v1` | `job/_result/my_fn/<64 hex>/v0/python.function.v1/rev1/rdb_v1` | `job___result__my_fn__<64 hex>__v0__python_function_v1__rev1__rdb_v1` | True | +| `job/_result/café/<64 hex>/v0/python.function.v1/rev1/rdb_v1` | `job/_result/cafè/<64 hex>/v0/python.function.v1/rev1/rdb_v1` | `job___result__caf___<64 hex>__v0__python_function_v1__rev1__rdb_v1` | True | +| `run-1/add/pdb_v1` | `run_1/add/pdb_v1` | `run_1__add__pdb_v1` | True | +| `a/b__c` | `a__b/c` | `a__b__c` | True | +| `a_/b` | `a/_b` | `a___b` | True | +| `1x` | `t_1x` | `t_1x` | True | + +| Stored table | Today's length | Proposed length | +|---|---|---| +| `proto___result__add__<64 hex>__v0__python_function_v1__rev1__rdb_v1` | 123 | at most 124 | +| `proto___result__mean__<64 hex>__v0__python_function_v1__rev1__rdb_v1` | 124 | at most 124 | +| `proto__add__<64 hex>__v0__python_function_v1__schema_<64 hex>__pdb_v1` | 181 | at most 124 | +| `proto__mean__<64 hex>__v0__python_function_v1__schema_<64 hex>__pdb_v1` | 182 | at most 124 | +| `proto__side_effects__notify__schema_<64 hex>__tdb_v1` | 108 | at most 124 | + +wrong result: my-fn doubles [0.0, 2.0]; my_fn triples [0.0, 1.0] and is given [0.0, 2.0] +``` diff --git a/docs/dev/specs/itl-1446/prototype.py b/docs/dev/specs/itl-1446/prototype.py new file mode 100644 index 000000000..0805a0322 --- /dev/null +++ b/docs/dev/specs/itl-1446/prototype.py @@ -0,0 +1,526 @@ +"""ITL-1446: a throwaway prototype of option (a), to measure it on pyspiral's disk fake. + +Not the implementation: it maps names and types in the connector, keeps the logical schema +in the table's key-value metadata, and runs a whole job on the fake. It answers three +questions with numbers: + +1. ``codec``: is the column-name encoding injective (random names, adversarial alphabet)? +2. ``job``: does a job (function, join, filter, group by, second function, side effect) give + the in-memory store's rows, record ids and hashes, and does a rerun call nothing? +3. ``cost``: how many SpiralDB calls does each run make today, by number of rows? + +Run: ``PYTHONPATH=. uv run python docs/dev/specs/itl-1446/prototype.py`` +""" + +from __future__ import annotations + +import base64 +import hashlib +import random +import tempfile +from collections import Counter +from contextlib import contextmanager +from typing import Any, cast +from pathlib import Path +from unittest.mock import patch + +import polars as pl +import pyarrow as pa + +from orcapod import PipelineJob, function_pod +from orcapod.core.operators import Batch, GroupBy, Join, PolarsFilter +from orcapod.core.sources import ArrowTableSource +from orcapod.core.sources.cached_source import CachedSource +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + InMemoryArrowDatabase, + SpiralDBConnector, +) +from orcapod.side_effects import SideEffectPod, SideEffectPodConfig +from orcapod.types import ColumnInfo +from orcapod.utils.arrow_utils import normalize_table_to_large_types +from tests.test_databases import fake_pyspiral + +# ---------------------------------------------------------------- column-name codec + +MARK = "ox_" +ESCAPED = frozenset(".$*;") | {chr(i) for i in range(32)} | {chr(127)} + + +def encode(name: str) -> str: + """The stored name of a value column (section 3.1 of the design).""" + plain = ( + name != "" + and not name.startswith(("__", MARK)) + and not any(c in ESCAPED and c != ";" for c in name) + ) + if plain: + return name + return MARK + "".join(f";{ord(c):02X}" if c in ESCAPED else c for c in name) + + +def decode(stored: str) -> str: + """The Orcapod name of a stored value column.""" + if not stored.startswith(MARK): + return stored + out, rest = [], stored[len(MARK) :] + i = 0 + while i < len(rest): + if rest[i] == ";": + out.append(chr(int(rest[i + 1 : i + 3], 16))) + i += 3 + else: + out.append(rest[i]) + i += 1 + return "".join(out) + + +def check_codec(rounds: int = 200_000) -> None: + """Round trip, injectivity and SpiralDB's rules over adversarial names.""" + rng = random.Random(1446) + pieces = [ + "_", + "__", + MARK, + ".", + ";", + ";2E", + ";3B", + "$", + "*", + "a", + "B", + "é", + "é", + "::", + " ", + "\n", + "\x00", + "{", + '"', + "x_", + "o", + ] + names = {"", "__record_id", MARK, "a.b", "a;2Eb", "ox_a;2Eb"} + while len(names) < rounds: + names.add("".join(rng.choices(pieces, k=rng.randint(0, 7)))) + stored = {encode(n) for n in names} + assert len(stored) == len(names), "not injective" + for n in names: + s = encode(n) + assert decode(s) == n, (n, s, decode(s)) + assert s and "." not in s and not s.startswith(("__", "$")) and s != "*" + print( + f"codec: {len(names)} distinct names -> {len(stored)} stored names, all decoded" + ) + + +# ------------------------------------------------------------------- the connector + +SCHEMA_KEY = "__orcapod_prototype__" + + +class MappingConnector(SpiralDBConnector): + """Maps names and (top-level) types on write, and back on read.""" + + def _logical(self, table_name: str) -> pa.Schema | None: + kv = self._project.table(self._table_id(table_name)).get_metadata() + parts = [kv[k] for k in sorted(kv) if k.startswith(SCHEMA_KEY)] + if not parts: + return None + raw = base64.b64decode(b"".join(parts)) + return pa.ipc.read_schema(pa.py_buffer(raw)) + + def unstorable_column_reason( + self, name: str, arrow_type: pa.DataType, *, primary_key: bool + ) -> str | None: + return None + + def upsert_records( + self, + table_name: str, + records: pa.Table, + id_column: str, + skip_existing: bool = False, + ) -> None: + tbl = self._project.table(self._table_id(table_name)) + if self._logical(table_name) is None: + raw = base64.b64encode(records.schema.serialize().to_pybytes()) + tbl.set_metadata( + { + f"{SCHEMA_KEY}/{i:04d}": raw[i * 8000 : (i + 1) * 8000] + for i in range(-(-len(raw) // 8000)) + } + ) + names, arrays = [], [] + for field, column in zip(records.schema, records.columns): + if isinstance(field.type, pa.BaseExtensionType): + storages: list[Any] = [cast(Any, c).storage for c in column.chunks] + column = pa.chunked_array( + storages, type=cast(Any, field.type.storage_type) + ) + if pa.types.is_timestamp(column.type) and column.type.tz is not None: + column = pa.chunked_array( + [c.view(pa.timestamp(column.type.unit)) for c in column.chunks] + ) + names.append(field.name if field.name == id_column else encode(field.name)) + arrays.append(column) + rows = pa.table(arrays, names=names) + if skip_existing: + held = self._spiral.scan(tbl.select()).to_table() + ids = set(held.column(id_column).to_pylist()) + rows = rows.filter( + pa.array([i not in ids for i in rows.column(id_column).to_pylist()]) + ) + if rows.num_rows: + tbl.write(rows) + + def get_arrow_schema(self, table_name: str) -> pa.Schema: + schema = self._logical(table_name) + assert schema is not None + return schema + + def get_column_info(self, table_name: str) -> list[ColumnInfo]: + return [ + ColumnInfo(name=f.name, arrow_type=f.type, nullable=f.nullable) + for f in self.get_arrow_schema(table_name) + ] + + def iter_batches( + self, query: str, params: Any = None, batch_size: int = 1000 + ) -> Any: + table_name = query.split('"')[1] + tbl = self._project.table(self._table_id(table_name)) + schema = self._logical(table_name) + if schema is None: + return + for batch in self._spiral.scan(tbl.select()).to_record_batches(): + rows = normalize_table_to_large_types( + pa.Table.from_batches([batch]), keep_null=True + ) + arrays = [] + for field in schema: + name = ( + field.name + if field.name in rows.column_names + else encode(field.name) + ) + array = rows.column(name).combine_chunks() + target = field.type + if pa.types.is_timestamp(target) and target.tz is not None: + array = array.view(target) + elif isinstance(target, pa.BaseExtensionType): + array = pa.ExtensionArray.from_storage( + target, array.cast(target.storage_type) + ) + elif array.type != target: + array = array.cast(target) + arrays.append(array) + yield pa.RecordBatch.from_arrays(arrays, schema=schema) + + +# ------------------------------------------------------------------------- the job + +CALLS: Counter[str] = Counter() + + +@function_pod(output_keys=["total"]) +def add(y: float, b: float) -> float: + """First function.""" + CALLS["add"] += 1 + return y + b + + +@function_pod(output_keys=["mean"]) +def mean(total: list[float]) -> float: + """Second function, over a group.""" + CALLS["mean"] += 1 + return sum(total) / len(total) + + +def notify(ctx: Any, mean: float) -> None: + """A side effect.""" + CALLS["notify"] += 1 + + +def _source(rows: int, name: str, data: list[str]) -> ArrowTableSource: + fields = [ + pa.field("g", pa.large_string(), nullable=False), + pa.field("k", pa.int64(), nullable=False), + *(pa.field(n, pa.float64(), nullable=False) for n in data), + ] + arrays = [ + pa.array([f"g{i % 2}" for i in range(rows)], pa.large_string()), + pa.array(range(rows), pa.int64()), + *(pa.array([float(i + j) for i in range(rows)]) for j in range(len(data))), + ] + return ArrowTableSource( + pa.Table.from_arrays(arrays, schema=pa.schema(fields)), + tag_columns=["g", "k"], + tag_only_columns=True, + source_id=name, + ) + + +def build(database: Any, rows: int) -> PipelineJob: + """The job of ITL-1446's goals, without observers.""" + job = PipelineJob(name="proto", database=database) + with job: + joined = Join()(_source(rows, "left", ["y"]), _source(rows, "right", ["b"])) + kept = PolarsFilter([pl.col("y") >= 0.0])(joined) + summed = add.pod(kept, label="add") + grouped = GroupBy(["g"])(summed) + means = mean.pod(grouped, label="mean") + SideEffectPod(notify, SideEffectPodConfig(track_completion=True))( + means, label="notify" + ) + return job + + +def result(job: PipelineJob) -> list[tuple[Any, ...]]: + """Every row of both functions with its system tags and content hash.""" + out: list[tuple[Any, ...]] = [] + for label in ("add", "mean"): + node = job.nodes[label] + table = node.as_table(columns={"system_tags": True, "content_hash": True}) + out.append( + (label, node.content_hash().to_string(), table.schema, table.to_pylist()) + ) + return out + + +@contextmanager +def counted() -> Any: + """Count the SpiralDB calls that are round trips on the real service.""" + counts: Counter[str] = Counter() + patches = [] + + def wrap(cls: Any, method: str, label: str) -> None: + original = getattr(cls, method) + + def call(self: Any, *a: Any, **k: Any) -> Any: + counts[label] += 1 + return original(self, *a, **k) + + patches.append(patch.object(cls, method, call)) + + wrap(fake_pyspiral.FakeProject, "list_tables", "list tables") + wrap(fake_pyspiral.FakeProject, "table", "look up table") + wrap(fake_pyspiral.FakeProject, "create_table", "create table") + wrap(fake_pyspiral.FakeSpiral, "scan", "whole-table scan") + wrap(fake_pyspiral.FakeTable, "get_metadata", "get metadata") + wrap(fake_pyspiral.FakeTable, "set_metadata", "set metadata") + wrap(fake_pyspiral.FakeTable, "write", "write transaction") + for p in patches: + p.start() + try: + yield counts + finally: + for p in patches: + p.stop() + + +def check_job() -> None: + """Same rows as in memory; a rerun from a fresh connector calls nothing.""" + with tempfile.TemporaryDirectory() as root, fake_pyspiral.install(root): + plain = build(InMemoryArrowDatabase(), 6) + plain.run() + expected = result(plain) + CALLS.clear() + job = build(ConnectorArrowDatabase(MappingConnector("p")), 6) + job.run() + assert result(job) == expected, "rows differ from the in-memory store" + assert CALLS == {"add": 6, "mean": 2, "notify": 2}, CALLS + first = dict(CALLS) + CALLS.clear() + again = build(ConnectorArrowDatabase(MappingConnector("p")), 6) + again.run() + assert result(again) == expected + stored = again.nodes["add"].as_source().as_table().to_pylist() + memory = plain.nodes["add"].as_source().as_table().to_pylist() + key = str + assert sorted(stored, key=key) == sorted(memory, key=key) + print( + f"job: first run calls {first}, rerun calls {dict(CALLS)}; " + "rows, schemas, system tags and content hashes equal the in-memory store's" + ) + + +def check_order() -> None: + """Do reads of what is stored follow the in-memory store's row order?""" + for rows in (6, 60): + with tempfile.TemporaryDirectory() as root, fake_pyspiral.install(root): + spiral = ConnectorArrowDatabase(MappingConnector("p")) + memory = InMemoryArrowDatabase() + order = {} + for name, database in (("spiral", spiral), ("memory", memory)): + build(database, rows // 2).run() + job = build(database, rows) + job.run() + node = job.nodes["add"] + path = node._versioned_pipeline_path + base = node._pipeline_database + order[name] = ( + base.get_all_records(path).column("k").to_pylist(), + node.as_source().as_table().column("k").to_pylist(), + ) + print( + f"order ({rows} rows): pipeline table equal " + f"{order['spiral'][0] == order['memory'][0]}, " + f"as_source() equal {order['spiral'][1] == order['memory'][1]}" + ) + + +def check_cached_source_order() -> None: + """A cached source reads its rows in key (hash) order from SpiralDB.""" + with tempfile.TemporaryDirectory() as root, fake_pyspiral.install(root): + for name, database in ( + ("in memory", InMemoryArrowDatabase()), + ("Delta", DeltaTableDatabase(Path(root) / "delta")), + ("SpiralDB", ConnectorArrowDatabase(MappingConnector("p"))), + ): + cached = CachedSource(_source(6, "left", ["y"]), cache_database=database) + batched = Batch(2)(cached).as_table() + print( + f"cached source, {name}: k {cached.as_table().column('k').to_pylist()}, " + + f"Batch(2) gives y {batched.column('y').to_pylist()}" + ) + + +def check_cost() -> None: + """SpiralDB calls per run, today's lookups.""" + print( + "\n| Rows | Run | " + + " | ".join( + [ + "list tables", + "look up table", + "get metadata", + "set metadata", + "create table", + "write transaction", + "whole-table scan", + ] + ) + + " |" + ) + print("|---|---|---|---|---|---|---|---|---|") + for rows in (2, 10, 50): + with tempfile.TemporaryDirectory() as root, fake_pyspiral.install(root): + for run, count in ( + ("first", rows), + ("unchanged rerun", rows), + ("10 rows added", rows + 10), + ): + job = build(ConnectorArrowDatabase(MappingConnector("p")), count) + with counted() as counts: + job.run() + print( + f"| {rows} | {run} | " + + " | ".join( + str(counts[c]) + for c in [ + "list tables", + "look up table", + "get metadata", + "set metadata", + "create table", + "write transaction", + "whole-table scan", + ] + ) + + " |" + ) + + +# --------------------------------------------------------------------- table names + + +def today(path: tuple[str, ...]) -> str: + """The name ``ConnectorArrowDatabase`` gives a path today.""" + return ConnectorArrowDatabase(MappingConnector("p"))._path_to_table_name(path) + + +def proposed(path: tuple[str, ...]) -> str: + """The proposed name (section 5.3 of the design).""" + import json + import re + + digest = hashlib.sha256( + json.dumps(list(path), ensure_ascii=False, separators=(",", ":")).encode() + ).hexdigest() + words = [p for p in path if not re.search(r"[0-9a-f]{64}", p)] + hint = re.sub(r"[^A-Za-z0-9_]+", "_", "_".join(words))[:56] + return f"op-{hint}-{digest}" + + +def check_names() -> None: + """Collisions and lengths of today's and the proposed names.""" + h = "0" * 64 + tail = (h, "v0", "python.function.v1", "rev1", "rdb_v1") + pairs = [ + (("job", "_result", "my-fn", *tail), ("job", "_result", "my_fn", *tail)), + (("job", "_result", "café", *tail), ("job", "_result", "cafè", *tail)), + (("run-1", "add", "pdb_v1"), ("run_1", "add", "pdb_v1")), + (("a", "b__c"), ("a__b", "c")), + (("a_", "b"), ("a", "_b")), + (("1x",), ("t_1x",)), + ] + print("\n| Path A | Path B | Today's one name | Proposed names differ |") + print("|---|---|---|---|") + with tempfile.TemporaryDirectory() as root, fake_pyspiral.install(root): + for a, b in pairs: + assert a != b and today(a) == today(b) + show = lambda p: "/".join(p).replace(h, "<64 hex>") # noqa: E731 + print( + f"| `{show(a)}` | `{show(b)}` | `{today(a).replace(h, '<64 hex>')}` | " + f"{proposed(a) != proposed(b)} |" + ) + database = ConnectorArrowDatabase(MappingConnector("p")) + build(database, 4).run() + print("\n| Stored table | Today's length | Proposed length |") + print("|---|---|---|") + import re + + for name in database._connector.get_table_names(): + # the path itself is not recoverable from today's name: the length is + shown = re.sub(r"[0-9a-f]{64}", "<64 hex>", name) + print(f"| `{shown}` | {len(name)} | at most 124 |") + + +def check_wrong_result() -> None: + """Two functions whose names collide today: one is served the other's results.""" + + def double(x: float) -> float: + return 2 * x + + def triple(x: float) -> float: + return 3 * x + + def run(fn: Any, name: str, db: Any) -> list[float]: + pod = function_pod(output_keys=["out"], function_name=name)(fn).pod + job = PipelineJob(name="j", database=db) + with job: + pod(_source(2, "s", ["x"]), label="n") + job.run() + return job.nodes["n"].as_table().column("out").to_pylist() + + with tempfile.TemporaryDirectory() as root, fake_pyspiral.install(root): + db = ConnectorArrowDatabase(MappingConnector("p")) + first = run(double, "my-fn", db) + second = run(triple, "my_fn", db) + print( + f"\nwrong result: my-fn doubles {first}; my_fn triples [0.0, 1.0] and is " + f"given {second}" + ) + + +if __name__ == "__main__": + check_codec() + check_job() + check_order() + check_cached_source_order() + check_cost() + check_names() + check_wrong_result() diff --git a/docs/dev/specs/itl-1446/stored-columns.md b/docs/dev/specs/itl-1446/stored-columns.md new file mode 100644 index 000000000..141a1a8f4 --- /dev/null +++ b/docs/dev/specs/itl-1446/stored-columns.md @@ -0,0 +1,218 @@ +# ITL-1446: every stored column (generated) + + + +"Refused today because" is what `SpiralDBConnector.unstorable_column_reason` answers; the last +column is what the disk fake does to that column written alone beside the record id. `<64 hex>` +stands for a digest. The record id column is named `__record_id` by every database; callers name +it differently (`_record_hash`, `__data_id`, `__pipeline_entry_id`). + +### cached source: `source/node:<64 hex>/sdb_v1` + +| Column | Arrow type | Nullable | Refused today because | Alone, through the fake | +|---|---|---|---|---| +| `__record_id` | `large_binary` | yes | stored | key column | +| `z_tag` | `large_string` | no | stored | nullability dropped (connector records it) | +| `a_tag` | `int64` | no | stored | nullability dropped (connector records it) | +| `y` | `double` | no | stored | nullability dropped (connector records it) | +| `b` | `double` | no | stored | nullability dropped (connector records it) | +| `_tag_source_id::<64 hex>` | `large_string` | no | stored | nullability dropped (connector records it) | +| `_tag_record_id::<64 hex>` | `large_string` | no | stored | nullability dropped (connector records it) | +| `_source_y` | `large_string` | no | stored | nullability dropped (connector records it) | +| `_source_b` | `large_string` | no | stored | nullability dropped (connector records it) | +| `__data_context` | `large_string` | no | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__data_context' has reserved prefix: column group columns must not start with '__' | + +### function pipeline: `itl1446/compute/<64 hex>/v0/python.function.v1/schema:<64 hex>/pdb_v1` + +| Column | Arrow type | Nullable | Refused today because | Alone, through the fake | +|---|---|---|---|---| +| `__record_id` | `large_binary` | yes | stored | key column | +| `z_tag` | `large_string` | no | stored | nullability dropped (connector records it) | +| `a_tag` | `int64` | no | stored | nullability dropped (connector records it) | +| `_tag_source_id::<64 hex>` | `large_string` | no | stored | nullability dropped (connector records it) | +| `_tag_record_id::<64 hex>` | `large_string` | no | stored | nullability dropped (connector records it) | +| `_source_y` | `large_string` | yes | stored | kept | +| `_source_b` | `large_string` | yes | stored | kept | +| `__data_id` | `large_binary` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__data_id' has reserved prefix: column group columns must not start with '__' | +| `__node_content_hash` | `large_binary` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__node_content_hash' has reserved prefix: column group columns must not start with '__' | +| `__input_data_hash` | `large_binary` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__input_data_hash' has reserved prefix: column group columns must not start with '__' | +| `__output_data_hash` | `large_binary` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__output_data_hash' has reserved prefix: column group columns must not start with '__' | +| `__data_context` | `large_string` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__data_context' has reserved prefix: column group columns must not start with '__' | +| `__computed` | `bool` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__computed' has reserved prefix: column group columns must not start with '__' | +| `__is_ephemeral` | `bool` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__is_ephemeral' has reserved prefix: column group columns must not start with '__' | +| `__pipeline_base_entry_id` | `large_binary` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pipeline_base_entry_id' has reserved prefix: column group columns must not start with '__' | +| `__pipeline_recomputation_index` | `int32` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pipeline_recomputation_index' has reserved prefix: column group columns must not start with '__' | +| `__pipeline_run_id` | `large_string` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pipeline_run_id' has reserved prefix: column group columns must not start with '__' | +| `__recorded_at` | `timestamp[us, tz=UTC]` | no | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__recorded_at' has reserved prefix: column group columns must not start with '__' | + +### function pipeline: `itl1446/logical/<64 hex>/v0/python.function.v1/schema:<64 hex>/pdb_v1` + +| Column | Arrow type | Nullable | Refused today because | Alone, through the fake | +|---|---|---|---|---| +| `__record_id` | `large_binary` | yes | stored | key column | +| `z_tag` | `large_string` | no | stored | nullability dropped (connector records it) | +| `a_tag` | `int64` | no | stored | nullability dropped (connector records it) | +| `_tag_source_id::<64 hex>` | `large_string` | no | stored | nullability dropped (connector records it) | +| `_tag_record_id::<64 hex>` | `large_string` | no | stored | nullability dropped (connector records it) | +| `_source_y` | `large_string` | yes | stored | kept | +| `__data_id` | `large_binary` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__data_id' has reserved prefix: column group columns must not start with '__' | +| `__node_content_hash` | `large_binary` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__node_content_hash' has reserved prefix: column group columns must not start with '__' | +| `__input_data_hash` | `large_binary` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__input_data_hash' has reserved prefix: column group columns must not start with '__' | +| `__output_data_hash` | `large_binary` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__output_data_hash' has reserved prefix: column group columns must not start with '__' | +| `__data_context` | `large_string` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__data_context' has reserved prefix: column group columns must not start with '__' | +| `__computed` | `bool` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__computed' has reserved prefix: column group columns must not start with '__' | +| `__is_ephemeral` | `bool` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__is_ephemeral' has reserved prefix: column group columns must not start with '__' | +| `__pipeline_base_entry_id` | `large_binary` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pipeline_base_entry_id' has reserved prefix: column group columns must not start with '__' | +| `__pipeline_recomputation_index` | `int32` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pipeline_recomputation_index' has reserved prefix: column group columns must not start with '__' | +| `__pipeline_run_id` | `large_string` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pipeline_run_id' has reserved prefix: column group columns must not start with '__' | +| `__recorded_at` | `timestamp[us, tz=UTC]` | no | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__recorded_at' has reserved prefix: column group columns must not start with '__' | + +### function result: `itl1446/_result/compute/<64 hex>/v0/python.function.v1/rev1/rdb_v1` + +| Column | Arrow type | Nullable | Refused today because | Alone, through the fake | +|---|---|---|---|---| +| `__record_id` | `large_binary` | yes | stored | key column | +| `__input_data_hash` | `large_binary` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__input_data_hash' has reserved prefix: column group columns must not start with '__' | +| `__pf_var_function_name` | `large_string` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pf_var_function_name' has reserved prefix: column group columns must not start with '__' | +| `__pf_var_function_version` | `large_string` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pf_var_function_version' has reserved prefix: column group columns must not start with '__' | +| `__pf_var_function_module` | `large_string` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pf_var_function_module' has reserved prefix: column group columns must not start with '__' | +| `__pf_var_function_signature_hash` | `large_binary` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pf_var_function_signature_hash' has reserved prefix: column group columns must not start with '__' | +| `__pf_var_function_content_hash` | `large_binary` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pf_var_function_content_hash' has reserved prefix: column group columns must not start with '__' | +| `__pf_var_git_hash` | `large_string` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pf_var_git_hash' has reserved prefix: column group columns must not start with '__' | +| `__pf_exec_executor_type` | `large_string` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pf_exec_executor_type' has reserved prefix: column group columns must not start with '__' | +| `__pf_exec_executor_info` | `large_list>` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pf_exec_executor_info' has reserved prefix: column group columns must not start with '__' | +| `__pf_exec_python_version` | `large_string` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pf_exec_python_version' has reserved prefix: column group columns must not start with '__' | +| `__pf_exec_extra_info` | `large_list>` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pf_exec_extra_info' has reserved prefix: column group columns must not start with '__' | +| `w_out` | `double` | no | stored | nullability dropped (connector records it) | +| `c_out` | `double` | no | stored | nullability dropped (connector records it) | +| `_source_w_out` | `large_string` | yes | stored | kept | +| `_source_c_out` | `large_string` | yes | stored | kept | +| `__pod_ts` | `timestamp[us, tz=UTC]` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pod_ts' has reserved prefix: column group columns must not start with '__' | +| `__data_context` | `large_string` | no | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__data_context' has reserved prefix: column group columns must not start with '__' | + +### function result: `itl1446/_result/logical/<64 hex>/v0/python.function.v1/rev1/rdb_v1` + +| Column | Arrow type | Nullable | Refused today because | Alone, through the fake | +|---|---|---|---|---| +| `__record_id` | `large_binary` | yes | stored | key column | +| `__input_data_hash` | `large_binary` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__input_data_hash' has reserved prefix: column group columns must not start with '__' | +| `__pf_var_function_name` | `large_string` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pf_var_function_name' has reserved prefix: column group columns must not start with '__' | +| `__pf_var_function_version` | `large_string` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pf_var_function_version' has reserved prefix: column group columns must not start with '__' | +| `__pf_var_function_module` | `large_string` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pf_var_function_module' has reserved prefix: column group columns must not start with '__' | +| `__pf_var_function_signature_hash` | `large_binary` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pf_var_function_signature_hash' has reserved prefix: column group columns must not start with '__' | +| `__pf_var_function_content_hash` | `large_binary` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pf_var_function_content_hash' has reserved prefix: column group columns must not start with '__' | +| `__pf_var_git_hash` | `large_string` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pf_var_git_hash' has reserved prefix: column group columns must not start with '__' | +| `__pf_exec_executor_type` | `large_string` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pf_exec_executor_type' has reserved prefix: column group columns must not start with '__' | +| `__pf_exec_executor_info` | `large_list>` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pf_exec_executor_info' has reserved prefix: column group columns must not start with '__' | +| `__pf_exec_python_version` | `large_string` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pf_exec_python_version' has reserved prefix: column group columns must not start with '__' | +| `__pf_exec_extra_info` | `large_list>` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pf_exec_extra_info' has reserved prefix: column group columns must not start with '__' | +| `at` | `timestamp[us, tz=UTC]` | no | SpiralDB drops a timestamp's time zone, so it reads back as timestamp[us] | type reads timestamp[us]; nullability dropped (connector records it) | +| `path` | `orcapod.path over large_string` | no | SpiralDB drops Arrow field metadata, so a logical (extension) type reads back as its storage type | type reads large_string; nullability dropped (connector records it) | +| `reading` | `Reading@<64 hex> over struct` | no | SpiralDB drops Arrow field metadata, so a logical (extension) type reads back as its storage type | type reads struct; nullability dropped (connector records it) | +| `ids` | `list[orcapod.uuid] over large_list` | no | SpiralDB drops Arrow field metadata, so a logical (extension) type reads back as its storage type | type reads large_list; nullability dropped (connector records it) | +| `counts` | `large_list>` | no | stored | nullability dropped (connector records it) | +| `_source_at` | `large_string` | yes | stored | kept | +| `_source_path` | `large_string` | yes | stored | kept | +| `_source_reading` | `large_string` | yes | stored | kept | +| `_source_ids` | `large_string` | yes | stored | kept | +| `_source_counts` | `large_string` | yes | stored | kept | +| `__pod_ts` | `timestamp[us, tz=UTC]` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__pod_ts' has reserved prefix: column group columns must not start with '__' | +| `__data_context` | `large_string` | no | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__data_context' has reserved prefix: column group columns must not start with '__' | + +### observer (execution_logs): `_observers/compute/<64 hex>/v0/python.function.v1/schema:<64 hex>/execution_logs` + +| Column | Arrow type | Nullable | Refused today because | Alone, through the fake | +|---|---|---|---|---| +| `__record_id` | `large_binary` | yes | stored | key column | +| `_log_id` | `fixed_size_binary[16]` | yes | stored | kept | +| `_log_run_id` | `large_string` | yes | stored | kept | +| `_log_timestamp` | `large_string` | yes | stored | kept | +| `_log_stdout_log` | `large_string` | yes | stored | kept | +| `_log_stderr_log` | `large_string` | yes | stored | kept | +| `_log_python_logs` | `large_string` | yes | stored | kept | +| `_log_traceback` | `large_string` | yes | stored | kept | +| `_log_success` | `bool` | yes | stored | kept | +| `z_tag` | `large_string` | yes | stored | kept | +| `a_tag` | `large_string` | yes | stored | kept | + +### observer (execution_logs): `_observers/logical/<64 hex>/v0/python.function.v1/schema:<64 hex>/execution_logs` + +| Column | Arrow type | Nullable | Refused today because | Alone, through the fake | +|---|---|---|---|---| +| `__record_id` | `large_binary` | yes | stored | key column | +| `_log_id` | `fixed_size_binary[16]` | yes | stored | kept | +| `_log_run_id` | `large_string` | yes | stored | kept | +| `_log_timestamp` | `large_string` | yes | stored | kept | +| `_log_stdout_log` | `large_string` | yes | stored | kept | +| `_log_stderr_log` | `large_string` | yes | stored | kept | +| `_log_python_logs` | `large_string` | yes | stored | kept | +| `_log_traceback` | `large_string` | yes | stored | kept | +| `_log_success` | `bool` | yes | stored | kept | +| `z_tag` | `large_string` | yes | stored | kept | +| `a_tag` | `large_string` | yes | stored | kept | + +### observer (execution_status): `_observers/compute/<64 hex>/v0/python.function.v1/schema:<64 hex>/execution_status` + +| Column | Arrow type | Nullable | Refused today because | Alone, through the fake | +|---|---|---|---|---| +| `__record_id` | `large_binary` | yes | stored | key column | +| `_status_id` | `fixed_size_binary[16]` | yes | stored | kept | +| `_status_run_id` | `large_string` | yes | stored | kept | +| `_status_pipeline_uri` | `large_string` | yes | stored | kept | +| `_status_state` | `large_string` | yes | stored | kept | +| `_status_timestamp` | `large_string` | yes | stored | kept | +| `_status_error_summary` | `large_string` | yes | stored | kept | +| `z_tag` | `large_string` | yes | stored | kept | +| `a_tag` | `large_string` | yes | stored | kept | +| `_tag_source_id::<64 hex>` | `large_string` | yes | stored | kept | +| `_tag_record_id::<64 hex>` | `large_string` | yes | stored | kept | + +### observer (execution_status): `_observers/logical/<64 hex>/v0/python.function.v1/schema:<64 hex>/execution_status` + +| Column | Arrow type | Nullable | Refused today because | Alone, through the fake | +|---|---|---|---|---| +| `__record_id` | `large_binary` | yes | stored | key column | +| `_status_id` | `fixed_size_binary[16]` | yes | stored | kept | +| `_status_run_id` | `large_string` | yes | stored | kept | +| `_status_pipeline_uri` | `large_string` | yes | stored | kept | +| `_status_state` | `large_string` | yes | stored | kept | +| `_status_timestamp` | `large_string` | yes | stored | kept | +| `_status_error_summary` | `large_string` | yes | stored | kept | +| `z_tag` | `large_string` | yes | stored | kept | +| `a_tag` | `large_string` | yes | stored | kept | +| `_tag_source_id::<64 hex>` | `large_string` | yes | stored | kept | +| `_tag_record_id::<64 hex>` | `large_string` | yes | stored | kept | + +### operator cache: `Join/<64 hex>/schema:<64 hex>/odb_v1` + +| Column | Arrow type | Nullable | Refused today because | Alone, through the fake | +|---|---|---|---|---| +| `__record_id` | `large_binary` | yes | stored | key column | +| `z_tag` | `large_string` | no | stored | nullability dropped (connector records it) | +| `a_tag` | `int64` | no | stored | nullability dropped (connector records it) | +| `_tag_source_id::<64 hex>::<64 hex>:0` | `large_string` | no | stored | nullability dropped (connector records it) | +| `_tag_record_id::<64 hex>::<64 hex>:0` | `large_string` | no | stored | nullability dropped (connector records it) | +| `_tag_source_id::<64 hex>::<64 hex>:1` | `large_string` | no | stored | nullability dropped (connector records it) | +| `_tag_record_id::<64 hex>::<64 hex>:1` | `large_string` | no | stored | nullability dropped (connector records it) | +| `y` | `double` | no | stored | nullability dropped (connector records it) | +| `b` | `double` | no | stored | nullability dropped (connector records it) | +| `x` | `double` | no | stored | nullability dropped (connector records it) | +| `e` | `double` | no | stored | nullability dropped (connector records it) | +| `_source_y` | `large_string` | no | stored | nullability dropped (connector records it) | +| `_source_b` | `large_string` | no | stored | nullability dropped (connector records it) | +| `_source_x` | `large_string` | no | stored | nullability dropped (connector records it) | +| `_source_e` | `large_string` | no | stored | nullability dropped (connector records it) | +| `__node_content_hash` | `large_binary` | yes | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__node_content_hash' has reserved prefix: column group columns must not start with '__' | +| `__data_context` | `large_string` | no | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__data_context' has reserved prefix: column group columns must not start with '__' | + +### side-effect log: `itl1446/side_effects/notify/schema:<64 hex>/tdb_v1` + +| Column | Arrow type | Nullable | Refused today because | Alone, through the fake | +|---|---|---|---|---| +| `__record_id` | `large_binary` | yes | stored | key column | +| `record_id_hash` | `large_binary` | yes | stored | kept | +| `pipeline_run_id` | `large_string` | yes | stored | kept | +| `executed_at` | `timestamp[us, tz=UTC]` | yes | SpiralDB drops a timestamp's time zone, so it reads back as timestamp[us] | type reads timestamp[us] | +| `__data_context` | `large_string` | no | SpiralDB reserves the '__' prefix on value columns | raises: Column name '__data_context' has reserved prefix: column group columns must not start with '__' | + +153 columns, 57 refused. diff --git a/docs/dev/specs/itl-1446/stored_columns.py b/docs/dev/specs/itl-1446/stored_columns.py new file mode 100644 index 000000000..c9b275b1a --- /dev/null +++ b/docs/dev/specs/itl-1446/stored_columns.py @@ -0,0 +1,213 @@ +"""ITL-1446: every column of every table a job stores, and what SpiralDB says about it. + +A job over one source (two tags, two data columns) runs a function +pod, an operator node that logs (a ``Join``), a cached source, a side-effect pod that tracks +its completions and a status and a logging observer against an in-memory database. Each +``add_records`` call is recorded by table path, so the columns below are those the library +writes, never a list typed by hand. Each column is then given to +``SpiralDBConnector.unstorable_column_reason``, and written alone (beside the record id) +through pyspiral's disk fake, which raises SpiralDB's own refusals. + +A second function has outputs of logical types, for the columns that depend on the user's +types. Observers are opt-in (``job.run(observer=...)``); their tables are listed because a +job can be given one over the same store. + +Run: ``uv run python docs/dev/specs/itl-1446/stored_columns.py`` (prints Markdown). +""" + +from __future__ import annotations + +import datetime +import re +import tempfile +import uuid +from pathlib import Path +from typing import Any + +import pyarrow as pa + +import orcapod +from orcapod import PipelineJob, function_pod +from orcapod.core.operators import Join +from orcapod.core.sources import ArrowTableSource +from orcapod.core.sources.cached_source import CachedSource +from orcapod.databases import InMemoryArrowDatabase, SpiralDBConnector +from orcapod.pipeline.composite_observer import CompositeObserver +from orcapod.pipeline.logging_observer import LoggingObserver +from orcapod.pipeline.status_observer import StatusObserver +from orcapod.side_effects import SideEffectPod, SideEffectPodConfig +from orcapod.types import CacheMode +from orcapod.utils.arrow_utils import normalize_schema_to_large_types +from tests.test_databases import fake_pyspiral + +SEEN: dict[tuple[str, ...], pa.Table] = {} +_add_records = InMemoryArrowDatabase.add_records + + +def _recording( + self: Any, record_path: Any, records: pa.Table, *a: Any, **k: Any +) -> Any: + given = (records, *a) + key = k.get("record_id_column") or (a[0] if a else None) + if key and key != "__record_id": + records = records.rename_columns( + ["__record_id" if n == key else n for n in records.column_names] + ) + SEEN.setdefault(self.base_path + tuple(record_path), records) + return _add_records(self, record_path, *given, **k) + + +setattr(InMemoryArrowDatabase, "add_records", _recording) # noqa: B010 + + +@orcapod.dataclass +class Reading: + """A structural user class (a struct in storage).""" + + value: float + unit: str + + +@function_pod(output_keys=["w_out", "c_out"]) +def compute(y: float, b: float) -> tuple[float, float]: + """Two outputs.""" + return y + b, y - b + + +@function_pod(output_keys=["at", "path", "reading", "ids", "counts"]) +def logical( + y: float, +) -> tuple[datetime.datetime, Path, Reading, list[uuid.UUID], dict[str, int]]: + """Outputs of the types a user is likely to declare.""" + return ( + datetime.datetime(2026, 1, 1, tzinfo=datetime.timezone.utc), + Path("/a"), + Reading(y, "mV"), + [uuid.UUID(int=1)], + {"a": 1}, + ) + + +def notify(ctx: Any, y: float, b: float) -> None: + """A side effect.""" + + +def _source(name: str, data: list[str]) -> ArrowTableSource: + fields = [ + pa.field("z_tag", pa.large_string(), nullable=False), + pa.field("a_tag", pa.int64(), nullable=False), + *(pa.field(n, pa.float64(), nullable=False) for n in data), + ] + arrays = [ + pa.array(["s1", "s2"], pa.large_string()), + pa.array([1, 2], pa.int64()), + *(pa.array([1.0, 2.0], pa.float64()) for _ in data), + ] + return ArrowTableSource( + pa.Table.from_arrays(arrays, schema=pa.schema(fields)), + tag_columns=["z_tag", "a_tag"], + tag_only_columns=True, + source_id=name, + ) + + +def run_jobs() -> None: + """Run both jobs, recording every table written.""" + database = InMemoryArrowDatabase() + job = PipelineJob(name="itl1446", database=database) + cached = CachedSource(_source("left", ["y", "b"]), cache_database=database) + with job: + right = _source("right", ["x", "e"]) + compute.pod(cached, label="fn") + Join()(cached, right, label="joined") + SideEffectPod(notify, SideEffectPodConfig(track_completion=True))( + cached, label="notify" + ) + logical.pod(_source("plain", ["y"]), label="logical") + job.nodes["joined"].attach_databases( + pipeline_database=database, cache_mode=CacheMode.LOG + ) + observers = database.at("_observers") + observer: Any = CompositeObserver( + StatusObserver(observers), LoggingObserver(observers) + ) + job.run(observer=observer) + + +def _short(text: str) -> str: + return re.sub(r"[0-9a-f]{64}", "<64 hex>", text) + + +def _kind(path: tuple[str, ...]) -> str: + return { + "pdb_v1": "function pipeline", + "rdb_v1": "function result", + "tdb_v1": "side-effect log", + "odb_v1": "operator cache", + "sdb_v1": "cached source", + }.get(path[-1], f"observer ({path[-1]})") + + +def _fake_refusal(records: pa.Table, name: str) -> str: + """What SpiralDB (the fake) raises or silently changes for one column.""" + with tempfile.TemporaryDirectory() as root, fake_pyspiral.install(root): + project = fake_pyspiral.FakeSpiral().project("p") + key = pa.schema([pa.field("__record_id", pa.large_binary())]) + table = project.create_table("default.t", key_schema=key) + rows = records.select(["__record_id"]) + rows = rows.set_column(0, "__record_id", rows.column(0).cast(pa.large_binary())) + if name == "__record_id": + return "key column" + field = records.schema.field(name) + rows = rows.append_column(field, records.column(name)) + try: + table.write(rows) + except ValueError as exc: + return f"raises: {_short(str(exc))}" + back = normalize_schema_to_large_types( + table.schema().to_arrow(), keep_null=True + ).field(name) + want = normalize_schema_to_large_types(rows.schema, keep_null=True).field(name) + changes = [] + if back.type != want.type: + changes.append(f"type reads {back.type}") + if (back.metadata or {}) != (want.metadata or {}): + changes.append("field metadata dropped (connector records it)") + if back.nullable != want.nullable: + changes.append("nullability dropped (connector records it)") + return "; ".join(changes) or "kept" + + +def main() -> None: + """Print one Markdown table per stored table.""" + run_jobs() + with tempfile.TemporaryDirectory() as root, fake_pyspiral.install(root): + connector = SpiralDBConnector("p") + total = refused = 0 + for path, records in sorted(SEEN.items(), key=lambda i: (_kind(i[0]), i[0])): + schema = normalize_schema_to_large_types(records.schema, keep_null=True) + print(f"\n### {_kind(path)}: `{_short('/'.join(path))}`\n") + print( + "| Column | Arrow type | Nullable | Refused today because | Alone, through the fake |" + ) + print("|---|---|---|---|---|") + for field in schema: + reason = connector.unstorable_column_reason( + field.name, field.type, primary_key=field.name == "__record_id" + ) + total += 1 + refused += reason is not None + text = re.sub(r"\s+", " ", _short(str(field.type))) + if isinstance(field.type, pa.BaseExtensionType): + text = f"{field.type.extension_name} over {field.type.storage_type}" + text = re.sub(r"@?[0-9a-f]{64}", "@<64 hex>", text) + print( + f"| `{_short(field.name)}` | `{text}` | " + f"{'yes' if field.nullable else 'no'} | {reason or 'stored'} | " + f"{_fake_refusal(records, field.name)} |" + ) + print(f"\n{total} columns, {refused} refused.") + + +if __name__ == "__main__": + main() From 25f307ab054388fed488c3d838d2b1723af98c14 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 09:55:36 -0800 Subject: [PATCH 2/8] docs(specs): the one-writer lease and what it can guarantee (ITL-1446) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1446-spiral-columns.md | 100 +++++++++++++++++----- docs/dev/specs/itl-1446/lease_model.py | 73 ++++++++++++++++ 2 files changed, 152 insertions(+), 21 deletions(-) create mode 100644 docs/dev/specs/itl-1446/lease_model.py diff --git a/docs/dev/specs/itl-1446-spiral-columns.md b/docs/dev/specs/itl-1446-spiral-columns.md index 51e217bdf..e6f1376c5 100644 --- a/docs/dev/specs/itl-1446-spiral-columns.md +++ b/docs/dev/specs/itl-1446-spiral-columns.md @@ -1,6 +1,10 @@ # ITL-1446: storing a pipeline in SpiralDB Status: **proposal, nothing implemented.** Section 8 lists the decisions the developer makes. +Decided (developer, 2026-11-24): the first version runs one job at a time and **refuses** a second +writer (section 6.3; several writers are a follow-up issue); every table kind goes to SpiralDB +(function pipeline, function result, operator cache, cached source, side-effect log); the live +probes may use the throwaway test project. Covers ITL-1176, ITL-1164, ITL-1100 (names, tables) and ITL-1190 (metadata races). How each statement below is known: @@ -432,26 +436,76 @@ committed record stays (insert when not matched), so a record once read never ch 3. **A failed write leaves no half-written table**: chunks, then header, then rows, and no rollback. *(holds under any race)* 4. **An existing record is not overwritten by a later run.** `skip_existing` is decided by - `read_by_keys` at the latest version just before the write. *(holds except in the window - between that read and the commit)* + `read_by_keys` at the latest version just before the write. *(holds while one writer holds the + store, 6.3)* +5. **A second writer is refused before it computes, delivers or writes anything.** *(holds under + the two conditions of 6.3; not unconditional)* -5. **Not promised**: first-writer-wins inside that window, exactly-once side effects, one - recomputation index per recomputation. +### 6.3 The lease: one writer, the second refused -### 6.3 Options for what is not promised +**What SpiralDB offers** (Read; behaviour to probe): -| Option | Closes the window? | Costs | -|---|---|---| -| **A. One writer per table at a time, documented, and checked after each commit** (recommended first): after a commit, re-read the written ids' `ox_order`; another value means another writer overwrote them, and a warning names the table and the count | no; reports most cases (a later overwrite is missed) | one keyed read per commit (about 1 s) | -| B. The key becomes (`__record_id`, `ox_writer`), one UUIDv7 a handle: every writer's row stays, reads keep one per id by (`ox_order`, `ox_writer`) | no record is ever lost, and `trace` could show every one. The kept one can still change when a writer with an earlier clock commits late | rows grow with races; every read groups by id; `key_table` needs the whole key, so lookups use `where`; the key schema **cannot be changed later** | -| C. A lease in table metadata | no: no compare-and-set, so two can take it | - | -| D. A lock outside SpiralDB | yes | a service to run and configure | -| E. Wait for a conditional write (`spiral-sdk`, ITL-931) | yes | not available | - -A is recommended because one job writing one store at a time is the expected use, and because 1 to -3 hold regardless. B is the only choice that is hard to make later: a store made under A is -rebuilt to move to B. If several processes are expected to write one store soon (Ray workers do -not: the driver writes), choose B now. +| Primitive | Use for a lease | +|---|---| +| conditional write, compare-and-set on rows or metadata | does not exist | +| `last_modified_at`, `asof`, the write-ahead log | shows afterwards that someone wrote: detection only, it stops nothing. (A transaction has a snapshot; nothing read says a commit fails because a key was written since) | +| table metadata | races are documented, so it is not used for the lease | +| `create_table(exist_ok=False)` | may be an atomic test-and-set, if the service makes names unique atomically. Unknown (P11) | +| upsert and `delete_keys` of one row, then a fresh read | **enough**, if a read started after a commit sees it | + +**Claim, then check.** One table `op-lease` per dataset, key `token` (UUIDv7 of one acquisition), +value columns: run id, job name, process id, start time, last renewal. + +1. Commit a row with my token. 2. Read every row, fresh. 3. If mine is the only one, I hold the +store. 4. Otherwise delete my row and refuse, naming the other claim (job, run id, start, +renewal). 5. The holder deletes its own row in a `finally`. + +*Why two cannot hold.* Suppose A and B both hold, with neither's claim removed. A read after its +claim was committed and did not see B, so B's commit came after A's read, and so after A's commit. +B read after its own commit, so B's read sees A, and B does not hold: a contradiction. +[`lease_model.py`](itl-1446/lease_model.py) visits every interleaving of 2, 3 and 4 writers with +crashes at any step: no two holders. It finds two holders in exactly the two variants below. + +**The guarantee is therefore conditional:** + +- **C1: a read started after a commit returned sees that commit, from any client.** P8 tests it. + A test can refute it, not prove it, so it needs SpiralDB's own statement too. With stale reads + the model reaches two holders. If C1 fails but P11 holds, the lease is the creation of one + named table instead; if both fail, what is left is detection (below), and must be called that. +- **C2: nobody clears the claim of a live writer.** SpiralDB has no fencing: a writer that was + cleared and is still alive can commit. It looks its claim up before every commit and stops when + it is gone, but **a window remains** between that check and the commit, and commits already in + flight land. That check is detection, not a guarantee. + +It covers Orcapod versions that take the lease. Another program, or an SDK call by hand, is not +stopped. + +| Case | Behaviour | +|---|---| +| Two starts at the same instant | at most one holds. **Both may be refused** (each sees the other); an acquisition therefore retries up to 3 times with a random wait of 1 to 5 s before refusing. The model shows the both-refused case | +| The claim's commit fails or its reply is lost | nothing has run. The writer tries to delete its token and raises. A claim that lands later is a stale one: others are refused, two never hold | +| A crashed job | its claim stays, and the next run is refused. A crash cannot be told from a pause, a lost network or a suspended laptop from outside, so **no claim ever expires by time**. The holder renews its row's time (about once a minute, at a commit or from a background thread); the refusal shows how old the renewal is, as information | +| Clearing a stale claim | by a person: `database.clear_lease(token)`, with the token from the error. It deletes exactly that row, so clearing twice or late never removes a newer claim. The message says what to check: that the named process no longer runs. Never automatic, not even when the process id looks dead on this machine (containers share hostnames and reuse ids) | +| Separate pipeline and result databases | a run takes the lease of **every** dataset it may write: both databases, a pod's own `result_database` and `pod_cache_database`, a cached operator's, a `CachedSource`'s, an observer's. One per dataset (views by `at()`, and two connectors to one dataset, count once per run), in sorted order. If one is refused, those taken are released | +| Several jobs in one process | a claim belongs to a run, not to a process: one after the other works; a second run while the first one runs (threads, `run_async`, a function that runs a job) is refused if it shares a dataset | +| One database object used by two threads | the second run's acquisition is refused. A bare `add_records` by another thread through the same object during a run uses that run's lease: one object has one queue | +| A forked child | refused: the lease records the process id and a write checks it. Ray workers do not write | +| `job.run()`, `run_async()` | after planning, before anything is computed or delivered, and only if a node is to run. (A source check that stores rows, a `CachedSource`'s, takes the lease for its own flush.) An unchanged rerun with nothing to run writes nothing and takes none | +| `node.run()` | the same acquisition, for the nodes its plan runs | +| Writes outside a run (`add_records` and `flush` by hand, a standalone side effect with a store) | the database itself enforces it: a flush without a lease takes one for that flush. So no write path can forget it | +| **Readers** | never refused, and take nothing: `get_*`, `as_source()`, `head`, `trace`, `load`, `load_only=True`, reads of a held run, `SpiralDBTableSource` over a store table. A reader during a run sees committed batches: results first, then records (promise 2) | +| Reading a `CachedSource` | it fetches live rows and **stores** them, so it is a writer. While another run holds the store it is refused, naming the holder (decision 11). `get_all_records()` on it, which reads the cache only, is a reader | + +**Cost**: one commit and one read to take it, one look-up per commit, one commit to release. About +3 to 5 s a run at the times seen live (P9 measures). Permissions: none beyond writing. + +**Detection besides the lease** (also the fallback if C1 and P11 both fail, and then documented as +best effort only): after a commit, the written ids' `ox_order` are read back and a difference +raises a warning naming the table and count; a later overwrite is missed. + +Follow-up (several writers), not designed here: the key (`__record_id`, writer), which keeps every +writer's row, or a conditional write in `spiral-sdk` (ITL-931). A store made now is rebuilt to +change its key. ### 6.4 Failed writes @@ -482,8 +536,10 @@ store by default (give them an in-memory or Delta store) until they batch. | P5 | `where` equality and `in_` on binary; time against a table of 10^3 to 10^6 rows | 4.3 | | P6 | parallel `set_metadata` of different keys, 50 pairs | 3.3 | | P7 | two clients write one key at once, 50 pairs: errors, winner; the same with a first write of new columns | 6 | -| P8 | read after commit from a second client, both at once and after `create_table(exist_ok=True)` raced by two | 6.2 | +| P8 | (C1, 1,000 times, two clients in two processes) read after commit from a second client, both at once and after `create_table(exist_ok=True)` raced by two | 6.2 | | P9 | time of list, look up, metadata, commit (1, 100, 10,000 rows), and of a rerun | 4 | +| P11 | `create_table(exist_ok=False)` of one name by two clients, 50 times: exactly one succeeds? the name's reuse after `drop_table` | 6.3 | +| P12 | the lease itself: two processes claim at once, 50 times; a process killed while holding; `delete_keys` of one token | 6.3 | | P10 | duplicate key in one write; a write killed midway | 6.4 | ## 8. First working version, in order @@ -497,9 +553,9 @@ today until PR 5. | 2 | `spiral_store` codec: names, types, manifest, as pure functions with no pyspiral | property tests: names (adversarial alphabet, nested), schema round trip over the type matrix, chunk sizes, two manifests | | 3 | Connector: store tables use the codec; `ox_order`; registry and table names; null struct refused when added; `ConnectorArrowDatabase` asks the connector for a table's name | matrix on the fake; column and row order; foreign tables unchanged; a failed first write; two connectors with an injected failure (ITL-1190's interleaving); collisions of 5.2 | | 4 | Lookups (4.3): keyed and `where` reads, the run index, table handles; failed rows restored (6.4) | call counts per run asserted; equivalence with the whole-table path (`test_*_lookup_equivalence`); staleness by a second handle | -| 5 | Job: refusals removed where covered; the post-commit check (option A); docs (names, other readers, cleanup, permissions, single writer) | the pipeline store suites parametrised over the fake: first run, rerun, added rows, changed version, `run()` and `run_async()`, save and load, `load_only`, `clear_cache`, separate result database, `trace`; equal to Delta: sync exactly, async as sets | +| 5 | Job: the lease (6.3) in the database and in `job.run`, `run_async` and `node.run`; refusals removed where covered; the post-commit check; docs (names, other readers, cleanup, permissions, the lease and its two conditions) | the pipeline store suites parametrised over the fake: first run, rerun, added rows, changed version, `run()` and `run_async()`, save and load, `load_only`, `clear_cache`, separate result database, `trace`; equal to Delta: sync exactly, async as sets. Every table kind. The lease: each row of 6.3's table, on the fake, with two handles and an injected crash between any two steps | | 6 | Live suite (the existing `spiral-integration` job): PR 5's job, the type matrix, P7, P8, cost printed; every table dropped | live | -| later | batched `_fetch_joined_records`; null structs; observers; maps if P3 refuses; option B or E | | +| later | batched `_fetch_joined_records`; null structs; observers; maps if P3 refuses; several writers | | ITL-1391 (load a saved connector database) and ITL-1381 (read before flush) are needed for save and load in PR 5; both are in progress. A saved config has no credential today (`to_config`: @@ -511,7 +567,7 @@ save an override that is not a known non-secret key (`server.url`). | # | Decision | Recommended | |---|---|---| | 1 | Where the mapping lives: (a) the store, (b) rename everywhere, (c) mixed | (a) | -| 2 | Concurrent writers: A (one writer, checked) or B (key with a writer id), which cannot be changed later without rebuilding stores | A | +| 2 | *Decided: one writer, a second refused.* To confirm: the lease's conditions C1 and C2 are acceptable, and what ships if P8 refutes C1 (named-table lease if P11 holds, else detection only) | lease; do not ship a "refusal" resting on neither | | 3 | Row order: store `ox_order` so reads follow the written order | yes; otherwise results differ from Delta | | 4 | Table names `op--` with the registry table `op-tables` (ITL-1100's lookup table) | yes | | 5 | Two different manifests in one table stop the job, rather than one winning | stop | @@ -520,6 +576,8 @@ save an override that is not a known non-secret key (`server.url`). | 8 | Observers not on a SpiralDB store at first | yes | | 9 | The 8 KiB failure of today's Arrow metadata entry on tables that are not store tables: fix now (chunks) or leave | fix in PR 2, same chunk code | | 10 | Stay on pyspiral 0.16.33 for this (ITL-931 and ITL-1186 later). The codec, manifest and registry do not depend on the client | yes | +| 11 | A `CachedSource` read while another run holds the store: refuse, or serve live rows without storing | refuse | +| 12 | A crashed job's claim is cleared by a person only, never by age | yes | ## 9. Not verified here diff --git a/docs/dev/specs/itl-1446/lease_model.py b/docs/dev/specs/itl-1446/lease_model.py new file mode 100644 index 000000000..a015d9062 --- /dev/null +++ b/docs/dev/specs/itl-1446/lease_model.py @@ -0,0 +1,73 @@ +"""ITL-1446: exhaustive check of the claim-then-check lease (section 6.3). + +Every interleaving of N writers. A writer: add its claim, read all claims, hold if its own +is the only one, else withdraw; a holder writes twice and releases. A writer may crash after +any step (its claim stays). Two variants show what the rule rests on: ``stale reads`` (the +check may miss the newest claim) and ``cleared while alive`` (a person deletes the claim of +a live holder). + +Run: ``uv run python docs/dev/specs/itl-1446/lease_model.py`` +""" + +from __future__ import annotations + +State = tuple[tuple[str, ...], frozenset[int], frozenset[int]] +HOLDING = ("hold", "wrote") + + +def steps(state: State, stale: bool, clear: bool) -> list[State]: + """Every state one step away: writers' phases, claims stored, claims visible.""" + phases, claims, seen = state + out: list[State] = [] + for i, phase in enumerate(phases): + + def to( + new: str, c: frozenset[int] = claims, s: frozenset[int] = seen, i: int = i + ) -> State: + return ((*phases[:i], new, *phases[i + 1 :]), c, s) + + if phase == "start": + # stored at once; visible at once unless reads may be stale + out.append(to("claimed", claims | {i}, seen if stale else seen | {i})) + elif phase == "claimed": + out.append(to("hold" if not (seen - {i}) else "withdraw")) + elif phase == "withdraw": + out.append(to("refused", claims - {i}, seen - {i})) + elif phase == "hold": + out.append(to("wrote")) + elif phase == "wrote": + out.append(to("done", claims - {i}, seen - {i})) + if phase not in ("start", "refused", "done", "crashed"): + out.append(to("crashed")) + if clear and i in claims: + out.append((phases, claims - {i}, seen - {i})) + if stale and claims - seen: + out.append((phases, claims, claims)) + return out + + +def explore(writers: int, *, stale: bool = False, clear: bool = False) -> None: + """Visit every reachable state and report whether two writers ever hold at once.""" + start: State = (("start",) * writers, frozenset(), frozenset()) + visited, queue, broken, all_refused = {start}, [start], False, False + while queue: + state = queue.pop() + holders = sum(p in HOLDING for p in state[0]) + broken = broken or holders > 1 + all_refused = all_refused or set(state[0]) == {"refused"} + for new in steps(state, stale, clear): + if new not in visited: + visited.add(new) + queue.append(new) + print( + f"{writers} writers, stale reads {stale}, cleared while alive {clear}: " + + f"{len(visited)} states, two holders possible: {broken}, " + + f"all refused possible: {all_refused}" + ) + + +if __name__ == "__main__": + for count in (2, 3, 4): + explore(count) + explore(2, stale=True) + explore(2, clear=True) From c2d5f9fac66b8f02b625a95674eeb7c411544afa Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 10:08:41 -0800 Subject: [PATCH 3/8] docs(specs): table names and the catalog (ITL-1446) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1446-spiral-columns.md | 102 ++++++++++++++++------ 1 file changed, 75 insertions(+), 27 deletions(-) diff --git a/docs/dev/specs/itl-1446-spiral-columns.md b/docs/dev/specs/itl-1446-spiral-columns.md index e6f1376c5..3f9d58c06 100644 --- a/docs/dev/specs/itl-1446-spiral-columns.md +++ b/docs/dev/specs/itl-1446-spiral-columns.md @@ -183,7 +183,7 @@ path, and the Arrow schema in storage form (logical types as `ARROW:extension:*` after the first time (the manifest of a table id does not change). - To probe: whether parallel `set_metadata` calls on **different** keys keep both. pyspiral says entries are upserted and parallel calls race "to set a value". If the server replaces the - whole map, the manifest goes to a table of its own (the registry of section 5.4), where a write + whole map, the manifest goes to a table of its own (the catalog of section 5.4), where a write is an upsert of one row. Limits: 1,024 entries a table, 8 KiB a pair, 255 characters a key. A key here is at most 90 @@ -369,30 +369,78 @@ stays below it either way. ### 5.3 The mapping -`op--`: `` is the 64-hex SHA-256 of the compact JSON list of the full path -(base path included), and `` is the components that hold no 64-hex hash, joined by `_`, -sanitised as today and cut to 56 characters. At most 124 characters, always `[a-z]`-initial, only -`[a-zA-Z0-9_-]`. Two paths share a name only if SHA-256 collides, and the manifest's recorded path -is compared on first use of a table, so even then (or if SpiralDB folds case) the store refuses -rather than mixes. A bare digest in a name carries no label, per the hash label rule. +Decided (developer, 2026-11-24): a short readable part plus a digest of the full, unsanitised +record path, independent of any lookup; a fixed-name catalog table; nothing is ever parsed out of +a name. -A reversible escape (no digest) was considered: it cannot fit. Two 64-hex hashes are already 128 -characters. +`op--`: -### 5.4 Finding tables by path: the registry +- `` is the 64-hex SHA-256 of the compact JSON list of the full path as text: the + database's base path and the record path, each component exact. JSON quoting keeps `["a","b"]` + and `["a/b"]` apart. +- `` is for people: the components without a 64-hex hash, joined by `_`, sanitised as + today, cut to 56 characters. -`list_table_paths(prefix)` must give real paths, and a digest cannot be reversed. Reading every -table's manifest costs a call a table. Proposed: the developer's lookup table (ITL-1100), one -table `op-tables` with key `table_name` and value columns `path` (JSON) and `format`: +At most 124 characters of `[a-zA-Z0-9_-]`, starting with `o`. The developer gives SpiralDB's limit +as 255; pyspiral's own type says 128 (Read). Names fit both, and P2 settles which the server +applies. A reversible escape instead of a digest cannot fit 128: two path hashes are already 128. -- a row is upserted **before** its table is created, so no store table is missing from it; -- a row's content is a function of its key, so two writers write the same row: the one kind of - upsert that really is harmless; -- listing is one scan of the registry, joined with the project's table list (a row whose table - was never created or was dropped is left out). +The digest is a new hash site of class "in a name" (bare hex, no label) and gets its row in the +hash site inventory. No existing hash or record path moves. -The prefix `op-` is the store's. A store table name that exists without a manifest and with value -columns is refused. Cleanup: the registry names every store table of a dataset. +**Several databases over one connector.** `.at()` views and separate `ConnectorArrowDatabase` +objects use the full path, so `db.at("a")` writing `("b",)` and `db` writing `("a", "b")` are one +table, as on Delta; they share one catalog. Two datasets are two stores. + +### 5.4 The catalog, `orcapod_catalog_v1` + +| Column | Type | Content | +|---|---|---| +| `physical_name` | text, **key** | the table's name in SpiralDB | +| `path` | text | the exact path, the JSON text the digest is of | +| `kind` | text | `function_pipeline`, `function_result`, `side_effect_log`, `operator_cache`, `cached_source`, or `other`; from the path's last component (its layout), never from the name | +| `store_format` | int32 | the manifest format the table was created with | + +No column starts with `__` or holds `.`. The catalog is written with these fixed types, without +the codec or a manifest, and its schema is checked when opened. A row is a function of its key: +there is no created-at column, so two writers write the same row. + +- **Order.** The catalog row is committed, then the table is created, then its manifest, then + rows. So every store table is in the catalog, and a crash leaves at most a row with no table, + which a listing leaves out. +- **Use.** A table's name is computed, so a read or write needs no lookup to find it. The catalog + is for `list_table_paths`, cleanup, people, and two checks: a row for the name with **another + path** is a digest collision and is refused; a table that exists **without a row** is not ours, + and is neither read nor written (an error naming it, never "no such table", which would + recompute over it). +- **Deletion.** Under the lease: drop the table by id, then delete its row. A crash between + leaves a row with no table. A table dropped by hand reads as absent and is recreated. Offered + as `database.delete_table(path)`; nothing is deleted automatically. +- **A lost catalog.** Every table's manifest also holds its path, so it can be rebuilt: + `rebuild_catalog()`, run by a person, reads each table's metadata once, takes those with a + manifest whose path gives exactly the table's name, and writes the rows. Until then the tables + are refused, not recomputed. When the catalog does not exist, opening the store for writing + looks once at the metadata of the tables there; if any has a manifest it refuses and names + `rebuild_catalog()`, else it creates the catalog. A catalog that lost only some rows shows as + "exists without a row" on use. `list_table_paths` cannot see those tables until the rebuild, so + stale-layout accounting may miss them: a stated limit. +- **Schema version.** In the name. A changed catalog is `orcapod_catalog_v2`, with its own + migration decision; a store that holds a catalog of another version is refused. The manifest and + the lease (`orcapod_lease_v1`, section 6.3) are versioned apart. +- **Cost.** One read a handle at the start of a run (about 300 bytes a table; kept until + `refresh_table`), none per row, one commit per **new** table (five for the prototype's job, first + run only), and nothing on a rerun. `list_table_paths` is this read plus one listing. +- **Scope: dataset or project** (under discussion with the developer): + +| | per dataset | per project | +|---|---|---| +| A dataset moved, copied or dropped takes its catalog along | yes | no: rows dangle | +| Permissions | the dataset's own | write access where the catalog lives, for every store | +| All stores of a project listed at once | no | yes | +| Key | `physical_name` | dataset and name | +| Lease | one per dataset, beside it | the lease stays per dataset | + +The rest of this design is the same either way; per dataset is the smaller one. ## 6. Concurrent writers and failed writes @@ -453,7 +501,7 @@ committed record stays (insert when not matched), so a record once read never ch | `create_table(exist_ok=False)` | may be an atomic test-and-set, if the service makes names unique atomically. Unknown (P11) | | upsert and `delete_keys` of one row, then a fresh read | **enough**, if a read started after a commit sees it | -**Claim, then check.** One table `op-lease` per dataset, key `token` (UUIDv7 of one acquisition), +**Claim, then check.** One table `orcapod_lease_v1` per dataset, key `token` (UUIDv7 of one acquisition), value columns: run id, job name, process id, start time, last renewal. 1. Commit a row with my token. 2. Read every row, fresh. 3. If mine is the only one, I hold the @@ -514,7 +562,7 @@ change its key. | the write raises, nothing committed | `ConnectorArrowDatabase` **drops** the rows from its queue (`take_ready`, never restored) | restore them (`PendingCommits.restore`) and withdraw their dependents, as Delta does; a later flush retries. A refusal of the rows themselves still drops them | | the commit is **ambiguous** (committed, but the reply is lost) | as above | results: a retry upserts the same UUIDs, harmless. Pipeline records: a retry is skipped by `skip_existing`. The run still reports failure | | the result table commits, the pipeline table fails | results without records | the next run finds them by input hash, computes nothing, writes the records | -| a manifest or registry row without rows | - | inert | +| a manifest or catalog row without rows | - | inert | | a side effect was delivered and its log row failed | the row is dropped: delivered again next run | the row stays queued; a crash still delivers again (at least once, as on Delta) | | interrupted between two tables' commits | - | promise 2; the job reruns | @@ -530,7 +578,7 @@ store by default (give them an in-memory or Delta store) until they batch. | # | Question | Decides | |---|---|---| | P1 | names: each ASCII character and class of 3.1, `ox_` names, 1 to 1,024 characters, case pairs, NFC/NFD pairs; nested field names | 3.1 | -| P2 | table name of 128 and 129 characters, case pair, `-` | 5.3 | +| P2 | table name of 128, 129, 255 and 256 characters, case pair, `-` | 5.3 | | P3 | the type matrix, physical forms; float bits; `null`; null struct; struct field order | 3.2 | | P4 | `key_table` with `binary` and `large_binary`, unsorted, repeated, absent ids; 1 to 100,000 ids: time | 4.3 | | P5 | `where` equality and `in_` on binary; time against a table of 10^3 to 10^6 rows | 4.3 | @@ -551,7 +599,7 @@ today until PR 5. |---|---|---| | 1 | Fake as strict as the client (3.4); the connector refuses what it must (`fixed_size_binary`, `duration`, `null`, table names); `database-types.md` regenerated | each rule, with the native library's text; matrix | | 2 | `spiral_store` codec: names, types, manifest, as pure functions with no pyspiral | property tests: names (adversarial alphabet, nested), schema round trip over the type matrix, chunk sizes, two manifests | -| 3 | Connector: store tables use the codec; `ox_order`; registry and table names; null struct refused when added; `ConnectorArrowDatabase` asks the connector for a table's name | matrix on the fake; column and row order; foreign tables unchanged; a failed first write; two connectors with an injected failure (ITL-1190's interleaving); collisions of 5.2 | +| 3 | Connector: store tables use the codec; `ox_order`; table names and the catalog; null struct refused when added; `ConnectorArrowDatabase` asks the connector for a table's name | matrix on the fake; column and row order; foreign tables unchanged; a failed first write; two connectors with an injected failure (ITL-1190's interleaving); collisions of 5.2; catalog: crash between each step, lost, partly lost, another version, `.at()` views, a forced digest collision | | 4 | Lookups (4.3): keyed and `where` reads, the run index, table handles; failed rows restored (6.4) | call counts per run asserted; equivalence with the whole-table path (`test_*_lookup_equivalence`); staleness by a second handle | | 5 | Job: the lease (6.3) in the database and in `job.run`, `run_async` and `node.run`; refusals removed where covered; the post-commit check; docs (names, other readers, cleanup, permissions, the lease and its two conditions) | the pipeline store suites parametrised over the fake: first run, rerun, added rows, changed version, `run()` and `run_async()`, save and load, `load_only`, `clear_cache`, separate result database, `trace`; equal to Delta: sync exactly, async as sets. Every table kind. The lease: each row of 6.3's table, on the fake, with two handles and an injected crash between any two steps | | 6 | Live suite (the existing `spiral-integration` job): PR 5's job, the type matrix, P7, P8, cost printed; every table dropped | live | @@ -569,13 +617,13 @@ save an override that is not a known non-secret key (`server.url`). | 1 | Where the mapping lives: (a) the store, (b) rename everywhere, (c) mixed | (a) | | 2 | *Decided: one writer, a second refused.* To confirm: the lease's conditions C1 and C2 are acceptable, and what ships if P8 refutes C1 (named-table lease if P11 holds, else detection only) | lease; do not ship a "refusal" resting on neither | | 3 | Row order: store `ox_order` so reads follow the written order | yes; otherwise results differ from Delta | -| 4 | Table names `op--` with the registry table `op-tables` (ITL-1100's lookup table) | yes | +| 4 | *Decided: digest names and the catalog.* Open: its scope, dataset or project (5.4) | dataset | | 5 | Two different manifests in one table stop the job, rather than one winning | stop | | 6 | Use the collision-free path mapping for SQLite and PostgreSQL too (their existing tables would no longer be found) | yes, in its own PR before 0.4.0, while nobody has such a store | | 7 | Null structs refused in the first version (a `T \| None` user-class output holding a null) | yes | | 8 | Observers not on a SpiralDB store at first | yes | | 9 | The 8 KiB failure of today's Arrow metadata entry on tables that are not store tables: fix now (chunks) or leave | fix in PR 2, same chunk code | -| 10 | Stay on pyspiral 0.16.33 for this (ITL-931 and ITL-1186 later). The codec, manifest and registry do not depend on the client | yes | +| 10 | Stay on pyspiral 0.16.33 for this (ITL-931 and ITL-1186 later). The codec, manifest and catalog do not depend on the client | yes | | 11 | A `CachedSource` read while another run holds the store: refuse, or serve live rows without storing | refuse | | 12 | A crashed job's claim is cleared by a person only, never by age | yes | @@ -585,7 +633,7 @@ save an override that is not a known non-secret key (`server.url`). limits. - The prototype maps names and top-level types only, and its job has number and text columns and UTC timestamps; it runs no logical type. It does not implement the manifest set, `ox_order`, the - registry, the proposed table names or the lookups. + catalog, the proposed table names or the lookups. - The async path, save and load, `load_only` and `trace` were not run through the prototype. - The fake's and the matrix's behaviour for logical types nested at depth was read, not run through the prototype. From de690e5448f7084aedc9ff2abae94c117e5655ba Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 10:09:47 -0800 Subject: [PATCH 4/8] docs(specs): one store per dataset, permissions and the lease's scope (ITL-1446) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1446-spiral-columns.md | 33 ++++++++++++++++------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/docs/dev/specs/itl-1446-spiral-columns.md b/docs/dev/specs/itl-1446-spiral-columns.md index 3f9d58c06..3fa40bdf6 100644 --- a/docs/dev/specs/itl-1446-spiral-columns.md +++ b/docs/dev/specs/itl-1446-spiral-columns.md @@ -430,17 +430,28 @@ there is no created-at column, so two writers write the same row. - **Cost.** One read a handle at the start of a run (about 300 bytes a table; kept until `refresh_table`), none per row, one commit per **new** table (five for the prototype's job, first run only), and nothing on a rerun. `list_table_paths` is this read plus one listing. -- **Scope: dataset or project** (under discussion with the developer): +- **Scope: one catalog per dataset** (decided, developer, 2026-11-24). A dataset is one + self-contained Orcapod store: its tables, its catalog and its lease. The database sees nothing + of other datasets, and a path names a table within its dataset only. -| | per dataset | per project | +### 5.5 What a dataset is, and who may write + +| Question | Answer | Source | |---|---|---| -| A dataset moved, copied or dropped takes its catalog along | yes | no: rows dangle | -| Permissions | the dataset's own | write access where the catalog lives, for every store | -| All stores of a project listed at once | no | yes | -| Key | `physical_name` | dataset and name | -| Lease | one per dataset, beside it | the lease stays per dataset | +| Must a dataset be created first? | **Unknown.** The client has no call that creates one: `create_table("dataset.table")` takes the name, and tables are listed, filtered and moved by it, so it looks implicit. The public documentation does not mention datasets | pyspiral 0.16.33 source; documentation; P13 | +| Dataset name | at most 128 characters, `[a-zA-Z_][a-zA-Z0-9_-]+`, so at least two | pyspiral `api/types.py` | +| Level of permissions | **the project**: "A grant gives one role on one Project to a principal." Roles `viewer`, `editor`, `admin`. Dataset or table grants: not in the documentation, and the client's grant call is on the project only | docs.spiraldb.com, Platform > Access; pyspiral `Projects.grant_role` | +| Roles the store needs | a reader `viewer`, a writer `editor` (create, write, drop): **unknown in detail**. The live test job runs as `editor` | `test_spiraldb_connector_integration.py`; P13 | + +So separate datasets do **not** separate permissions: anyone who may write one store of a project +may write all of them, its lease and catalog included. Different writers need different projects. -The rest of this design is the same either way; per dataset is the smaller one. +The current documentation describes the newer platform (catalog, branches, commits, `spiral-sdk`), +not pyspiral's `dataset.table` model, so it may not apply to this client unchanged. It states +conflict checks that pyspiral does not expose: a commit compares names and versions and fails +with a conflict, and one commit may change several tables of a project. With that client +(ITL-931) the lease could be a conditional publish, and results and records one commit. It states +no read-after-commit guarantee, so C1 is not documented. ## 6. Concurrent writers and failed writes @@ -534,7 +545,8 @@ stopped. | The claim's commit fails or its reply is lost | nothing has run. The writer tries to delete its token and raises. A claim that lands later is a stale one: others are refused, two never hold | | A crashed job | its claim stays, and the next run is refused. A crash cannot be told from a pause, a lost network or a suspended laptop from outside, so **no claim ever expires by time**. The holder renews its row's time (about once a minute, at a commit or from a background thread); the refusal shows how old the renewal is, as information | | Clearing a stale claim | by a person: `database.clear_lease(token)`, with the token from the error. It deletes exactly that row, so clearing twice or late never removes a newer claim. The message says what to check: that the named process no longer runs. Never automatic, not even when the process id looks dead on this machine (containers share hostnames and reuse ids) | -| Separate pipeline and result databases | a run takes the lease of **every** dataset it may write: both databases, a pod's own `result_database` and `pod_cache_database`, a cached operator's, a `CachedSource`'s, an observer's. One per dataset (views by `at()`, and two connectors to one dataset, count once per run), in sorted order. If one is refused, those taken are released | +| Separate pipeline and result databases | a run takes the lease of **every** dataset it may write: both databases, a pod's own `result_database` and `pod_cache_database`, a cached operator's, a `CachedSource`'s, an observer's. The refusal is per dataset. Two datasets: the run holds both leases, taken in sorted order; if one is refused the other is released, and another job that shares **either** dataset is refused. A job sharing only the result dataset is refused too, although it would write other tables. Two jobs in disjoint datasets run together | +| One dataset, two connectors or database objects | in one run (its pipeline and result databases, or `at()` views): one lease, recognised by server, project and dataset, not by object. In two runs: the second is refused, also in one process. A connector opened under another server address for the same service is not recognised as the same: it is then refused by its own run's claim, which is safe | | Several jobs in one process | a claim belongs to a run, not to a process: one after the other works; a second run while the first one runs (threads, `run_async`, a function that runs a job) is refused if it shares a dataset | | One database object used by two threads | the second run's acquisition is refused. A bare `add_records` by another thread through the same object during a run uses that run's lease: one object has one queue | | A forked child | refused: the lease records the process id and a write checks it. Ray workers do not write | @@ -588,6 +600,7 @@ store by default (give them an in-memory or Delta store) until they batch. | P9 | time of list, look up, metadata, commit (1, 100, 10,000 rows), and of a rerun | 4 | | P11 | `create_table(exist_ok=False)` of one name by two clients, 50 times: exactly one succeeds? the name's reuse after `drop_table` | 6.3 | | P12 | the lease itself: two processes claim at once, 50 times; a process killed while holding; `delete_keys` of one token | 6.3 | +| P13 | `create_table` in a dataset that does not exist; what `viewer` and `editor` may do to tables, rows and metadata | 5.5 | | P10 | duplicate key in one write; a write killed midway | 6.4 | ## 8. First working version, in order @@ -617,7 +630,7 @@ save an override that is not a known non-secret key (`server.url`). | 1 | Where the mapping lives: (a) the store, (b) rename everywhere, (c) mixed | (a) | | 2 | *Decided: one writer, a second refused.* To confirm: the lease's conditions C1 and C2 are acceptable, and what ships if P8 refutes C1 (named-table lease if P11 holds, else detection only) | lease; do not ship a "refusal" resting on neither | | 3 | Row order: store `ox_order` so reads follow the written order | yes; otherwise results differ from Delta | -| 4 | *Decided: digest names and the catalog.* Open: its scope, dataset or project (5.4) | dataset | +| 4 | *Decided: digest names, and one catalog per dataset.* To note: permissions are per project (5.5) | - | | 5 | Two different manifests in one table stop the job, rather than one winning | stop | | 6 | Use the collision-free path mapping for SQLite and PostgreSQL too (their existing tables would no longer be found) | yes, in its own PR before 0.4.0, while nobody has such a store | | 7 | Null structs refused in the first version (a `T \| None` user-class output holding a null) | yes | From c813a6631c0f01927f0e638dae6294c1f6e391d5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 10:20:56 -0800 Subject: [PATCH 5/8] docs(specs): table names for every connector or SpiralDB only (ITL-1446) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1446-spiral-columns.md | 24 ++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/docs/dev/specs/itl-1446-spiral-columns.md b/docs/dev/specs/itl-1446-spiral-columns.md index 3fa40bdf6..8068d8637 100644 --- a/docs/dev/specs/itl-1446-spiral-columns.md +++ b/docs/dev/specs/itl-1446-spiral-columns.md @@ -453,6 +453,28 @@ with a conflict, and one commit may change several tables of a project. With tha (ITL-931) the lease could be a conditional publish, and results and records one commit. It states no read-after-commit guarantee, so C1 is not documented. +### 5.6 Every connector, or SpiralDB only + +`_path_to_table_name` is shared by all three connectors, so the collisions of 5.2 exist on SQLite +and PostgreSQL too, and PostgreSQL refuses names over 63 bytes (ITL-1162, CA3): a join's operator +cache, 2 hashes in its path, cannot have a name there. + +| | SpiralDB connector only | `ConnectorArrowDatabase`, every connector | +|---|---|---| +| Fixes collisions | SpiralDB | all three | +| PostgreSQL table names | no | yes: 63 bytes hold `op--`. 128 bits, and the catalog refuses a collision | +| PostgreSQL operator caches | no | **not by this alone**: its column names are over 63 bytes too (a join's system tags, 148), which is ITL-1166 | +| Needs | a name hook on one connector | the hook, a length limit per connector (SpiralDB 128, PostgreSQL 63 bytes, SQLite none known), a catalog per dataset / schema / file, all in the database layer | +| Catalog write | the order of 5.4 | the same, or one transaction with `CREATE TABLE` on SQL connectors | +| Tests | SpiralDB fake | also SQLite, PostgreSQL (its CI job), every existing name and listing test of the three | +| Existing tables | none: no store table could be written | SQLite and PostgreSQL tables of `ConnectorArrowDatabase` would no longer be found: they have no catalog row. Nobody has any (greenfield, before 0.4.0), so no migration: rebuild. Tables read by a SQL **source** are not affected | + +**Recommended:** the code goes in `ConnectorArrowDatabase`, switched on per connector, and the +first version switches on SpiralDB only. The path digest, the catalog's columns and the crash +order are connector-neutral as designed, so switching on SQLite and PostgreSQL is a later PR that +renames no SpiralDB table. That PR should land before 0.4.0, while nobody has such a store. The +first version does not wait for it. + ## 6. Concurrent writers and failed writes SpiralDB upserts by key. The client retries a transaction "after conflicts" (3 times by default) @@ -632,7 +654,7 @@ save an override that is not a known non-secret key (`server.url`). | 3 | Row order: store `ox_order` so reads follow the written order | yes; otherwise results differ from Delta | | 4 | *Decided: digest names, and one catalog per dataset.* To note: permissions are per project (5.5) | - | | 5 | Two different manifests in one table stop the job, rather than one winning | stop | -| 6 | Use the collision-free path mapping for SQLite and PostgreSQL too (their existing tables would no longer be found) | yes, in its own PR before 0.4.0, while nobody has such a store | +| 6 | Digest names and the catalog for SQLite and PostgreSQL too (5.6): existing tables there are rebuilt, nobody has any | yes, a later PR before 0.4.0; the first version does not wait | | 7 | Null structs refused in the first version (a `T \| None` user-class output holding a null) | yes | | 8 | Observers not on a SpiralDB store at first | yes | | 9 | The 8 KiB failure of today's Arrow metadata entry on tables that are not store tables: fix now (chunks) or leave | fix in PR 2, same chunk code | From 9f11805560f991376bd7d66dcbaa193ea2763abd Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 10:43:53 -0800 Subject: [PATCH 6/8] docs(specs): a SpiralDB store keeps no row order (ITL-1446) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1446-spiral-columns.md | 79 +++++++++++++-------- docs/dev/specs/itl-1446/prototype-output.md | 12 ++++ docs/dev/specs/itl-1446/prototype.py | 47 +++++++++++- 3 files changed, 106 insertions(+), 32 deletions(-) diff --git a/docs/dev/specs/itl-1446-spiral-columns.md b/docs/dev/specs/itl-1446-spiral-columns.md index 8068d8637..e548ac329 100644 --- a/docs/dev/specs/itl-1446-spiral-columns.md +++ b/docs/dev/specs/itl-1446-spiral-columns.md @@ -25,13 +25,13 @@ How each statement below is known: on the fake with rows, schemas, system tags and content hashes equal to the in-memory store's, and an unchanged rerun calls nothing (Measured, [`prototype.py`](itl-1446/prototype.py)). - Column names are the small part. Reading the code and running the prototype found five things - the issue does not list, each of which must be in the first version: + the issue does not list. F3 is accepted; the others must be in the first version: | # | Finding | How known | Section | |---|---|---|---| | F1 | **Table names are too long.** pyspiral types a table name as at most 128 characters of `[a-zA-Z0-9_-]`. A function pipeline table's name is 181 characters today. `unstorable_table_name_reason` says SpiralDB holds every name | Read, Measured | 5 | | F2 | **Table names collide, and a collision serves wrong results.** `function_name="my-fn"` and `"my_fn"` share one result table; the second function is given the first one's values | Measured | 5 | -| F3 | **Row order is lost.** SpiralDB returns rows in key order, and the key is a hash. `Batch(2)` over a `CachedSource` gives other batches than on Delta and in memory | Measured | 3.6 | +| F3 | **Row order is not kept.** SpiralDB returns rows in key order, and the key is a hash, so `Batch(2)` over a `CachedSource` gives other batches than on Delta. *Accepted (developer): a store is a set of rows* | Measured | 3.6 | | F4 | **Result record ids are not content derived.** A function result's id is a random UUIDv7; a pipeline record's id leaves out the result it names. "Same id, same content" holds only for operator caches and cached sources, and not bit for bit | Read | 6 | | F5 | **The fake accepts what the client refuses**: `fixed_size_binary` and `duration` (pyspiral's own `Schema.from_arrow` raises) and probably a `null` column (the native library has an error for it). The connector says it stores all three | Measured (client, offline) and Read | 3.4 | @@ -64,7 +64,7 @@ A second point the list shows: the reason given is the first one found. `__recor | What changes | a SpiralDB store encodes on write and decodes on read | `SYSTEM_COLUMN_PREFIX` becomes a prefix SpiralDB accepts, for every store | (b) for Orcapod's own columns, (a) for user columns | | Hashes, paths, golden | **none** | `__input_data_hash` and `__pipeline_recomputation_index` are column names in hashed preimages (`_build_record_id_preimage`), and `__node_content_hash` is in the operator cache's hashed row: every pipeline entry id, base entry id, side-effect id and operator record id moves | as (b) | | Layouts | none | all five layout versions and the Python function type's revision | as (b) | -| Time zones, logical types, dotted names, table names, row order | handled by the same mechanism | **not handled**; (a) is needed anyway | (a) is needed anyway | +| Time zones, logical types, dotted names, table names | handled by the same mechanism | **not handled**; (a) is needed anyway | (a) is needed anyway | | Existing stores | untouched | Delta stores of 0.4.0rc1 are no longer read | as (b) | | What other SpiralDB readers see | `ox___data_context` for `__data_context` | a plain name | a plain name | @@ -113,8 +113,6 @@ pyspiral's expressions (`Expr.__getitem__`). - **Key column.** `__record_id` is stored as it is: SpiralDB accepts `__` on a key column. `E` never yields a name that starts with `__`, so a value column cannot collide with it. -- **Store-only columns.** A name that starts with `ox_` and is not any `E(c)` is free for the - store. `ox_order` (3.6) is such a name: `order` is plain, and `E("ox_order")` is `ox_ox_order`. - **Unicode.** Characters are kept as code points, with no normalisation. To probe: whether SpiralDB normalises (`é` as one or two code points) or folds case. If it does, two names that it merges are refused before writing; the rule is written from the probe, not guessed. @@ -206,7 +204,7 @@ refuse these, so the suite fails where the service would. store refuses to write into a table without a manifest that has value columns. - **Another SpiralDB reader of a store table** (CLI, Polars, DuckDB, spiral-sdk) sees `ox___pod_ts` as a timestamp without a zone (UTC instants), a logical type as its storage, a `File` or user - class as its struct with sorted fields, and `ox_order`. Plain user columns, tags and + class as its struct with sorted fields. Plain user columns, tags and `_source_*` are readable under their own names. Documented, with the encoding version. - **A `SpiralDBTableSource` over a store table** must not silently show encoded names: it reads the manifest, so it shows Orcapod's names, and refuses a manifest version it does not know. @@ -223,23 +221,40 @@ refuse these, so the suite fails where the service would. **Column order.** SpiralDB stores value columns sorted by name. A read puts them in the manifest's order, so a table reads back in the order of its first write, as on Delta. -**Row order.** SpiralDB returns key order. The key is a hash, so stored rows come back shuffled -(Measured): +**Row order: none is kept, and none is promised** (decided, developer, 2026-11-24). A database is a +**set of rows** unless one says otherwise. There is no order column and nothing hidden; stores are +compared as sets of rows. A read of an unchanged table gives SpiralDB's key order, which is a hash +order and says nothing about when a row was written. -| Store | `CachedSource` over k = 0..5 reads | `Batch(2)` gives y | -|---|---|---| -| in memory, Delta | 0, 1, 2, 3, 4, 5 | [0, 1], [2, 3], [4, 5] | -| SpiralDB (prototype) | 4, 5, 1, 2, 3, 0 | [4, 5], [1, 2], [3, 0] | - -This is a difference in computed results, not presentation. The raw pipeline table also comes -back in another order; `as_source()` of a function node happened to agree (6 and 60 rows), which -is not a guarantee. +Within a run nothing depends on it: a node's rows are in the run's own order, stored rows +included (ITL-1441), which the run takes from its inputs. So a job gives equal rows in the same +order on SpiralDB and Delta, unless one of its **inputs** is read from a store. There, what can +differ from Delta (Measured on the fake and on Delta): -Design: a store-only column `ox_order` (`int64`). A handle gives a batch consecutive values from -`max(last + 1, time.time_ns())`, in row order. A read sorts by (`ox_order`, `__record_id`) and -drops the column. One writer: exactly the order written. Several writers: deterministic for a -given store content; interleaved by their clocks, as concurrent Delta commits are by commit. It -is in no hash, never leaves the store, and costs 8 bytes a row and a sort per read. +| Where | SpiralDB (prototype) | Delta | +|---|---|---| +| `CachedSource` over k = 0..5 | 4, 5, 1, 2, 3, 0 | 0, 1, 2, 3, 4, 5 | +| `Batch(2)` over it: y | [4, 5], [1, 2], [3, 0] | [0, 1], [2, 3], [4, 5] | +| `as_source(tags_as_data=...)` over a logged `Join`: **positional** record ids of k = 0..3 | 3, 0, 2, 1; after 4 rows are added 5, 1, 4, 2 | 0, 1, 2, 3; after 4 rows are added 4, 5, 6, 7 | +| the same with `record_id_columns=["k"]` | `{"k":0}` ... in every case | the same | + +All accepted. The consequences, to be documented: + +- **An order-sensitive step over rows read from a store** (`Batch`; a `GroupBy` whose members tie + on every tag and record id) may group differently, so its values, folded record ids and what is + recomputed downstream differ. This covers a `CachedSource`, a `REPLAY` operator, and any + `as_source()`. +- **Adding rows** puts them anywhere in key order, so such a step's earlier groups change. On + Delta too: the third row shows that Delta's order is not append order either. +- **Positional record ids over a stored node** move when rows are added, and everything + downstream is computed again. Give `record_id_columns`. +- `head()`, previews and `as_table()` of stored rows show key order; `sort_by_tags` for a stable + one. +- Two results of one input with an equal `__pod_ts` (to the microsecond): which one a lookup + takes is unspecified, as it is today. + +Compare-as-sets is for what is read **from a store**. A run's own rows are still compared exactly +for sync and as sets for async. ### 3.7 Does anything move? @@ -312,7 +327,7 @@ That makes each lookup small, but still one round trip a row. At 0.7 to 1.7 s a run**, as `DeltaTableDatabase` does with its `KeyIndex`: - On the first lookup in a table, read only the lookup columns of all rows with a pinned `asof` - (`__record_id`, `__input_data_hash`, `__data_context`, `__pod_ts`, `ox_order` for results; + (`__record_id`, `__input_data_hash`, `__data_context`, `__pod_ts` for results; `__record_id`, `__pipeline_base_entry_id`, `__pipeline_recomputation_index`, `__node_content_hash`, `__data_context` for the pipeline). A miss needs no call. Hits read their full rows by `read_by_keys`. @@ -490,8 +505,8 @@ commit wins, and no error is raised. | Function pipeline | hash of system tags, input hash, recomputation index | `__data_id`, `__computed`, `__output_data_hash`, `__is_ephemeral`, `__pipeline_run_id`, `__recorded_at` | **no** (below) | | ... its recomputation index | read, then write | two writers both take index `n`; one recomputation disappears from the history | **no** | | Side-effect log | hash of the same preimage | `pipeline_run_id`, `executed_at` | the log is, the **delivery is not**: both delivered before either logged | -| Operator cache | hash of the row and node content hash | `ox_order`; float bits (below) | yes, up to float bits | -| Cached source | hash of the row with system tags | `ox_order`; float bits | yes, up to float bits | +| Operator cache | hash of the row and node content hash | float bits (below) | yes, up to float bits | +| Cached source | hash of the row with system tags | float bits | yes, up to float bits | Every row of a table has the same `__node_content_hash` for one id only where that hash enters the id: it does for the operator cache. For the pipeline table it is redundant with the path and @@ -582,8 +597,12 @@ stopped. 3 to 5 s a run at the times seen live (P9 measures). Permissions: none beyond writing. **Detection besides the lease** (also the fallback if C1 and P11 both fail, and then documented as -best effort only): after a commit, the written ids' `ox_order` are read back and a difference -raises a warning naming the table and count; a later overwrite is missed. +best effort only): after a commit, the written ids are read back by key and compared with the rows +written. No hidden column is needed: what a second writer changes in a pipeline record +(`__data_id`, `__pipeline_run_id`, `__recorded_at`) and in a side-effect row (`pipeline_run_id`, +`executed_at`) is stored data. A difference raises a warning naming the table and the count. +A later overwrite is missed. **For the other tables there is no detection and none is needed**: a +result's id is a random UUID, and a cache row written twice is the same row up to float bits. Follow-up (several writers), not designed here: the key (`__record_id`, writer), which keeps every writer's row, or a conditional write in `spiral-sdk` (ITL-931). A store made now is rebuilt to @@ -634,9 +653,9 @@ today until PR 5. |---|---|---| | 1 | Fake as strict as the client (3.4); the connector refuses what it must (`fixed_size_binary`, `duration`, `null`, table names); `database-types.md` regenerated | each rule, with the native library's text; matrix | | 2 | `spiral_store` codec: names, types, manifest, as pure functions with no pyspiral | property tests: names (adversarial alphabet, nested), schema round trip over the type matrix, chunk sizes, two manifests | -| 3 | Connector: store tables use the codec; `ox_order`; table names and the catalog; null struct refused when added; `ConnectorArrowDatabase` asks the connector for a table's name | matrix on the fake; column and row order; foreign tables unchanged; a failed first write; two connectors with an injected failure (ITL-1190's interleaving); collisions of 5.2; catalog: crash between each step, lost, partly lost, another version, `.at()` views, a forced digest collision | +| 3 | Connector: store tables use the codec; table names and the catalog; null struct refused when added; `ConnectorArrowDatabase` asks the connector for a table's name | matrix on the fake; column order; rows as a set; foreign tables unchanged; a failed first write; two connectors with an injected failure (ITL-1190's interleaving); collisions of 5.2; catalog: crash between each step, lost, partly lost, another version, `.at()` views, a forced digest collision | | 4 | Lookups (4.3): keyed and `where` reads, the run index, table handles; failed rows restored (6.4) | call counts per run asserted; equivalence with the whole-table path (`test_*_lookup_equivalence`); staleness by a second handle | -| 5 | Job: the lease (6.3) in the database and in `job.run`, `run_async` and `node.run`; refusals removed where covered; the post-commit check; docs (names, other readers, cleanup, permissions, the lease and its two conditions) | the pipeline store suites parametrised over the fake: first run, rerun, added rows, changed version, `run()` and `run_async()`, save and load, `load_only`, `clear_cache`, separate result database, `trace`; equal to Delta: sync exactly, async as sets. Every table kind. The lease: each row of 6.3's table, on the fake, with two handles and an injected crash between any two steps | +| 5 | Job: the lease (6.3) in the database and in `job.run`, `run_async` and `node.run`; refusals removed where covered; the post-commit comparison (pipeline records and side-effect rows); docs (names, other readers, cleanup, permissions, the lease and its two conditions) | the pipeline store suites parametrised over the fake: first run, rerun, added rows, changed version, `run()` and `run_async()`, save and load, `load_only`, `clear_cache`, separate result database, `trace`; a run's rows equal Delta's: sync exactly, async as sets; stores compared as sets of rows; `Batch` over a stored source asserted only for what 3.6 promises. Every table kind. The lease: each row of 6.3's table, on the fake, with two handles and an injected crash between any two steps | | 6 | Live suite (the existing `spiral-integration` job): PR 5's job, the type matrix, P7, P8, cost printed; every table dropped | live | | later | batched `_fetch_joined_records`; null structs; observers; maps if P3 refuses; several writers | | @@ -651,7 +670,7 @@ save an override that is not a known non-secret key (`server.url`). |---|---|---| | 1 | Where the mapping lives: (a) the store, (b) rename everywhere, (c) mixed | (a) | | 2 | *Decided: one writer, a second refused.* To confirm: the lease's conditions C1 and C2 are acceptable, and what ships if P8 refutes C1 (named-table lease if P11 holds, else detection only) | lease; do not ship a "refusal" resting on neither | -| 3 | Row order: store `ox_order` so reads follow the written order | yes; otherwise results differ from Delta | +| 3 | *Decided: no row order is kept or promised; a store is a set of rows (3.6).* | - | | 4 | *Decided: digest names, and one catalog per dataset.* To note: permissions are per project (5.5) | - | | 5 | Two different manifests in one table stop the job, rather than one winning | stop | | 6 | Digest names and the catalog for SQLite and PostgreSQL too (5.6): existing tables there are rebuilt, nobody has any | yes, a later PR before 0.4.0; the first version does not wait | @@ -667,7 +686,7 @@ save an override that is not a known non-secret key (`server.url`). - Everything marked "to probe". The fake cannot answer timing, conflicts, visibility or server limits. - The prototype maps names and top-level types only, and its job has number and text columns and - UTC timestamps; it runs no logical type. It does not implement the manifest set, `ox_order`, the + UTC timestamps; it runs no logical type. It does not implement the manifest set, the catalog, the proposed table names or the lookups. - The async path, save and load, `load_only` and `trace` were not run through the prototype. - The fake's and the matrix's behaviour for logical types nested at depth was read, not run diff --git a/docs/dev/specs/itl-1446/prototype-output.md b/docs/dev/specs/itl-1446/prototype-output.md index 721b16658..b37c4736b 100644 --- a/docs/dev/specs/itl-1446/prototype-output.md +++ b/docs/dev/specs/itl-1446/prototype-output.md @@ -8,6 +8,18 @@ order (60 rows): pipeline table equal False, as_source() equal True cached source, in memory: k [0, 1, 2, 3, 4, 5], Batch(2) gives y [[0.0, 1.0], [2.0, 3.0], [4.0, 5.0]] cached source, Delta: k [0, 1, 2, 3, 4, 5], Batch(2) gives y [[0.0, 1.0], [2.0, 3.0], [4.0, 5.0]] cached source, SpiralDB: k [4, 5, 1, 2, 3, 0], Batch(2) gives y [[4.0, 5.0], [1.0, 2.0], [3.0, 0.0]] +record ids, in memory, 4 rows, key None: ['row_0', 'row_1', 'row_2', 'row_3'] +record ids, in memory, 4 rows, key ['k']: ['{"k":0}', '{"k":1}', '{"k":2}', '{"k":3}'] +record ids, in memory, 8 rows, key None: ['row_0', 'row_1', 'row_2', 'row_3'] +record ids, in memory, 8 rows, key ['k']: ['{"k":0}', '{"k":1}', '{"k":2}', '{"k":3}'] +record ids, Delta, 4 rows, key None: ['row_0', 'row_1', 'row_2', 'row_3'] +record ids, Delta, 4 rows, key ['k']: ['{"k":0}', '{"k":1}', '{"k":2}', '{"k":3}'] +record ids, Delta, 8 rows, key None: ['row_4', 'row_5', 'row_6', 'row_7'] +record ids, Delta, 8 rows, key ['k']: ['{"k":0}', '{"k":1}', '{"k":2}', '{"k":3}'] +record ids, SpiralDB, 4 rows, key None: ['row_3', 'row_0', 'row_2', 'row_1'] +record ids, SpiralDB, 4 rows, key ['k']: ['{"k":0}', '{"k":1}', '{"k":2}', '{"k":3}'] +record ids, SpiralDB, 8 rows, key None: ['row_5', 'row_1', 'row_4', 'row_2'] +record ids, SpiralDB, 8 rows, key ['k']: ['{"k":0}', '{"k":1}', '{"k":2}', '{"k":3}'] | Rows | Run | list tables | look up table | get metadata | set metadata | create table | write transaction | whole-table scan | |---|---|---|---|---|---|---|---|---| diff --git a/docs/dev/specs/itl-1446/prototype.py b/docs/dev/specs/itl-1446/prototype.py index 0805a0322..ca607dcd9 100644 --- a/docs/dev/specs/itl-1446/prototype.py +++ b/docs/dev/specs/itl-1446/prototype.py @@ -29,7 +29,7 @@ from orcapod import PipelineJob, function_pod from orcapod.core.operators import Batch, GroupBy, Join, PolarsFilter -from orcapod.core.sources import ArrowTableSource +from orcapod.core.sources import ArrowTableSource, DerivedSource from orcapod.core.sources.cached_source import CachedSource from orcapod.databases import ( ConnectorArrowDatabase, @@ -38,7 +38,7 @@ SpiralDBConnector, ) from orcapod.side_effects import SideEffectPod, SideEffectPodConfig -from orcapod.types import ColumnInfo +from orcapod.types import CacheMode, ColumnInfo from orcapod.utils.arrow_utils import normalize_table_to_large_types from tests.test_databases import fake_pyspiral @@ -388,6 +388,48 @@ def check_cached_source_order() -> None: ) +def check_positional_ids() -> None: + """Positional record ids of a ``tags_as_data`` source over a logged operator.""" + for name, build_database in ( + ("in memory", lambda root: InMemoryArrowDatabase()), + ("Delta", lambda root: DeltaTableDatabase(Path(root) / "delta")), + ("SpiralDB", lambda root: ConnectorArrowDatabase(MappingConnector("p"))), + ): + with tempfile.TemporaryDirectory() as root, fake_pyspiral.install(root): + database = build_database(root) + for rows in (4, 8): + job = PipelineJob(name="positional", database=database) + with job: + Join()( + _source(rows, "left", ["y"]), + _source(rows, "right", ["b"]), + label="joined", + ) + node = job.nodes["joined"] + node.attach_databases( + pipeline_database=database, cache_mode=CacheMode.LOG + ) + job.run() + for keys in (None, ["k"]): + origin = node.as_source(tags_as_data={"k": "kk"}, source_id="d") + if keys is not None: + origin = DerivedSource( + node, + source_id="d", + tags_as_data={"k": "kk"}, + record_id_columns=keys, + ) + table = origin.as_table(columns={"system_tags": True}) + column = next( + c for c in table.column_names if c.startswith("_tag_record_id") + ) + ids = dict(zip(table["k"].to_pylist(), table[column].to_pylist())) + print( + f"record ids, {name}, {rows} rows, key {keys}: " + + f"{[ids[k] for k in range(4)]}" + ) + + def check_cost() -> None: """SpiralDB calls per run, today's lookups.""" print( @@ -521,6 +563,7 @@ def run(fn: Any, name: str, db: Any) -> list[float]: check_job() check_order() check_cached_source_order() + check_positional_ids() check_cost() check_names() check_wrong_result() From 3526f0269c7f8e3de0402343562dee3e984dbef3 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 10:56:48 -0800 Subject: [PATCH 7/8] docs(specs): revise the SpiralDB store design after review (ITL-1446) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1446-spiral-columns.md | 1129 ++++++++----------- docs/dev/specs/itl-1446/lease_model.py | 117 +- docs/dev/specs/itl-1446/prototype-output.md | 1 + docs/dev/specs/itl-1446/prototype.py | 29 +- 4 files changed, 592 insertions(+), 684 deletions(-) diff --git a/docs/dev/specs/itl-1446-spiral-columns.md b/docs/dev/specs/itl-1446-spiral-columns.md index e548ac329..30d04a129 100644 --- a/docs/dev/specs/itl-1446-spiral-columns.md +++ b/docs/dev/specs/itl-1446-spiral-columns.md @@ -1,693 +1,548 @@ # ITL-1446: storing a pipeline in SpiralDB -Status: **proposal, nothing implemented.** Section 8 lists the decisions the developer makes. -Decided (developer, 2026-11-24): the first version runs one job at a time and **refuses** a second -writer (section 6.3; several writers are a follow-up issue); every table kind goes to SpiralDB -(function pipeline, function result, operator cache, cached source, side-effect log); the live -probes may use the throwaway test project. -Covers ITL-1176, ITL-1164, ITL-1100 (names, tables) and ITL-1190 (metadata races). - -How each statement below is known: - -- **Measured**: run on `main` at `7a2248bf` on the disk fake (`tests/test_databases/fake_pyspiral.py`) - by the scripts in [`itl-1446/`](itl-1446/). The fake is a model, not the service. -- **Read**: from the installed pyspiral 0.16.33 (its Python source, stubs, or the text of its - native library). Reading says what the client offers, not what the server does. -- **Seen live**: an earlier live session, cited by issue. -- **To probe**: not known; section 7 lists one live probe for each. No SpiralDB was used here. - -## 0. Summary - -- **Recommendation: option (a).** A SpiralDB store maps column names, types and table names when - it writes and restores them when it reads. Nothing above the database changes: no hash, record - path, layout version or golden value moves. -- A prototype of (a) runs a job (join, filter, function, group by, second function, side effect) - on the fake with rows, schemas, system tags and content hashes equal to the in-memory store's, - and an unchanged rerun calls nothing (Measured, [`prototype.py`](itl-1446/prototype.py)). -- Column names are the small part. Reading the code and running the prototype found five things - the issue does not list. F3 is accepted; the others must be in the first version: - -| # | Finding | How known | Section | -|---|---|---|---| -| F1 | **Table names are too long.** pyspiral types a table name as at most 128 characters of `[a-zA-Z0-9_-]`. A function pipeline table's name is 181 characters today. `unstorable_table_name_reason` says SpiralDB holds every name | Read, Measured | 5 | -| F2 | **Table names collide, and a collision serves wrong results.** `function_name="my-fn"` and `"my_fn"` share one result table; the second function is given the first one's values | Measured | 5 | -| F3 | **Row order is not kept.** SpiralDB returns rows in key order, and the key is a hash, so `Batch(2)` over a `CachedSource` gives other batches than on Delta. *Accepted (developer): a store is a set of rows* | Measured | 3.6 | -| F4 | **Result record ids are not content derived.** A function result's id is a random UUIDv7; a pipeline record's id leaves out the result it names. "Same id, same content" holds only for operator caches and cached sources, and not bit for bit | Read | 6 | -| F5 | **The fake accepts what the client refuses**: `fixed_size_binary` and `duration` (pyspiral's own `Schema.from_arrow` raises) and probably a `null` column (the native library has an error for it). The connector says it stores all three | Measured (client, offline) and Read | 3.4 | +Status: **proposal, nothing implemented.** Revised after an independent review that found the +first draft not sound (section 11 answers each finding). Covers ITL-1176, ITL-1164, ITL-1100 and +ITL-1190. -## 1. Every stored column +Decided by the developer (2026-11-24): one job at a time, a second writer is refused; every table +kind goes to SpiralDB (function pipeline, function result, operator cache, cached source, +side-effect log); digest table names and one catalog per dataset, so a dataset is one +self-contained store; a store is a **set of rows**, with no row order kept or promised. -[`stored-columns.md`](itl-1446/stored-columns.md) is generated by -[`stored_columns.py`](itl-1446/stored_columns.py): a job writes every table kind, each -`add_records` call is recorded, and each column is given to -`SpiralDBConnector.unstorable_column_reason` and written alone through the fake. It has names, -Arrow types, nullability, the reason for each refusal, and what the fake does. 153 columns, 57 -refused. +How each statement is known: + +- **Live**: measured on the throwaway project by the live worker, taken as given until its + report; or an earlier session, cited by issue. +- **Fake**: run by the scripts in [`itl-1446/`](itl-1446/) on the disk fake, a model of SpiralDB. +- **Read**: from pyspiral 0.16.33 (Python source, stubs, text of the native library). +- **To probe**: unknown; section 9. + +## 1. Summary -| Table kind | Columns refused today | Reason | +A SpiralDB store maps column names and types, and table names, when it writes, and restores them +when it reads (option (a) of section 2). No hash, record path, layout or golden value moves. One +run holds a lease on the dataset; a catalog says which tables are the store's. + +| # | What the first version must solve | Known | |---|---|---| -| Function pipeline (`pdb_v1`) | the 11 bookkeeping columns: `__data_id`, `__node_content_hash`, `__input_data_hash`, `__output_data_hash`, `__data_context`, `__computed`, `__is_ephemeral`, `__pipeline_base_entry_id`, `__pipeline_recomputation_index`, `__pipeline_run_id`, `__recorded_at` | `__` prefix; `__recorded_at` also has a time zone | -| Function result (`rdb_v1`) | 13: `__input_data_hash`, six `__pf_var_*`, four `__pf_exec_*`, `__pod_ts`, `__data_context` | `__` prefix; `__pod_ts` also has a time zone | -| ... its outputs | `datetime`, `Path`, a user class, `list[UUID]` | time zone; logical (extension) type | -| Side-effect log (`tdb_v1`) | `executed_at`, `__data_context` | time zone; `__` prefix | -| Operator cache (`odb_v1`) | `__node_content_hash`, `__data_context`, and user columns by type | `__` prefix | -| Cached source (`sdb_v1`) | `__data_context`, and user columns by type | `__` prefix | -| Observer tables (opt-in) | none | but `_log_id` / `_status_id` are `fixed_size_binary[16]`, which the client refuses (F5) | +| F1 | Table names reach 182 characters and **collide**: `my-fn` and `my_fn` share a result table, and the second is served the first one's results | Fake | +| F2 | `__` columns, dotted names, time zones and logical types are refused: 57 of 153 stored columns ([list](itl-1446/stored-columns.md)) | Fake | +| F3 | Two writers of one key: the last commit wins, silently. No data-commit conflict exists | Live | +| F4 | A first write that fails leaves a key-only table that refuses every later run | Live | +| F5 | Lookups cost a whole-table scan for each new row, and 4 listings for each row | Fake | +| F6 | Result record ids are random; a pipeline record's id does not cover the result it names, so an overwrite is not harmless | Read | +| F7 | Row order is not kept. **Accepted** (section 3.5) | Fake | + +**Honest size: about four L of work, not a few days** (section 10), with a narrow first version. -A second point the list shows: the reason given is the first one found. `__recorded_at` and -`__pod_ts` fail twice, so fixing names alone does not make them storable. +## 2. Stored columns, and the options -## 2. Options +[`stored-columns.md`](itl-1446/stored-columns.md) is generated by +[`stored_columns.py`](itl-1446/stored_columns.py): every column of every table kind, with type, +nullability, the refusal and what the fake does. + +| Table kind | Refused today | +|---|---| +| Function pipeline (`pdb_v1`) | 11 bookkeeping columns (`__`); `__recorded_at` also for its zone | +| Function result (`rdb_v1`) | 13 (`__`); `__pod_ts` also for its zone; outputs that are `datetime` or logical types | +| Side-effect log (`tdb_v1`) | `executed_at` (zone), `__data_context` | +| Operator cache (`odb_v1`) | `__node_content_hash`, `__data_context`; user columns by type | +| Cached source (`sdb_v1`) | `__data_context`; user columns by type | | | (a) map in the store | (b) rename the stored columns everywhere | (c) mixed | |---|---|---|---| -| What changes | a SpiralDB store encodes on write and decodes on read | `SYSTEM_COLUMN_PREFIX` becomes a prefix SpiralDB accepts, for every store | (b) for Orcapod's own columns, (a) for user columns | -| Hashes, paths, golden | **none** | `__input_data_hash` and `__pipeline_recomputation_index` are column names in hashed preimages (`_build_record_id_preimage`), and `__node_content_hash` is in the operator cache's hashed row: every pipeline entry id, base entry id, side-effect id and operator record id moves | as (b) | -| Layouts | none | all five layout versions and the Python function type's revision | as (b) | -| Time zones, logical types, dotted names, table names | handled by the same mechanism | **not handled**; (a) is needed anyway | (a) is needed anyway | -| Existing stores | untouched | Delta stores of 0.4.0rc1 are no longer read | as (b) | -| What other SpiralDB readers see | `ox___data_context` for `__data_context` | a plain name | a plain name | - -(b) and (c) pay the cost of moving hashes and still need (a). **Recommended: (a).** +| Hashes, golden | none move | every pipeline entry, base entry, side-effect and operator record id moves: `__input_data_hash`, `__pipeline_recomputation_index` and `__node_content_hash` are names inside hashed tables | as (b) | +| Layouts | none | all five, and the Python function revision | as (b) | +| Zones, logical types, dotted names, table names | handled | not handled: (a) is needed anyway | (a) is needed anyway | +| Another SpiralDB reader sees | `ox___data_context` | a plain name | a plain name | -Where (a) lives: in `SpiralDBConnector`, for a table it creates through -`create_table_if_not_exists`, which is where `ConnectorArrowDatabase` learns a table is new. A -table is an *Orcapod store table* when its key-value metadata holds a manifest (3.3); every other -table is read and written exactly as today, without decoding. +**(a).** It applies only to a connector opened as a store (`store mode`, section 10), only to +tables in its catalog. A connector used otherwise, and `SpiralDBTableSource` over a user's table, +read and write as today. -## 3. Columns: the exact encoding +## 3. Columns ### 3.1 Names -`E(c)`, the stored name of a value column `c`: +`E(c)`, the stored name of a value column, or of a struct field among its siblings: -1. `c` is **plain** when it is not empty, does not start with `__` or `ox_`, and holds none of - `.`, `$`, `*` and the ASCII control characters (0-31, 127). A plain name is stored as it is. -2. Any other name is stored as `ox_` followed by `c` with each of `.`, `$`, `*`, `;` and each - control character written as `;` and two upper-case hex digits. +1. `c` is **plain**, and stored as it is, when it is not empty, does not start with `__` or `ox_`, + and holds none of `.` `$` `*` and the ASCII controls. +2. Otherwise it is `ox_` + `c`, with each of `.` `$` `*` `;` and each control written `;` + two + upper-case hex digits. -| Orcapod name | Stored name | +| Orcapod name | Stored | |---|---| -| `x`, `_source_x`, `_tag_source_id::`, `a;b`, `é`, `a b` | unchanged | +| `x`, `_source_x`, `_tag_source_id::`, `a;b`, `a;2Eb`, `é` | unchanged | | `__data_context` | `ox___data_context` | | `a.b` | `ox_a;2Eb` | -| `a;2Eb` | `a;2Eb` (plain) | -| `ox_a;2Eb` (a user's column that looks encoded) | `ox_ox_a;3B2Eb` | -| `ox_` | `ox_ox_` | +| `ox_a;2Eb` | `ox_ox_a;3B2Eb` | | the empty name | `ox_` | -`D(s)`: if `s` does not start with `ox_`, `s`; otherwise drop `ox_` and replace each `;HH`. - -**Injective, proof.** A plain name does not start with `ox_`, so it never equals an encoded one, -and plain names map to themselves. Among encoded names, the escape replaces single characters by -codes that start with `;`, and a literal `;` is itself escaped, so reading left to right every `;` -starts a code of exactly two digits and every other character is literal: `D(E(c)) = c`. So `E` is -injective. **Accepted by SpiralDB's known rules**: no `.` remains, and no stored value column -starts with `__` or `$`. The prototype checks round trip, injectivity and these rules on 200,000 -adversarial names; the implementation keeps that as a property test. - -Why these characters: `:` `::` space, `-`, `;`, `"`, `/`, upper case, non-ASCII letters and JSON -text were accepted live (ITL-1164). `%` was never tried, so the escape is `;`, not `%`. `$` is -"reserved for key columns" (Read: native library text). `*` selects all columns in -pyspiral's expressions (`Expr.__getitem__`). - -- **Key column.** `__record_id` is stored as it is: SpiralDB accepts `__` on a key column. - `E` never yields a name that starts with `__`, so a value column cannot collide with it. -- **Unicode.** Characters are kept as code points, with no normalisation. To probe: whether - SpiralDB normalises (`é` as one or two code points) or folds case. If it does, two names that - it merges are refused before writing; the rule is written from the probe, not guessed. -- **Length.** An encoded name adds 3 characters and 2 per escaped one. No client limit was found - (Read); to probe. The longest names Orcapod writes are a join's system tags: - `_tag_record_id::<64 hex>::<64 hex>:0` is 148 characters after one join (section 1's list), and - each nested join adds 68. -- **Nested names.** SpiralDB stores a struct column as a column group, and its name rules are - stated for "column group columns", so a struct field named `a.b` or `__x` may be refused or - split. The same `E` is applied to struct field names at every depth. - -### 3.2 What is kept, per Arrow type - -The store writes a *physical* column and restores the *logical* one from the manifest. All -physical fields are declared nullable (SpiralDB stores a null in a non-null struct field as the -type's zero, seen live, ITL-936); the logical flags are checked before a write and after a read, -as the nullability record does today. - -| Logical type | Physical | Restored by | First version | -|---|---|---|---| -| timestamp with a zone, top level or nested | the same integers, `timestamp[unit]` without a zone | a zero-copy view under the recorded type. Exact for every zone and unit the physical type keeps: Arrow stores UTC instants | yes | -| logical (extension) type, top level | its storage type, mapped by this table | the recorded extension name and metadata; a live type when it is registered, else field metadata | yes | -| logical type in a list (`list[UUID]`) | a native container is itself one top-level extension type over its storage | as above | yes | -| logical type nested in a plain list or struct | Orcapod refuses it at definition (`require_storable_in_struct_field`); one that reaches the store is refused | - | refuse | -| logical data-tag | as a top-level column; the data-tag marker is field metadata, and the manifest keeps field metadata at every depth | manifest | yes | -| `large_string` / `large_binary` / lists | native | large normalisation, as today | yes | -| `fixed_size_binary[n]` | `large_binary` | recorded width; another width is refused on read (as Delta) | yes (F5) | -| `duration` | `int64` | view | yes (F5) | -| `null` column | `int8`, all null | recorded type | yes (F5) | -| struct | struct with encoded field names. SpiralDB returns the fields sorted by name (seen live, ITL-1367) | fields matched by name, in recorded order | yes | -| **null struct** | refused today (`UnsupportedValueError`), at flush, after the function ran | later: a hidden presence field | refuse, but when rows are added (`validate_records`), before anything is buffered | -| map with fields `key` / `value` | native | recorded key order flag, nullability and metadata | keep if the live matrix keeps it, else refuse | -| renamed map | IPC renames the fields, so the record cannot hold them | - | refuse, as today | -| `interval`, union, list view, dictionary, run-end encoded | - | - | refuse (the client refuses an interval; streams refuse the others) | -| `decimal256`, `float16`, `date64`, `time` | native (the client accepts them, offline) | recorded type | by live matrix; a lossy one is refused | -| float bits (`-0.0`, NaN payloads) | native | - | by live matrix; a lossy one is recorded as an integer or refused | - -"Kept" must be shown twice: on the fake by the type matrix, and live by the same matrix. A row -is kept in the first version only when **both** keep it. - -### 3.3 The manifest, against today's two records - -| | nullability record (ITL-936) | Arrow metadata (ITL-471) | manifest (proposed) | -|---|---|---|---| -| Holds | non-null paths | field and schema metadata | the whole logical schema: names, order, types, nullability, metadata; the record path; the encoding version | -| Size | chunked, under 8 KiB each | **one entry: over 8 KiB the write raises** (Measured: 200 columns with a 40-byte metadata value) | chunked | -| Written | first write | before **every** write | once | -| After a failed first write | removed (races, ITL-1190) | previous value put back (races) | stays | -| Two writers | last header wins | last entry wins | a set: both stay, and a difference is found | - -Format: header key `__orcapod_store__/` with `{"format", "version", "chunks", "sha256"}`, -and chunk keys `__orcapod_store__//`. The payload is JSON: encoding version, record -path, and the Arrow schema in storage form (logical types as `ARROW:extension:*` field metadata, -`canonical_form.storage_form_schema`) as base64 IPC. Chunks go first, then the header. - -- **No write ever replaces or removes a manifest** (a grow-only set of digests), so two writers - cannot lose one another's. Manifests are compared as decoded schemas, field by field at every - depth (Arrow's own type equality ignores nested names), so bytes that differ only by pyarrow - version agree. -- **Two different manifests in one table** are refused, on read and write, naming both. Data is - never decoded by the wrong one. The pipeline determines a node's columns, so this should not - happen; if it does it is a bug or another Orcapod version, and stopping is right. -- **A manifest without rows** (a first write that failed) is inert: the table reads as having - those columns and zero rows. The next writer of the same schema just writes. -- A writer compares its rows' schema with the manifest before buffering; the check costs nothing - after the first time (the manifest of a table id does not change). -- To probe: whether parallel `set_metadata` calls on **different** keys keep both. pyspiral says - entries are upserted and parallel calls race "to set a value". If the server replaces the - whole map, the manifest goes to a table of its own (the catalog of section 5.4), where a write - is an upsert of one row. - -Limits: 1,024 entries a table, 8 KiB a pair, 255 characters a key. A key here is at most 90 -characters. A 1 MiB schema fits in about 130 entries. - -### 3.4 The fake must be made as strict as the client first - -F5 means that today's "kept" in the SpiralDB column of `docs/reference/database-types.md` is not -evidence for `fixed_size_binary`, `duration` and `null`. The fake's other gaps that matter here: -struct fields keep their order (live: sorted), every table name is accepted (client: 128 -characters, `[a-zA-Z_][a-zA-Z0-9_-]*`), `$` is accepted, duplicate keys in one write are -accepted (native text: "Duplicate keys found in input batch"), and a write of key columns only is -accepted (native text: "Write array contains only key columns"). The first PR makes the fake -refuse these, so the suite fails where the service would. - -### 3.5 Tables of another program, other readers, pushdown - -- **A table another program wrote** has no manifest: names, types and nullability are read as - today, so a user's column called `ox_a` stays `ox_a`. `SpiralDBTableSource` is unaffected. The - store refuses to write into a table without a manifest that has value columns. -- **Another SpiralDB reader of a store table** (CLI, Polars, DuckDB, spiral-sdk) sees `ox___pod_ts` - as a timestamp without a zone (UTC instants), a logical type as its storage, a `File` or user - class as its struct with sorted fields. Plain user columns, tags and - `_source_*` are readable under their own names. Documented, with the encoding version. -- **A `SpiralDBTableSource` over a store table** must not silently show encoded names: it reads - the manifest, so it shows Orcapod's names, and refuses a manifest version it does not know. -- **Writes by another program into a store table** cannot be prevented. A read checks every - batch against the manifest: a missing or retyped column, or a null in a non-null one, raises - naming it; an extra column not in the manifest raises too. -- **Pushdown.** A predicate on an Orcapod column is built on `E(name)`, its literal converted as - the column is (a zone-aware instant to its UTC timestamp; a logical column is not pushed down). - Encoding removes `.` from names, which `table["a.b"]` would split. Store lookups use only - binary, text and boolean columns, so nothing else is needed at first. - -### 3.6 Order - -**Column order.** SpiralDB stores value columns sorted by name. A read puts them in the -manifest's order, so a table reads back in the order of its first write, as on Delta. - -**Row order: none is kept, and none is promised** (decided, developer, 2026-11-24). A database is a -**set of rows** unless one says otherwise. There is no order column and nothing hidden; stores are -compared as sets of rows. A read of an unchanged table gives SpiralDB's key order, which is a hash -order and says nothing about when a row was written. - -Within a run nothing depends on it: a node's rows are in the run's own order, stored rows -included (ITL-1441), which the run takes from its inputs. So a job gives equal rows in the same -order on SpiralDB and Delta, unless one of its **inputs** is read from a store. There, what can -differ from Delta (Measured on the fake and on Delta): - -| Where | SpiralDB (prototype) | Delta | -|---|---|---| -| `CachedSource` over k = 0..5 | 4, 5, 1, 2, 3, 0 | 0, 1, 2, 3, 4, 5 | -| `Batch(2)` over it: y | [4, 5], [1, 2], [3, 0] | [0, 1], [2, 3], [4, 5] | -| `as_source(tags_as_data=...)` over a logged `Join`: **positional** record ids of k = 0..3 | 3, 0, 2, 1; after 4 rows are added 5, 1, 4, 2 | 0, 1, 2, 3; after 4 rows are added 4, 5, 6, 7 | -| the same with `record_id_columns=["k"]` | `{"k":0}` ... in every case | the same | +**Injective.** A plain name never starts with `ox_`; an encoded one does. In an encoded name every +`;` starts an escape of two digits, because a literal `;` is escaped there. Checked on 200,000 +adversarial names (Fake). The key column `__record_id` is stored as it is; no `E(c)` starts with `__`. -All accepted. The consequences, to be documented: +**Reading never decodes a name.** `E` is invertible only on its image (`ox_order` would decode to +`order`, which is not stored so). The manifest lists each column's logical and stored name, at +every depth; a read looks for exactly the **expected stored name**, and refuses a missing, extra +or repeated one. The earlier prototype looked for the logical name first, and so gave column +`ox_a;2Eb` the values of `a.b`; it is fixed, with a check. -- **An order-sensitive step over rows read from a store** (`Batch`; a `GroupBy` whose members tie - on every tag and record id) may group differently, so its values, folded record ids and what is - recomputed downstream differ. This covers a `CachedSource`, a `REPLAY` operator, and any - `as_source()`. -- **Adding rows** puts them anywhere in key order, so such a step's earlier groups change. On - Delta too: the third row shows that Delta's order is not append order either. -- **Positional record ids over a stored node** move when rows are added, and everything - downstream is computed again. Give `record_id_columns`. -- `head()`, previews and `as_table()` of stored rows show key order; `sort_by_tags` for a stable - one. -- Two results of one input with an equal `__pod_ts` (to the microsecond): which one a lookup - takes is unspecified, as it is today. +Refused before anything is written, naming the column: -Compare-as-sets is for what is read **from a store**. A run's own rows are still compared exactly -for sync and as sets for async. +- a name or path component that is not valid UTF-8 (a lone surrogate); +- two siblings of one name, at the top level or among a struct's fields; +- a name over the service's limit, in characters or bytes, once probed. -### 3.7 Does anything move? +Matching uses path components, never joined text. List item and map key/value names are Arrow's +own and are not encoded. -No. Hashes, `record_path` tuples, system-tag column names, layout versions, data function type -revisions and golden values are computed above the database, from Orcapod names and types. The -manifest's SHA-256 and the table name's SHA-256 (section 5) are in names; both get a row in the -hash site inventory ("in a name"). The store's own format is versioned by the manifest's -`version`, independent of `pdb_v1` and the others. The implementing PRs run `--check` on golden. +**Case and Unicode folding: a rule that waits for P1, not a guess.** Upper case was kept live +(`B, C, a`, ITL-1367); whether two names that differ only in case or in normal form can be +siblings is unknown. If the service keeps them apart, nothing is added. If it folds or +normalises: names that it would change (even alone) are escaped, by adding exactly those +characters to the escaped set, so stored names are stable under the service and stay distinct. +Until P1 runs, the store refuses non-ASCII names and names with two siblings equal under +`casefold`. In either case the first commit of a table is **read back** and its column names must be +exactly the expected ones; otherwise the write fails and the table stays `intended` (5.3). -## 4. Lookups +### 3.2 Types -### 4.1 What a run costs today +All physical fields are nullable (a null in a non-null struct field is stored as zero, seen live, +ITL-936). Logical nullability is checked on write and read, a child's under its parent's validity; +the key has its own rule: never null. -SpiralDB calls of the six-step job of `prototype.py` with today's lookups (Measured on the fake; -each is at least one round trip on the service): +| Logical type | Physical | First version | +|---|---|---| +| timestamp with a zone, at any depth | the same integers without the zone (zero-copy view) | kept | +| logical type at the top level, a native container (`list[UUID]`, `set[int]`) included | its storage | kept; live when registered, else as field metadata | +| logical type inside a plain list or struct | - | refused (Orcapod refuses it at definition too) | +| text, binary, `large_list`, integer, bool, float32/64, date32, naive timestamp | native | kept once P3 shows it, float bits included | +| struct | encoded field names; SpiralDB sorts fields by name (live, ITL-1367); restored by name in the recorded order | kept | +| a **null struct** | - | refused when the batch is added, before it is buffered | +| `fixed_size_list`, map, `decimal`, `float16`, `date64`, `time` | native | kept only if both the fake and P3 keep it; until then refused | +| `fixed_size_binary`, `duration` | - | refused: pyspiral's own `Schema.from_arrow` raises (Read, offline) | +| `null` | - | refused; only inferred from a native error text, so P3 confirms it | +| renamed map, map field metadata, `interval` | - | refused | + +A data-tag's marker is field metadata, which the manifest keeps at every depth. + +**What "refused before anything is written" means.** A refusal by type or name happens when the +database is attached, or before the first row of the table. A refusal by **value** (a null struct, +a null in a non-null field) happens when that batch is added: batches committed earlier in the run +stay, as results that a rerun reuses. ITL-1446's wording is wider; this narrower promise is +decision 3. + +### 3.3 The manifest + +One manifest per table, written once at creation under the lease, never changed: format version, +record path, kind, and the logical schema (names with stored names, order, types, nullability, +metadata at every depth, in storage form). Chunks `__orcapod_store__//` first, then the +header `__orcapod_store__/`. + +- A read checks the full digest, the chunk count and order, the schema, and that the recorded path + is the one asked for. Chunks without a header are no manifest; two headers are refused. +- It replaces, for store tables, the nullability record and the Arrow metadata entry. The latter + is one entry of at most 8 KiB, above which a write raises today (Fake: 200 columns). +- Schemas are compared field by field at every depth, unknown logical types by name and metadata. +- **A manifest without value columns** (a crash before the first rows) reads as zero rows of the + recorded schema. The key-only table is never scanned, which the service refuses (live, ITL-926). + +### 3.4 Other programs, pushdown + +Another SpiralDB reader sees stored names, UTC instants without a zone, storage types. A +`SpiralDBTableSource` over a store table reads the manifest and shows Orcapod's names; it refuses +a format it does not know. Writes by another program into a store table cannot be prevented; a +read checks every batch against the manifest. Predicates use stored names and only text, binary, +boolean and integer columns; everything else is filtered by Arrow, with the same null behaviour. + +### 3.5 Order + +Columns come back in the manifest's order. **Rows: no order is kept, promised or hidden.** A +node's rows within a run are in the run's own order (ITL-1441). Where a job's *input* is read from +a store, an order-sensitive step can differ from Delta (Fake, and local Delta): -| Rows | Run | list tables | look up table | metadata reads | writes | whole-table scans | -|---|---|---|---|---|---|---| -| 2 | first | 35 | 15 | 5 | 5 | 3 | -| 50 | first | 227 | 15 | 5 | 5 | 3 | -| 50 | unchanged rerun | 10 | 14 | 7 | 0 | 7 | -| 50 | 10 rows added | 48 | 89 | 48 | 5 | 34 | +| Where | SpiralDB (prototype) | Delta | +|---|---|---| +| `CachedSource` over k = 0..5 | 4, 5, 1, 2, 3, 0 | 0, 1, 2, 3, 4, 5 | +| `Batch(2)` over it: y | [4, 5], [1, 2], [3, 0] | [0, 1], [2, 3], [4, 5] | +| positional record ids of `as_source(tags_as_data=...)` over a logged `Join`, k = 0..3 | 3, 0, 2, 1; after 4 rows more 5, 1, 4, 2 | 0, 1, 2, 3; after 4 rows more 4, 5, 6, 7 | +| the same with `record_id_columns=["k"]` | stable | stable | -Three separate problems: +Accepted, and documented: `Batch` (or a `GroupBy` with full ties) over a `CachedSource`, a +`REPLAY` operator or an `as_source()` may group differently and so change values and ids +downstream; adding rows can regroup earlier ones; positional ids over a stored node move. Delta +does not keep append order either. Conformance tests use order-independent jobs and one explicit +order-sensitive example. -1. **`list_tables` per row** (4 per row on a first run): `ConnectorArrowDatabase` lists the whole - project to ask whether one table exists. At about 1 s a call (seen live, ITL-926: 1.2 s for - 27 tables) 50 rows spend minutes. -2. **A whole-table scan per new row and table.** `ResultCache.lookup` (by `__input_data_hash`) - and `add_pipeline_record` (by `__pipeline_base_entry_id`) are called once per row, through - `get_records_with_column_value`. N new rows read the table N times: quadratic. The issue's - "record-id lookup pushdown" covers neither, since both look up by another column; only the - side-effect log looks up by record id. -3. **Whole tables per node per run** (`_fetch_joined_records` reads the pipeline table and the - result table, payload included, whatever the inputs). +## 4. The lease -### 4.2 What pyspiral 0.16.33 offers (Read) +### 4.1 What the service gives -| Facility | Use | +| Primitive | Live result | |---|---| -| `scan(proj, where=expr)`; `==`, `!=`, `<` ..., `&`, `\|`, `~`, `is_null`; `expr.in_([...])` (a list literal: `list.contains`) | lookup by any column | -| `scan(proj).to_record_batches(key_table=keys)` | **take by key**: a table whose columns are exactly the key schema | -| `scan(..., asof=version)`, `last_modified_at()` | pin a read; one call says whether a table changed | -| `scan(table.select("a", "b"))` | read some columns only | -| `scan(..., key_ranges=[KeyRange])` | ranges; excludes `key_table` | -| `scan_keys` | keys only. The client says it reads keys of the referenced column groups; seen live, a scan of key columns alone was refused (ITL-926) | -| `Spiral.sample`, `enrich` | not needed | - -There is no conditional write, no read of "rows changed since a version", and no transaction over -two tables. Docs say an unsorted or repeated `key_table` is supported but slower; the native text -says "must be sorted by key". So keys are always sorted by bytes and made unique. - -### 4.3 Design, for SpiralDB only - -The protocol methods stay as they are. Three optional connector methods, which the database uses -when the connector has them (as `get_arrow_schema` today); SQLite and PostgreSQL keep their path: - -- `read_by_keys(table, ids)`: `key_table` of `{"__record_id": large_binary}` (cast to the key - type the table states: `binary` or `large_binary`), sorted and unique, 10,000 ids a batch (about - 0.6 MB of 60-byte ids; the size is a constant set by a live measurement). Serves - `get_record_by_id`, `get_records_by_ids` and `skip_existing` (which today scans the table and - converts it to Python). -- `read_where(table, pairs)`: equality on encoded names. Serves `get_records_with_column_value`. - Binary, text, boolean and integer columns only; anything else is filtered by Arrow on the - client, as today. -- `read_columns(table, names)`. - -That makes each lookup small, but still one round trip a row. At 0.7 to 1.7 s a scan (seen live) -1,000 new rows would take an hour. So lookups are answered from a **per-table index held for one -run**, as `DeltaTableDatabase` does with its `KeyIndex`: - -- On the first lookup in a table, read only the lookup columns of all rows with a pinned `asof` - (`__record_id`, `__input_data_hash`, `__data_context`, `__pod_ts` for results; - `__record_id`, `__pipeline_base_entry_id`, `__pipeline_recomputation_index`, - `__node_content_hash`, `__data_context` for the pipeline). A miss needs no call. Hits read their - full rows by `read_by_keys`. -- Columns indexed are those a caller has filtered by, so the database needs no knowledge of - table kinds. -- Own commits extend the index. Pending rows are consulted as today. -- About 250 bytes a row: 1 M rows is about 250 MB and one scan. `read_where` per lookup is the - fallback above a limit (proposed: 2 M rows by `row_count_estimate`). - -Batch-loading the rows a run needs (problem 3) is a change in `_fetch_joined_records`: ask by the -run's base entry ids, then result ids, instead of `get_all_records`. It is a separate PR after the -store works, since it touches every store's path. - -**Staleness.** `refresh_table` is already called for each table of a function node at the start of -a run and at every read of what is stored (ITL-1408). On SpiralDB it becomes one -`last_modified_at` call: unchanged keeps the index, changed drops it. Within a run the handle -does not see another writer's rows, which costs at most a repeated computation, as on Delta; the -keyed check before a write (section 6) reads the latest version. - -**Table existence and handles.** `lookup_table` once per table and handle (the exact-name -listing), kept until `refresh_table`; "does not exist" is asked again at refresh and before -create. Expected calls per run: about 2 per table for an unchanged rerun, plus 2 to 4 per commit, -and none per row. The tests assert these counts on the fake. - -## 5. Table names - -### 5.1 Today - -Each path component has every character other than `[a-zA-Z0-9_]` replaced by `_`, joined by -`__`; `t_` in front of a digit. - -### 5.2 Collisions: disproved safe, by example - -| Path A | Path B | One name today | +| `create_table(exist_ok=False)` | an **atomic test-and-set**: 25 rounds of 5 processes, exactly one winner, the others a 409; 0.12 s | +| dropping by table **id** | a late clearer gets a 404 and cannot drop a newer table of that name; takeover 10 of 10 rounds one winner | +| owner text in the key column's name | fits, so the owner is part of the atomic create | +| claim row, then check | works, but about 6 s, and two starts at once are both refused in 45 of 48 | +| data commits | no conflict; last commit of a key wins. A drop fences an open transaction on that table (404); a rename does not | + +### 4.2 Design: one table per dataset, `orcapod_lease_v1` + +- **Take**: `create_table("orcapod_lease_v1", exist_ok=False)` with one key column named + `own----`. The token is a new UUIDv7 for + each attempt, never reused, not even after a retry, a fork or a restart. The returned **table + id** is the lease. +- **409**: someone holds it. The refusal names the owner text and the table id. No retry loop: + one attempt, refuse at once. +- **Lost reply** (timeout, or the client's own retry got a 409): look the name up. My token in + the key column name: I own it, with that id. Anything else, or nothing, or an error: refuse. A + create that lands after that is a left-behind lease, never a second holder. +- **Before every commit**: look the name up; the id must be mine. Otherwise stop the run. +- **Release**: drop **by id**. 404 is success. An unclear reply: look up, drop the id again if it + is still there; a repeated or late drop of that id cannot touch a newer lease. If it cannot be + settled, the run raises (or adds a note to its own error) with the id to clear. +- **Reuse of the name** after a drop was measured with takeover; P11 repeats it across clients. + +[`lease_model.py`](itl-1446/lease_model.py) visits every interleaving of 2 to 4 writers with +crashes, lost replies, late creates and repeated drops: never two holders. Two holders are reached +in the two variants that break a rule: a live holder's table is cleared, or drops go by name. + +### 4.3 What is guaranteed, and the window that is not + +Two Orcapod runs never both hold one dataset, **if**: + +- L1. the service keeps creation of a name atomic, and a dropped id gone. Measured, not + documented: violations can be found by tests, not excluded. Ask SpiralDB to state it. +- L2. nobody drops or renames the lease table of a live writer. +- L3. every writer takes the lease: this version of Orcapod, in store mode. A program calling + pyspiral, or an older Orcapod, is not stopped. + +There is **no fencing** of data writes: if L2 is broken, the old holder notices at its next commit +check, but a commit already past that check lands. That check is detection, not a guarantee, and +so is the read-back after a commit (section 6.5). + +### 4.4 A crashed holder + +The lease stays. **No age, process id or host makes it expire**: a crash cannot be told from a +pause. A person runs `store.clear_lease(table_id)` with the id from the refusal, after making sure +the process is gone *and* that no request of it is in flight (the message says to wait for the +client's request timeout, P10). It drops exactly that id. Nothing renews or recreates a lease, so a +cleared writer never brings it back. + +### 4.5 Scope: a write session + +A **session** is one run's leases and the state decided under them. The order of a run: + +1. Collect every SpiralDB dataset the run may write: the pipeline and result databases, a pod's + `result_database` and `pod_cache_database`, cached operators', `CachedSource`s', observers'. +2. Take their leases, sorted by (endpoint, project, dataset), **before sources are checked and + before the plan**. If one is refused, release those taken and raise; report a failed release. +3. Drop everything remembered from before: indexes, table handles, "does not exist" answers, the + catalog, and once-per-object flags (`_pipeline_preflight_checked`, `_stale_tables_checked`). + Then check the catalog (5.2). +4. Check sources, plan, compute, deliver, commit: every read that decides work is under the lease. +5. Drain: wait for every task, thread and commit of this run, cancelled ones included (a + cancelled `to_thread` commit still runs). Then the final flush, then release. + +| Case | Rule | +|---|---| +| `job.run()`, `run_async()`, `node.run()` | a session. An unchanged rerun takes it too (about 0.3 s), because whether there is work is decided under it | +| `load_only=True`, `load`, `as_source()`, `head`, `get_*`, `trace`, reads of a held run | no session, **never refused**. They read the pipeline table first and results after, so a record's result is there (results commit first) | +| reading a `CachedSource` outside a run, a standalone tracked side effect | a session of its own, taken before the cache or log is read, or anything delivered. Refused while another run holds the dataset (decision 4); `cached.get_all_records()` is a pure read | +| `add_records` / `flush` by hand | only inside `with store.writing():`. Outside it, refused **before buffering**. At the end of a session the queue is empty: committed, or dropped with an error that counts the rows | +| whose writes are the session's | a context variable, set by the run and copied by Orcapod into its own tasks and threads. A user's thread, or another run on the same object, has none, so its write is refused | +| a user function | runs **without** the variable, so it cannot write with the run's authority. A nested job on the same dataset is refused | +| a task that outlives the run | its session is closed: refused | +| a fork | the session records the process id; a write from another is refused. Ray workers do not write | +| two datasets | both leases. A run sharing either dataset is refused, even if it would write other tables | +| one dataset, two connectors in one run | one lease: the 409's owner text holds this run's own token | +| the same service under two addresses | the second create sees the same name. Recognised by the token within a run, refused between runs | +| the process is killed, or draining fails | the lease stays (4.4) | + +## 5. Tables + +### 5.1 Names + +`op--`, the digest being the 64-hex SHA-256 of the path's compact JSON list (UTF-8, +non-ASCII as itself; a component that is not UTF-8 is refused earlier; `/` and NUL stay refused). +The hint: drop the components that match `([a-z]+:)?[0-9a-f]{64}`, replace every run of characters +outside `[A-Za-z0-9_]` by `_`, join by `_`, cut to 56. At most 124 characters; the limit is 255 on +the table part (Live). Because the hint is part of the name, its rule and the JSON form are frozen +as **store format 1** with test vectors: another rule would look for another name and find nothing. + +The full path includes `base_path`, so `.at()` views agree on a table. The digest is a hash "in a +name" (bare hex), with a row in the hash site inventory. SQLite and PostgreSQL share the old +mapping and its collisions: the code goes in `ConnectorArrowDatabase`, switched on for SpiralDB +only; the others later (their tables would be rebuilt; nobody has any. PostgreSQL's 63 bytes hold +a hint of 27 and 32 hex digits; its long column names stay ITL-1166). + +### 5.2 The catalog, `orcapod_catalog_v1` + +Key `physical_name`; columns `path` (JSON text), `kind`, `store_format`, `state` (`intended`, +`ready`), `table_id`. Written only under the lease. `kind` comes from the path's last component; +nothing is parsed from a name. + +**It fails closed.** A store's dataset holds only store tables, the catalog and the lease. At the +start of every session, and in `list_table_paths`, one listing is compared with the catalog: + +| Found | Meaning | Action | |---|---|---| -| `job/_result/my-fn//v0/...` | `job/_result/my_fn//v0/...` | `job___result__my_fn____v0__...` | -| `job/_result/café//...` | `job/_result/cafè//...` | `job___result__caf_____...` | -| `run-1/add/pdb_v1` | `run_1/add/pdb_v1` (two job names) | `run_1__add__pdb_v1` | -| `a/b__c` | `a__b/c` | `a__b__c` | -| `a_/b` | `a/_b` | `a___b` | -| `1x` | `t_1x` | `t_1x` | - -The first is reachable with the public `function_name` argument, and the two functions need only -the same outputs and major version. Through the prototype, `my_fn` (3x) was given `my-fn`'s (2x) -stored `[0.0, 2.0]` for inputs `[0.0, 1.0]`: a result lookup matches the input hash and the data -context, not the function. On `main` no function table reaches a connector database, so nobody -has been given such a result; the same mapping serves SQLite and PostgreSQL, where it is latent -(decision 6). - -**Length** (Measured): 181 and 182 characters for the function pipeline tables of a job named -`proto` with functions `add` and `mean`, 123 and 124 for their result tables. Limit: 128 (Read, -`spiral/api/types.py`: `TableName`). Whether the server enforces 128 is to probe; the design -stays below it either way. - -### 5.3 The mapping - -Decided (developer, 2026-11-24): a short readable part plus a digest of the full, unsanitised -record path, independent of any lookup; a fixed-name catalog table; nothing is ever parsed out of -a name. - -`op--`: - -- `` is the 64-hex SHA-256 of the compact JSON list of the full path as text: the - database's base path and the record path, each component exact. JSON quoting keeps `["a","b"]` - and `["a/b"]` apart. -- `` is for people: the components without a 64-hex hash, joined by `_`, sanitised as - today, cut to 56 characters. +| nothing at all | a new store | create the catalog (exclusive) | +| tables, no catalog | lost catalog, or a foreign dataset | refuse: `rebuild_catalog()`, or another dataset | +| a table without a row | a lost row, or a foreign table | refuse, naming it | +| a `ready` row without its table, or with another table id | dropped or replaced by hand | refuse: never read as absent. `forget_table(path)` says it is meant | +| an `intended` row | an interrupted creation | finish it (5.3); a reader sees no rows | +| a row for the name with another path | a digest collision | refuse | +| another catalog version, or an unexpected schema | another Orcapod | refuse | -At most 124 characters of `[a-zA-Z0-9_-]`, starting with `o`. The developer gives SpiralDB's limit -as 255; pyspiral's own type says 128 (Read). Names fit both, and P2 settles which the server -applies. A reversible escape instead of a digest cannot fit 128: two path hashes are already 128. +So a stale-layout check never runs on a partial listing: the review showed that a missing row of +an old side-effect log lets a delivery through. For result lookups too, a missing row is an error +in the writer **and** the reader path, never a miss. An access or network failure is an error, +never "absent". -The digest is a new hash site of class "in a name" (bare hex, no label) and gets its row in the -hash site inventory. No existing hash or record path moves. +`rebuild_catalog()` takes the lease, reads every table's manifest, refuses if one is invalid, +repeated, or does not give its own name, writes the rows to a new table, and only then +makes it the catalog; a half-built one is never read. A table whose creation never reached its manifest has no known +path: it is listed for the person to drop. -**Several databases over one connector.** `.at()` views and separate `ConnectorArrowDatabase` -objects use the full path, so `db.at("a")` writing `("b",)` and `db` writing `("a", "b")` are one -table, as on Delta; they share one catalog. Two datasets are two stores. +### 5.3 Creating a table -### 5.4 The catalog, `orcapod_catalog_v1` +Under the lease. The live failure (F4) is a key-only table left by a failed first write. -| Column | Type | Content | +| Step | A crash after it leaves | Recovery by the next session | |---|---|---| -| `physical_name` | text, **key** | the table's name in SpiralDB | -| `path` | text | the exact path, the JSON text the digest is of | -| `kind` | text | `function_pipeline`, `function_result`, `side_effect_log`, `operator_cache`, `cached_source`, or `other`; from the path's last component (its layout), never from the name | -| `store_format` | int32 | the manifest format the table was created with | - -No column starts with `__` or holds `.`. The catalog is written with these fixed types, without -the codec or a manifest, and its schema is checked when opened. A row is a function of its key: -there is no created-at column, so two writers write the same row. - -- **Order.** The catalog row is committed, then the table is created, then its manifest, then - rows. So every store table is in the catalog, and a crash leaves at most a row with no table, - which a listing leaves out. -- **Use.** A table's name is computed, so a read or write needs no lookup to find it. The catalog - is for `list_table_paths`, cleanup, people, and two checks: a row for the name with **another - path** is a digest collision and is refused; a table that exists **without a row** is not ours, - and is neither read nor written (an error naming it, never "no such table", which would - recompute over it). -- **Deletion.** Under the lease: drop the table by id, then delete its row. A crash between - leaves a row with no table. A table dropped by hand reads as absent and is recreated. Offered - as `database.delete_table(path)`; nothing is deleted automatically. -- **A lost catalog.** Every table's manifest also holds its path, so it can be rebuilt: - `rebuild_catalog()`, run by a person, reads each table's metadata once, takes those with a - manifest whose path gives exactly the table's name, and writes the rows. Until then the tables - are refused, not recomputed. When the catalog does not exist, opening the store for writing - looks once at the metadata of the tables there; if any has a manifest it refuses and names - `rebuild_catalog()`, else it creates the catalog. A catalog that lost only some rows shows as - "exists without a row" on use. `list_table_paths` cannot see those tables until the rebuild, so - stale-layout accounting may miss them: a stated limit. -- **Schema version.** In the name. A changed catalog is `orcapod_catalog_v2`, with its own - migration decision; a store that holds a catalog of another version is refused. The manifest and - the lease (`orcapod_lease_v1`, section 6.3) are versioned apart. -- **Cost.** One read a handle at the start of a run (about 300 bytes a table; kept until - `refresh_table`), none per row, one commit per **new** table (five for the prototype's job, first - run only), and nothing on a rerun. `list_table_paths` is this read plus one listing. -- **Scope: one catalog per dataset** (decided, developer, 2026-11-24). A dataset is one - self-contained Orcapod store: its tables, its catalog and its lease. The database sees nothing - of other datasets, and a path names a table within its dataset only. - -### 5.5 What a dataset is, and who may write - -| Question | Answer | Source | -|---|---|---| -| Must a dataset be created first? | **Unknown.** The client has no call that creates one: `create_table("dataset.table")` takes the name, and tables are listed, filtered and moved by it, so it looks implicit. The public documentation does not mention datasets | pyspiral 0.16.33 source; documentation; P13 | -| Dataset name | at most 128 characters, `[a-zA-Z_][a-zA-Z0-9_-]+`, so at least two | pyspiral `api/types.py` | -| Level of permissions | **the project**: "A grant gives one role on one Project to a principal." Roles `viewer`, `editor`, `admin`. Dataset or table grants: not in the documentation, and the client's grant call is on the project only | docs.spiraldb.com, Platform > Access; pyspiral `Projects.grant_role` | -| Roles the store needs | a reader `viewer`, a writer `editor` (create, write, drop): **unknown in detail**. The live test job runs as `editor` | `test_spiraldb_connector_integration.py`; P13 | +| 1. the name is not listed; row `intended`, read back | a row, no table | go on from 2 | +| 2. `create_table(exist_ok=False)` | an empty key-only table | no value columns and no committed write: **drop it by id, create it again** | +| 3. manifest chunks, then header | the same, with a manifest | the same (a manifest of an empty table pins nothing) | +| 4. first rows, one atomic commit; names read back | a whole table | manifest valid and value columns present: go on to 5 | +| 5. row `ready` with the table id | done | - | -So separate datasets do **not** separate permissions: anyone who may write one store of a project -may write all of them, its lease and catalog included. Different writers need different projects. +- Step 2's 409 means the table appeared after step 1's listing. It is never adopted: refuse. +- The drop in recovery is safe only because the row is `intended` (so nobody may have results in + it), the lease is held, and the table has no value columns. A table with value columns and no + valid manifest is refused, never dropped. +- A lost reply at any step is settled by reading back before going on. -The current documentation describes the newer platform (catalog, branches, commits, `spiral-sdk`), -not pyspiral's `dataset.table` model, so it may not apply to this client unchanged. It states -conflict checks that pyspiral does not expose: a commit compares names and versions and fails -with a conflict, and one commit may change several tables of a project. With that client -(ITL-931) the lease could be a conditional publish, and results and records one commit. It states -no read-after-commit guarantee, so C1 is not documented. +Deleting (`delete_table(path)`, by a person, in a session): row to `intended`, drop by id, delete +row. Nothing is deleted automatically. Deleting a result table whose pipeline records remain makes +those records recompute, as on Delta; the method says so and asks for `force`. -### 5.6 Every connector, or SpiralDB only +## 6. Reading and writing -`_path_to_table_name` is shared by all three connectors, so the collisions of 5.2 exist on SQLite -and PostgreSQL too, and PostgreSQL refuses names over 63 bytes (ITL-1162, CA3): a join's operator -cache, 2 hashes in its path, cannot have a name there. +### 6.1 What a run costs today (Fake, prototype's six-step job) -| | SpiralDB connector only | `ConnectorArrowDatabase`, every connector | -|---|---|---| -| Fixes collisions | SpiralDB | all three | -| PostgreSQL table names | no | yes: 63 bytes hold `op--`. 128 bits, and the catalog refuses a collision | -| PostgreSQL operator caches | no | **not by this alone**: its column names are over 63 bytes too (a join's system tags, 148), which is ITL-1166 | -| Needs | a name hook on one connector | the hook, a length limit per connector (SpiralDB 128, PostgreSQL 63 bytes, SQLite none known), a catalog per dataset / schema / file, all in the database layer | -| Catalog write | the order of 5.4 | the same, or one transaction with `CREATE TABLE` on SQL connectors | -| Tests | SpiralDB fake | also SQLite, PostgreSQL (its CI job), every existing name and listing test of the three | -| Existing tables | none: no store table could be written | SQLite and PostgreSQL tables of `ConnectorArrowDatabase` would no longer be found: they have no catalog row. Nobody has any (greenfield, before 0.4.0), so no migration: rebuild. Tables read by a SQL **source** are not affected | - -**Recommended:** the code goes in `ConnectorArrowDatabase`, switched on per connector, and the -first version switches on SpiralDB only. The path digest, the catalog's columns and the crash -order are connector-neutral as designed, so switching on SQLite and PostgreSQL is a later PR that -renames no SpiralDB table. That PR should land before 0.4.0, while nobody has such a store. The -first version does not wait for it. - -## 6. Concurrent writers and failed writes - -SpiralDB upserts by key. The client retries a transaction "after conflicts" (3 times by default) -and reports "failed to commit transaction due to conflict" (Read). What counts as a conflict is -to probe; nothing read suggests that two upserts of one key do. Assume: both commit, the later -commit wins, and no error is raised. - -### 6.1 Is "same id, same content" true? - -| Table | Record id | What a second write of the same id changes | Harmless? | -|---|---|---|---| -| Function result | **random UUIDv7** of the output datagram | cannot happen between writers. Two writers computing one input store **two** rows; a lookup takes the newest `__pod_ts` | yes for storage; both values stay, and a nondeterministic function can then serve either | -| Function pipeline | hash of system tags, input hash, recomputation index | `__data_id`, `__computed`, `__output_data_hash`, `__is_ephemeral`, `__pipeline_run_id`, `__recorded_at` | **no** (below) | -| ... its recomputation index | read, then write | two writers both take index `n`; one recomputation disappears from the history | **no** | -| Side-effect log | hash of the same preimage | `pipeline_run_id`, `executed_at` | the log is, the **delivery is not**: both delivered before either logged | -| Operator cache | hash of the row and node content hash | float bits (below) | yes, up to float bits | -| Cached source | hash of the row with system tags | float bits | yes, up to float bits | - -Every row of a table has the same `__node_content_hash` for one id only where that hash enters -the id: it does for the operator cache. For the pipeline table it is redundant with the path and -system tags by design, so the two writers' values agree unless two nodes share both. - -*Float bits*: the Arrow hash reads `-0.0` as `0.0` and every NaN alike (ITL-1179), so one id can -hold two bit patterns. The stored value is one of them; the same holds on Delta. - -**What an overwritten pipeline record breaks.** Writer A records entry `e` naming result `r_A`, -and its downstream nodes compute from `r_A`. Writer B overwrites `e`, naming `r_B`. Both results -stay, so nothing dangles, but: `trace` of A's downstream rows reaches result `r_A` with no -pipeline entry naming it; the entry's run id and time are B's, so A's run appears to have computed -nothing; and a reader that read `e` before and after sees history change. On Delta the first -committed record stays (insert when not matched), so a record once read never changes. - -### 6.2 What the design promises - -1. **A record id is stored once**, always: it is the table's key. *(holds under any race)* -2. **A pipeline record never names a result that was not stored.** The result table commits first - and `PendingCommit` withholds the records (ITL-1412). Each SpiralDB write is one atomic - transaction. *(holds under any race; needs a live test that a read after a commit sees it, - from another client)* -3. **A failed write leaves no half-written table**: chunks, then header, then rows, and no - rollback. *(holds under any race)* -4. **An existing record is not overwritten by a later run.** `skip_existing` is decided by - `read_by_keys` at the latest version just before the write. *(holds while one writer holds the - store, 6.3)* -5. **A second writer is refused before it computes, delivers or writes anything.** *(holds under - the two conditions of 6.3; not unconditional)* - -### 6.3 The lease: one writer, the second refused - -**What SpiralDB offers** (Read; behaviour to probe): - -| Primitive | Use for a lease | +| Rows | Run | list tables | look up | metadata reads | writes | whole-table scans | +|---|---|---|---|---|---|---| +| 2 | first | 35 | 15 | 5 | 5 | 3 | +| 50 | first | 227 | 15 | 5 | 5 | 3 | +| 50 | unchanged | 10 | 14 | 7 | 0 | 7 | +| 50 | 10 rows added | 48 | 89 | 48 | 5 | 34 | + +Offered by the client (Read): `where=` with comparisons, `in_`, null tests; `to_record_batches( +key_table=)` (sorted, unique keys); `asof`; `last_modified_at`; projection. Not offered: +conditional writes, rows since a version, a transaction over two tables. + +### 6.2 One generation + +A session pins, for each table, `(table id, manifest digest, version V)`. The index scan **and** +the payload reads use `asof=V`. A manifest never changes for an id. Under the lease only this +session changes a table, so V moves only by its own commits: the index is extended by the rows +**actually inserted** (not skipped, not ambiguous) and V is read again. A reader without a lease +pins V once for its read. The version must be exact and never reused for an id: P14. If it is not, +a session reads the latest (safe under the lease) and readers check the version before and after. + +### 6.3 Lookups + +- **Index**, read once per session and table: record id, the columns callers filter by, data + context, and `__pod_ts` for results. A lookup with a constraint on another column loads that + column into the index at the same V. +- **Misses cost no call.** A hit needs its full row. +- **Hits are read in batches.** A node hands over all its inputs' keys before its loop (sync: it + already lists them; async: what the channel holds without waiting, at most 1,000). One + `key_table` read serves up to 10,000 ids: 10,000 warm hits are 1 to 10 scans, not 10,000. + `ResultCache` gets `prefetch(inputs)`; a single `lookup` uses what was prefetched. +- **Side-effect checks**: the log's record ids are one index; a check is a set lookup. The lease + makes it authoritative for the session. +- **Equal `__pod_ts`**: the greater record id (UUIDv7 bytes) wins, on every database. Today the + first row returned wins, which depends on the backend. Decision 5, as it changes Delta's tie. +- **Budget**: 512 MiB of index and prefetched rows per session, counted in Arrow bytes. Over it, a + table falls back to `where=.in_(batch)` for each prefetch batch, never per row. The + earlier 250 bytes a row was not measured; PR 7 measures peak memory. + +### 6.4 The other whole-table reads + +| Read | First version | |---|---| -| conditional write, compare-and-set on rows or metadata | does not exist | -| `last_modified_at`, `asof`, the write-ahead log | shows afterwards that someone wrote: detection only, it stops nothing. (A transaction has a snapshot; nothing read says a commit fails because a key was written since) | -| table metadata | races are documented, so it is not used for the lease | -| `create_table(exist_ok=False)` | may be an atomic test-and-set, if the service makes names unique atomically. Unknown (P11) | -| upsert and `delete_keys` of one row, then a fresh read | **enough**, if a read started after a commit sees it | - -**Claim, then check.** One table `orcapod_lease_v1` per dataset, key `token` (UUIDv7 of one acquisition), -value columns: run id, job name, process id, start time, last renewal. - -1. Commit a row with my token. 2. Read every row, fresh. 3. If mine is the only one, I hold the -store. 4. Otherwise delete my row and refuse, naming the other claim (job, run id, start, -renewal). 5. The holder deletes its own row in a `finally`. - -*Why two cannot hold.* Suppose A and B both hold, with neither's claim removed. A read after its -claim was committed and did not see B, so B's commit came after A's read, and so after A's commit. -B read after its own commit, so B's read sees A, and B does not hold: a contradiction. -[`lease_model.py`](itl-1446/lease_model.py) visits every interleaving of 2, 3 and 4 writers with -crashes at any step: no two holders. It finds two holders in exactly the two variants below. - -**The guarantee is therefore conditional:** - -- **C1: a read started after a commit returned sees that commit, from any client.** P8 tests it. - A test can refute it, not prove it, so it needs SpiralDB's own statement too. With stale reads - the model reaches two holders. If C1 fails but P11 holds, the lease is the creation of one - named table instead; if both fail, what is left is detection (below), and must be called that. -- **C2: nobody clears the claim of a live writer.** SpiralDB has no fencing: a writer that was - cleared and is still alive can commit. It looks its claim up before every commit and stops when - it is gone, but **a window remains** between that check and the commit, and commits already in - flight land. That check is detection, not a guarantee. - -It covers Orcapod versions that take the lease. Another program, or an SDK call by hand, is not -stopped. - -| Case | Behaviour | +| `_fetch_joined_records` (pipeline, then results) | batched: a run asks for its base entry ids, then their result ids, through a new protocol method `get_records_by_column(path, column, values)`, implemented by every database | +| `as_source()`, `get_all_records()`, `trace` | whole, pipeline rows first; that is the request. Result payloads by id | +| `stored_data_contexts`, the data-context check | projection of one column | +| `CachedSource` ids and source-id check | projection of two columns, under the session | +| `CachedSource` rows, `REPLAY` operators | whole: they return every row. **Not bounded** | +| `skip_existing` | the index | +| `_stored_record_count` (at save) | projection with `where` | + +**Cost at 10,000 rows**, from the calls (not measured): each table that gets 10,000 new rows takes +100 commits at `commit_every_rows=100`, each with a lease look-up and a version read: about 300 +calls a table, 1,500 for five. The job suggests a larger `commit_every_rows` on SpiralDB. An +unchanged rerun: the listing and catalog, one index scan a table, and the batched reads. P9 and PR +7 measure calls, bytes, memory and time for: unchanged (same object, rebuilt job), many hits, new +rows, two result databases, and much old history. The issue's "acceptable cost" is judged on those. + +### 6.5 Writes + +- **Insert only.** A row whose id is stored is never overwritten, whatever `skip_duplicates` says, + as Delta's merge does. Under the lease and the index this holds without a window. Equal ids can + hold other float bits (`-0.0`, NaN); the first stored stays, bit for bit. +- **Results before records**, across databases too (`PendingCommits`, ITL-1412), unchanged. +- **A failed commit** keeps its rows queued for a retry in the session, with their guards, schema + checks and skip policy (today `ConnectorArrowDatabase` drops them). An **ambiguous** one is settled by + reading the ids back before a retry; results keep their UUIDs. +- **After a crash** the next session reads what is stored before it treats anything as a miss. +- **Read-back** of pipeline records and side-effect rows after a commit finds an overwrite by a + program outside the lease, and warns. Detection only; other tables have none. +- Run progress is partial: committed batches of a failed run stay. Side effects are at least once: + a crash between delivery and its log row delivers again. + +Why an overwrite of a pipeline record is not harmless (F6): the new record names another result, +run and time, while downstream rows were computed from the first, so `trace` breaks and history +changes. The recomputation index is read, then written, with the same exposure. + +## 7. Hashes, parity, credentials + +- Nothing above the database changes: hashes, record paths, system-tag names, layouts, revisions + and golden values stay; golden `--check` runs in every PR. +- **Parity with Delta** is: equal values, tags, system tags, content hashes, pipeline entry ids + and schemas; sync rows of a run exactly, async and stores as sets. Generated values (result + UUIDs, run ids, timestamps) cannot be equal: they are compared through a one-to-one mapping, and + every reference must resolve. Delta accepts some inputs SpiralDB v1 refuses (schema evolution, + null structs, the refused types). +- **Saved files**: `overrides` is saved only for `server.url`, and only as scheme, host, port and + path. User information, a query or a fragment is refused, in nested and separate databases too. +- **Permissions are per project** (documentation: "A grant gives one role on one Project to a + principal"; pyspiral's grant call agrees). Datasets do not separate writers. Whether a dataset + must be created first, and which role the store needs, is P13. + +## 8. Failure table + +| Failure | Result | |---|---| -| Two starts at the same instant | at most one holds. **Both may be refused** (each sees the other); an acquisition therefore retries up to 3 times with a random wait of 1 to 5 s before refusing. The model shows the both-refused case | -| The claim's commit fails or its reply is lost | nothing has run. The writer tries to delete its token and raises. A claim that lands later is a stale one: others are refused, two never hold | -| A crashed job | its claim stays, and the next run is refused. A crash cannot be told from a pause, a lost network or a suspended laptop from outside, so **no claim ever expires by time**. The holder renews its row's time (about once a minute, at a commit or from a background thread); the refusal shows how old the renewal is, as information | -| Clearing a stale claim | by a person: `database.clear_lease(token)`, with the token from the error. It deletes exactly that row, so clearing twice or late never removes a newer claim. The message says what to check: that the named process no longer runs. Never automatic, not even when the process id looks dead on this machine (containers share hostnames and reuse ids) | -| Separate pipeline and result databases | a run takes the lease of **every** dataset it may write: both databases, a pod's own `result_database` and `pod_cache_database`, a cached operator's, a `CachedSource`'s, an observer's. The refusal is per dataset. Two datasets: the run holds both leases, taken in sorted order; if one is refused the other is released, and another job that shares **either** dataset is refused. A job sharing only the result dataset is refused too, although it would write other tables. Two jobs in disjoint datasets run together | -| One dataset, two connectors or database objects | in one run (its pipeline and result databases, or `at()` views): one lease, recognised by server, project and dataset, not by object. In two runs: the second is refused, also in one process. A connector opened under another server address for the same service is not recognised as the same: it is then refused by its own run's claim, which is safe | -| Several jobs in one process | a claim belongs to a run, not to a process: one after the other works; a second run while the first one runs (threads, `run_async`, a function that runs a job) is refused if it shares a dataset | -| One database object used by two threads | the second run's acquisition is refused. A bare `add_records` by another thread through the same object during a run uses that run's lease: one object has one queue | -| A forked child | refused: the lease records the process id and a write checks it. Ray workers do not write | -| `job.run()`, `run_async()` | after planning, before anything is computed or delivered, and only if a node is to run. (A source check that stores rows, a `CachedSource`'s, takes the lease for its own flush.) An unchanged rerun with nothing to run writes nothing and takes none | -| `node.run()` | the same acquisition, for the nodes its plan runs | -| Writes outside a run (`add_records` and `flush` by hand, a standalone side effect with a store) | the database itself enforces it: a flush without a lease takes one for that flush. So no write path can forget it | -| **Readers** | never refused, and take nothing: `get_*`, `as_source()`, `head`, `trace`, `load`, `load_only=True`, reads of a held run, `SpiralDBTableSource` over a store table. A reader during a run sees committed batches: results first, then records (promise 2) | -| Reading a `CachedSource` | it fetches live rows and **stores** them, so it is a writer. While another run holds the store it is refused, naming the holder (decision 11). `get_all_records()` on it, which reads the cache only, is a reader | - -**Cost**: one commit and one read to take it, one look-up per commit, one commit to release. About -3 to 5 s a run at the times seen live (P9 measures). Permissions: none beyond writing. - -**Detection besides the lease** (also the fallback if C1 and P11 both fail, and then documented as -best effort only): after a commit, the written ids are read back by key and compared with the rows -written. No hidden column is needed: what a second writer changes in a pipeline record -(`__data_id`, `__pipeline_run_id`, `__recorded_at`) and in a side-effect row (`pipeline_run_id`, -`executed_at`) is stored data. A difference raises a warning naming the table and the count. -A later overwrite is missed. **For the other tables there is no detection and none is needed**: a -result's id is a random UUID, and a cache row written twice is the same row up to float bits. - -Follow-up (several writers), not designed here: the key (`__record_id`, writer), which keeps every -writer's row, or a conditional write in `spiral-sdk` (ITL-931). A store made now is rebuilt to -change its key. - -### 6.4 Failed writes - -| Failure | Today | Design | -|---|---|---| -| the write raises, nothing committed | `ConnectorArrowDatabase` **drops** the rows from its queue (`take_ready`, never restored) | restore them (`PendingCommits.restore`) and withdraw their dependents, as Delta does; a later flush retries. A refusal of the rows themselves still drops them | -| the commit is **ambiguous** (committed, but the reply is lost) | as above | results: a retry upserts the same UUIDs, harmless. Pipeline records: a retry is skipped by `skip_existing`. The run still reports failure | -| the result table commits, the pipeline table fails | results without records | the next run finds them by input hash, computes nothing, writes the records | -| a manifest or catalog row without rows | - | inert | -| a side effect was delivered and its log row failed | the row is dropped: delivered again next run | the row stays queued; a crash still delivers again (at least once, as on Delta) | -| interrupted between two tables' commits | - | promise 2; the job reruns | - -Write-size limits and the time of one commit are to probe. `commit_every_rows=100` gives one -commit per table per 100 rows. Orcapod flushes per table, so several node tables are several -transactions; there is no transaction over tables. - -Observers write with `flush=True`, one SpiralDB transaction per event. They stay off a SpiralDB -store by default (give them an in-memory or Delta store) until they batch. - -## 7. Live probes (throwaway tables, agent workload; before PR 3) - -| # | Question | Decides | -|---|---|---| -| P1 | names: each ASCII character and class of 3.1, `ox_` names, 1 to 1,024 characters, case pairs, NFC/NFD pairs; nested field names | 3.1 | -| P2 | table name of 128, 129, 255 and 256 characters, case pair, `-` | 5.3 | -| P3 | the type matrix, physical forms; float bits; `null`; null struct; struct field order | 3.2 | -| P4 | `key_table` with `binary` and `large_binary`, unsorted, repeated, absent ids; 1 to 100,000 ids: time | 4.3 | -| P5 | `where` equality and `in_` on binary; time against a table of 10^3 to 10^6 rows | 4.3 | -| P6 | parallel `set_metadata` of different keys, 50 pairs | 3.3 | -| P7 | two clients write one key at once, 50 pairs: errors, winner; the same with a first write of new columns | 6 | -| P8 | (C1, 1,000 times, two clients in two processes) read after commit from a second client, both at once and after `create_table(exist_ok=True)` raced by two | 6.2 | -| P9 | time of list, look up, metadata, commit (1, 100, 10,000 rows), and of a rerun | 4 | -| P11 | `create_table(exist_ok=False)` of one name by two clients, 50 times: exactly one succeeds? the name's reuse after `drop_table` | 6.3 | -| P12 | the lease itself: two processes claim at once, 50 times; a process killed while holding; `delete_keys` of one token | 6.3 | -| P13 | `create_table` in a dataset that does not exist; what `viewer` and `editor` may do to tables, rows and metadata | 5.5 | -| P10 | duplicate key in one write; a write killed midway | 6.4 | - -## 8. First working version, in order - -The **smallest working version is PRs 1 to 5**. Each is reviewable alone; a job is refused as -today until PR 5. - -| PR | Content | Tests | -|---|---|---| -| 1 | Fake as strict as the client (3.4); the connector refuses what it must (`fixed_size_binary`, `duration`, `null`, table names); `database-types.md` regenerated | each rule, with the native library's text; matrix | -| 2 | `spiral_store` codec: names, types, manifest, as pure functions with no pyspiral | property tests: names (adversarial alphabet, nested), schema round trip over the type matrix, chunk sizes, two manifests | -| 3 | Connector: store tables use the codec; table names and the catalog; null struct refused when added; `ConnectorArrowDatabase` asks the connector for a table's name | matrix on the fake; column order; rows as a set; foreign tables unchanged; a failed first write; two connectors with an injected failure (ITL-1190's interleaving); collisions of 5.2; catalog: crash between each step, lost, partly lost, another version, `.at()` views, a forced digest collision | -| 4 | Lookups (4.3): keyed and `where` reads, the run index, table handles; failed rows restored (6.4) | call counts per run asserted; equivalence with the whole-table path (`test_*_lookup_equivalence`); staleness by a second handle | -| 5 | Job: the lease (6.3) in the database and in `job.run`, `run_async` and `node.run`; refusals removed where covered; the post-commit comparison (pipeline records and side-effect rows); docs (names, other readers, cleanup, permissions, the lease and its two conditions) | the pipeline store suites parametrised over the fake: first run, rerun, added rows, changed version, `run()` and `run_async()`, save and load, `load_only`, `clear_cache`, separate result database, `trace`; a run's rows equal Delta's: sync exactly, async as sets; stores compared as sets of rows; `Batch` over a stored source asserted only for what 3.6 promises. Every table kind. The lease: each row of 6.3's table, on the fake, with two handles and an injected crash between any two steps | -| 6 | Live suite (the existing `spiral-integration` job): PR 5's job, the type matrix, P7, P8, cost printed; every table dropped | live | -| later | batched `_fetch_joined_records`; null structs; observers; maps if P3 refuses; several writers | | - -ITL-1391 (load a saved connector database) and ITL-1381 (read before flush) are needed for save -and load in PR 5; both are in progress. A saved config has no credential today (`to_config`: -project, dataset, `overrides`); `overrides` is free-form client configuration, so PR 5 refuses to -save an override that is not a known non-secret key (`server.url`). +| a second run starts | refused before it reads, computes, delivers or writes | +| the holder crashes | its lease blocks until a person clears it | +| the lease is cleared while alive | detected at the next commit; a commit past the check lands | +| a first write fails or is killed | recovered by the next session (5.3) | +| a commit fails | retried in the session; else the run fails, earlier batches stay | +| catalog lost or partial | refused until rebuilt; no recomputation, no delivery | +| a table dropped by hand | refused until `forget_table` | +| network or access failure | an error, never "absent" | + +## 9. Probes still needed + +| # | Question | +|---|---| +| P1 | names: case and normal-form pairs, alone and as siblings, at depth; each ASCII class; length in characters and bytes | +| P3 | the type matrix in physical form, float bits, `null`, struct order | +| P4, P5 | `key_table` and `where in_`: key type, absent and repeated ids, `asof`; 1 to 100,000 ids | +| P6 | metadata entries: 1 to 130 chunks; read by another client at once | +| P8 | a read after a commit, from a second client (results before records) | +| P9 | time of every call; the runs listed in 6.4 | +| P10 | a write killed midway; duplicate keys in one write; the client's request timeout and retries | +| P11 | the lease across clients: name reuse, lost replies, a paused process, two endpoint addresses | +| P13 | dataset creation; what `viewer` and `editor` may do | +| P14 | `last_modified_at` and `asof`: exact, monotonic, never reused; two commits in one microsecond; after recreation | + +## 10. Pull requests + +A **store mode** switch (`SpiralDBConnector(..., store=True)`) stays private and refuses to open +until PR 8. Leaving jobs refused is not enough, because `ConnectorArrowDatabase` can be written to +directly. **No PR before 8 lets anything write a store table outside tests on the fake and the +throwaway project.** + +| PR | Content | Size | Mergeable alone? | +|---|---|---|---| +| 1 | Fake as strict as the service (names, 255 characters, key-only writes, duplicate keys, struct order, 409s, ids, drops by id); refusals the client confirms; types page regenerated | M | **yes** (a behaviour change of the direct connector, in the changelog) | +| 2 | Codec and manifest as pure functions, with property tests | M | **yes**, unused | +| 3 | `ConnectorArrowDatabase`: failed rows kept, insert only; the `__pod_ts` tie-breaker on every database | S | **yes** | +| 4 | `get_records_by_column` on every database; `_fetch_joined_records` and side-effect checks batched | M | **yes**, helps Delta too; the differential suite must show no change | +| 5 | Lease and sessions | L | inert: merges after 1, used by nothing | +| 6 | Catalog, names, creation and recovery, store reads and writes | L | inert: needs 2, 3, 5; behind the switch | +| 7 | Index, pinned generations, prefetch, budget; cost measured | L | inert: needs 4, 6 | +| 8 | Job integration, `CachedSource`, saved config, docs, **switch on** | L | no: needs all, ITL-1391, ITL-1381, and the gate | +| 9 | The store as an ongoing live job in CI | S | after 8 | + +**Gate for PR 8**, evidence in its PR: P1, P3, P4, P8, P10, P11, P14 answered; live lease races and +first-write kills; the full conformance suite on the fake (first run, rerun, added rows, changed +version, sync, async, save and load, `load_only`, `clear_cache`, separate result database, +`trace`, every table kind, every row of 4.5, 5.2 and 5.3 with a crash between steps) **and** the +same job live; measured costs. Live evidence comes before the switch, not after it. + +Decision 9 of the first draft (the 8 KiB limit for non-store tables) is integration work and gets +its own issue, not PR 2. + +**The first working version excludes**: several writers; null structs; `fixed_size_binary`, +`duration`, `null`, and every type P3 does not prove; non-ASCII names if P1 is not answered; +observers (one commit an event); bounded `CachedSource` and `REPLAY` reads; automatic clearing of +leases; stores shared with other tables in a dataset; SQLite and PostgreSQL names; schema +evolution; `spiral-sdk`; any promise of order. + +**Estimate.** Four L (a few days each, with review rounds), three M, two S; PRs 1 to 4 can go in +parallel, 5 to 8 mostly cannot. A demonstration on the fake is days away; a store fit for real +results is weeks, and the live probes may add to it. ### Decisions for the developer | # | Decision | Recommended | |---|---|---| -| 1 | Where the mapping lives: (a) the store, (b) rename everywhere, (c) mixed | (a) | -| 2 | *Decided: one writer, a second refused.* To confirm: the lease's conditions C1 and C2 are acceptable, and what ships if P8 refutes C1 (named-table lease if P11 holds, else detection only) | lease; do not ship a "refusal" resting on neither | -| 3 | *Decided: no row order is kept or promised; a store is a set of rows (3.6).* | - | -| 4 | *Decided: digest names, and one catalog per dataset.* To note: permissions are per project (5.5) | - | -| 5 | Two different manifests in one table stop the job, rather than one winning | stop | -| 6 | Digest names and the catalog for SQLite and PostgreSQL too (5.6): existing tables there are rebuilt, nobody has any | yes, a later PR before 0.4.0; the first version does not wait | -| 7 | Null structs refused in the first version (a `T \| None` user-class output holding a null) | yes | -| 8 | Observers not on a SpiralDB store at first | yes | -| 9 | The 8 KiB failure of today's Arrow metadata entry on tables that are not store tables: fix now (chunks) or leave | fix in PR 2, same chunk code | -| 10 | Stay on pyspiral 0.16.33 for this (ITL-931 and ITL-1186 later). The codec, manifest and catalog do not depend on the client | yes | -| 11 | A `CachedSource` read while another run holds the store: refuse, or serve live rows without storing | refuse | -| 12 | A crashed job's claim is cleared by a person only, never by age | yes | - -## 9. Not verified here - -- Everything marked "to probe". The fake cannot answer timing, conflicts, visibility or server - limits. -- The prototype maps names and top-level types only, and its job has number and text columns and - UTC timestamps; it runs no logical type. It does not implement the manifest set, the - catalog, the proposed table names or the lookups. -- The async path, save and load, `load_only` and `trace` were not run through the prototype. -- The fake's and the matrix's behaviour for logical types nested at depth was read, not run - through the prototype. +| 1 | Accept the lease's conditions L1 to L3 and the stated window (4.3) | yes, with SpiralDB asked to confirm L1 | +| 2 | A crashed run's lease is cleared by a person only | yes | +| 3 | Value refusals (null struct) come per batch; earlier batches of the run stay | yes | +| 4 | Reading a `CachedSource` outside a run is a write, so it is refused while another run holds the dataset | yes | +| 5 | Equal `__pod_ts`: the greater record id wins, on every database | yes | +| 6 | A store's dataset holds nothing else; an unknown table refuses the store | yes | +| 7 | An unchanged rerun takes the lease too | yes | +| 8 | Hand writes only inside `with store.writing():` | yes | +| 9 | Order of work: correctness gate before the switch, even if the working version is later than hoped | yes | + +## 11. Answers to the review + +| Finding | Answer | +|---|---| +| `E` invertible only on its image; the prototype swaps `a.b` and `ox_a;2Eb` | taken: 3.1, reads by expected names; prototype fixed and checked | +| non-UTF-8 names, duplicate siblings, nested traversal, path components | taken: 3.1 | +| folding can break a single name | taken: 3.1, refuse until P1, then escape; read back the first commit | +| manifest integrity, incomplete chunks, schema pinned by an empty table, typed empty reads | taken: 3.3, 5.3. The grow-only set is dropped: under the lease there is one manifest | +| the row lease: token reuse, missing own row, ghost claims, both refused | taken by replacing it with the named table (4.2); the old model's wrong grant on an empty read is gone with it | +| canonical lease table, aliases, never-reused tokens | taken: 4.2, 4.5 | +| hold until all writes drained; run-scoped owner; threads, forks, flushes by hand | taken: 4.5. The shared-object exception is removed | +| decisions before the lease (source checks, cached indexes) | taken: 4.5, order of a run | +| clear only when quiescent; pid and age only diagnostic; renewals | taken: 4.4; there are no renewals | +| ambiguous delete | taken: 4.2 | +| destructive operations and references across datasets | partly: deletion needs a session on its own dataset and `force`. Refusing to delete a still-referenced result would need a scan of every store that may refer to it, which cannot be known; left to the person | +| catalog race, adoption of a foreign empty table, competing first schemas | taken: 5.2, 5.3; the lease covers the catalog from its first write | +| hint rule must be fixed by format | taken: 5.1 | +| `/` and NUL in components | already refused; kept | +| lost or partial catalog must fail closed, stale layouts and results, readers too | taken: 5.2 | +| losing a physical result table | taken, stricter: refused until `forget_table`, not recomputed | +| generation of index, payload, manifest; version semantics; refresh; own commits | taken: 6.2, P14 | +| a false miss is not only repeated work | taken: decisions are made under the lease at the pinned version | +| 10,000 hits are 10,000 scans; side-effect probes; new constraints | taken: 6.3 | +| tie on `__pod_ts` | taken: 6.3, for every database | +| byte budget; 250 bytes unmeasured | taken: 6.3 | +| remaining whole-table reads | taken: 6.4; `CachedSource` and `REPLAY` rows stay unbounded, stated | +| "none per row", "about 2 per table" unsubstantiated | taken: withdrawn; 6.4 has call estimates and says they are not measured | +| `ox_order`, clocks, high-water mark | no longer applies: no order is kept | +| generated ids differ; what the prototype did not compare | taken: 7 | +| Delta inserts only, the connector overwrites | taken: insert only, 6.5 | +| parent validity, key nullability, fixed-size lists, value-dependent refusal at row 101 | taken: 3.2; fixed-size lists refused until P3 | +| `server.url` can hold secrets | taken: 7 | +| `null`: refused or inferred? | taken: refused in v1, marked as inferred until P3 | +| PR 3 enables writing before the lease; live evidence after the switch | taken: 10 | + +## 12. Not verified here + +- Everything in section 9. The live facts of 4.1 are the live worker's and await its report. +- The prototype maps names and top-level types for a job of numbers, text and UTC timestamps. It + implements no lease, catalog, manifest format, index or batched read, and did not run async, + save and load, `load_only` or `trace`. +- Costs in 6.4 and sizes in 10 are estimates. diff --git a/docs/dev/specs/itl-1446/lease_model.py b/docs/dev/specs/itl-1446/lease_model.py index a015d9062..e232b27f1 100644 --- a/docs/dev/specs/itl-1446/lease_model.py +++ b/docs/dev/specs/itl-1446/lease_model.py @@ -1,73 +1,106 @@ -"""ITL-1446: exhaustive check of the claim-then-check lease (section 6.3). +"""ITL-1446: exhaustive check of the named-table lease (section 4 of the design). -Every interleaving of N writers. A writer: add its claim, read all claims, hold if its own -is the only one, else withdraw; a holder writes twice and releases. A writer may crash after -any step (its claim stays). Two variants show what the rule rests on: ``stale reads`` (the -check may miss the newest claim) and ``cleared while alive`` (a person deletes the claim of -a live holder). +One table name; creating it succeeds for one caller only (atomic, measured live). A writer: +creates; on a lost reply looks the name up and owns the table only when its own token is in +it; writes; drops **its own table id**. Every interleaving, with a crash after any step. + +Variants, each adding one thing: + +* ``late``: a create whose reply was lost may land after the writer looked (a ghost lease). +* ``late_drop``: a drop may be sent again after it already succeeded. +* ``clear``: a person drops the current table's id while its holder is alive (forbidden). +* ``by_name``: drops go by name instead of by id (the rule the design rests on, removed). Run: ``uv run python docs/dev/specs/itl-1446/lease_model.py`` """ from __future__ import annotations -State = tuple[tuple[str, ...], frozenset[int], frozenset[int]] +from typing import NamedTuple + HOLDING = ("hold", "wrote") -def steps(state: State, stale: bool, clear: bool) -> list[State]: - """Every state one step away: writers' phases, claims stored, claims visible.""" - phases, claims, seen = state +class State(NamedTuple): + """Writers' phases, the table's (owner, id) or ``None``, next id, own ids, in flight.""" + + phases: tuple[str, ...] + table: tuple[int, int] | None + next_id: int + ids: tuple[int, ...] + flying: frozenset[int] + + +def steps( + s: State, *, late: bool, late_drop: bool, clear: bool, by_name: bool +) -> list[State]: + """Every state one step away.""" out: list[State] = [] - for i, phase in enumerate(phases): + for i, phase in enumerate(s.phases): - def to( - new: str, c: frozenset[int] = claims, s: frozenset[int] = seen, i: int = i - ) -> State: - return ((*phases[:i], new, *phases[i + 1 :]), c, s) + def to(new: str, i: int = i) -> tuple[str, ...]: + return (*s.phases[:i], new, *s.phases[i + 1 :]) + own = (*s.ids[:i], s.next_id, *s.ids[i + 1 :]) if phase == "start": - # stored at once; visible at once unless reads may be stale - out.append(to("claimed", claims | {i}, seen if stale else seen | {i})) - elif phase == "claimed": - out.append(to("hold" if not (seen - {i}) else "withdraw")) - elif phase == "withdraw": - out.append(to("refused", claims - {i}, seen - {i})) + if s.table is None: + made = s._replace(table=(i, s.next_id), next_id=s.next_id + 1) + out.append(made._replace(phases=to("hold"), ids=own)) + out.append(made._replace(phases=to("unsure"))) # reply lost + else: + out.append(s._replace(phases=to("refused"))) + out.append(s._replace(phases=to("unsure"))) # refusal lost + if late: + out.append(s._replace(phases=to("unsure"), flying=s.flying | {i})) + elif phase == "unsure": + if s.table is not None and s.table[0] == i: + ids = (*s.ids[:i], s.table[1], *s.ids[i + 1 :]) + out.append(s._replace(phases=to("hold"), ids=ids)) + else: + out.append(s._replace(phases=to("refused"))) elif phase == "hold": - out.append(to("wrote")) - elif phase == "wrote": - out.append(to("done", claims - {i}, seen - {i})) + out.append(s._replace(phases=to("wrote"))) + elif phase == "wrote" or (late_drop and phase == "done"): + mine = s.table is not None and (by_name or s.table[1] == s.ids[i]) + out.append(s._replace(phases=to("done"), table=None if mine else s.table)) if phase not in ("start", "refused", "done", "crashed"): - out.append(to("crashed")) - if clear and i in claims: - out.append((phases, claims - {i}, seen - {i})) - if stale and claims - seen: - out.append((phases, claims, claims)) + out.append(s._replace(phases=to("crashed"))) + if i in s.flying: + landed = s._replace(flying=s.flying - {i}) + if s.table is None: + landed = landed._replace(table=(i, s.next_id), next_id=s.next_id + 1) + out.append(landed) + if clear and s.table is not None: + out.append(s._replace(table=None)) return out -def explore(writers: int, *, stale: bool = False, clear: bool = False) -> None: - """Visit every reachable state and report whether two writers ever hold at once.""" - start: State = (("start",) * writers, frozenset(), frozenset()) - visited, queue, broken, all_refused = {start}, [start], False, False +def explore(writers: int, **variant: bool) -> None: + """Visit every reachable state; report two holders at once, and a stuck lease.""" + options = {"late": False, "late_drop": False, "clear": False, "by_name": False} + options.update(variant) + start = State(("start",) * writers, None, 0, (-1,) * writers, frozenset()) + visited, queue, two, stuck = {start}, [start], False, False while queue: - state = queue.pop() - holders = sum(p in HOLDING for p in state[0]) - broken = broken or holders > 1 - all_refused = all_refused or set(state[0]) == {"refused"} - for new in steps(state, stale, clear): + s = queue.pop() + two = two or sum(p in HOLDING for p in s.phases) > 1 + ended = all(p in ("refused", "done", "crashed") for p in s.phases) + stuck = stuck or (ended and not s.flying and s.table is not None) + for new in steps(s, **options): if new not in visited: visited.add(new) queue.append(new) print( - f"{writers} writers, stale reads {stale}, cleared while alive {clear}: " - + f"{len(visited)} states, two holders possible: {broken}, " - + f"all refused possible: {all_refused}" + f"{writers} writers, {', '.join(variant) or 'base'}: {len(visited)} states, " + + f"two holders possible: {two}, a lease left behind possible: {stuck}" ) if __name__ == "__main__": for count in (2, 3, 4): explore(count) - explore(2, stale=True) + explore(3, late=True) + explore(3, late_drop=True) + explore(3, late=True, late_drop=True) explore(2, clear=True) + explore(3, late_drop=True, by_name=True) diff --git a/docs/dev/specs/itl-1446/prototype-output.md b/docs/dev/specs/itl-1446/prototype-output.md index b37c4736b..d01707dee 100644 --- a/docs/dev/specs/itl-1446/prototype-output.md +++ b/docs/dev/specs/itl-1446/prototype-output.md @@ -2,6 +2,7 @@ ```text codec: 200000 distinct names -> 200000 stored names, all decoded +codec: a.b and ox_a;2Eb side by side keep their own values job: first run calls {'add': 6, 'mean': 2, 'notify': 2}, rerun calls {}; rows, schemas, system tags and content hashes equal the in-memory store's order (6 rows): pipeline table equal False, as_source() equal True order (60 rows): pipeline table equal False, as_source() equal True diff --git a/docs/dev/specs/itl-1446/prototype.py b/docs/dev/specs/itl-1446/prototype.py index ca607dcd9..3ff91a648 100644 --- a/docs/dev/specs/itl-1446/prototype.py +++ b/docs/dev/specs/itl-1446/prototype.py @@ -201,11 +201,10 @@ def iter_batches( ) arrays = [] for field in schema: - name = ( - field.name - if field.name in rows.column_names - else encode(field.name) - ) + # The expected stored name, never "whichever is there": a.b is stored + # as ox_a;2Eb, which is also a name a user's column may have. + key = field.name == ConnectorArrowDatabase.RECORD_ID_COLUMN + name = field.name if key else encode(field.name) array = rows.column(name).combine_chunks() target = field.type if pa.types.is_timestamp(target) and target.tz is not None: @@ -321,6 +320,25 @@ def call(self: Any, *a: Any, **k: Any) -> Any: p.stop() +def check_lookalike() -> None: + """A column that looks like another's stored name keeps its own values.""" + with tempfile.TemporaryDirectory() as root, fake_pyspiral.install(root): + connector = MappingConnector("p") + database = ConnectorArrowDatabase(connector) + rows = pa.table( + { + "__record_id": pa.array([b"k"], pa.large_binary()), + "a.b": [1], + "ox_a;2Eb": [2], + } + ) + database.add_records(("t",), rows, record_id_column="__record_id", flush=True) + read = database.get_all_records(("t",)) + assert read is not None + assert read.to_pylist() == [{"a.b": 1, "ox_a;2Eb": 2}], read.to_pylist() + print("codec: a.b and ox_a;2Eb side by side keep their own values") + + def check_job() -> None: """Same rows as in memory; a rerun from a fresh connector calls nothing.""" with tempfile.TemporaryDirectory() as root, fake_pyspiral.install(root): @@ -560,6 +578,7 @@ def run(fn: Any, name: str, db: Any) -> list[float]: if __name__ == "__main__": check_codec() + check_lookalike() check_job() check_order() check_cached_source_order() From 0e746c199a7f5bc0c9d08cba1a0c67bd2726ba4f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 11:32:37 -0800 Subject: [PATCH 8/8] docs(specs): publish SpiralDB store tables by catalog row; second review (ITL-1446) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1446-spiral-columns.md | 773 +++++++++---------- docs/dev/specs/itl-1446/prototype.py | 2 +- docs/dev/specs/itl-1446/publication_model.py | 165 ++++ 3 files changed, 548 insertions(+), 392 deletions(-) create mode 100644 docs/dev/specs/itl-1446/publication_model.py diff --git a/docs/dev/specs/itl-1446-spiral-columns.md b/docs/dev/specs/itl-1446-spiral-columns.md index 30d04a129..d5e21ed56 100644 --- a/docs/dev/specs/itl-1446-spiral-columns.md +++ b/docs/dev/specs/itl-1446-spiral-columns.md @@ -1,39 +1,35 @@ # ITL-1446: storing a pipeline in SpiralDB -Status: **proposal, nothing implemented.** Revised after an independent review that found the -first draft not sound (section 11 answers each finding). Covers ITL-1176, ITL-1164, ITL-1100 and +Status: **proposal, nothing implemented.** Third version, after two independent reviews of it and +a live measurement (section 11 answers the open findings). Covers ITL-1176, ITL-1164, ITL-1100 and ITL-1190. Decided by the developer (2026-11-24): one job at a time, a second writer is refused; every table -kind goes to SpiralDB (function pipeline, function result, operator cache, cached source, -side-effect log); digest table names and one catalog per dataset, so a dataset is one -self-contained store; a store is a **set of rows**, with no row order kept or promised. +kind goes to SpiralDB; one catalog per dataset; a store is a **set of rows**, with no order. -How each statement is known: - -- **Live**: measured on the throwaway project by the live worker, taken as given until its - report; or an earlier session, cited by issue. -- **Fake**: run by the scripts in [`itl-1446/`](itl-1446/) on the disk fake, a model of SpiralDB. -- **Read**: from pyspiral 0.16.33 (Python source, stubs, text of the native library). -- **To probe**: unknown; section 9. +Sources: **Live** (measured with pyspiral 0.16.33 on a throwaway project, one machine, one day), +**Fake** (the scripts in [`itl-1446/`](itl-1446/) on the disk fake), **Read** (pyspiral's source). +Nothing Live is backed by documentation: the public documentation describes the newer, keyless +tables of `spiral-sdk`, and the service warns that an endpoint this client uses is deprecated. ## 1. Summary -A SpiralDB store maps column names and types, and table names, when it writes, and restores them -when it reads (option (a) of section 2). No hash, record path, layout or golden value moves. One -run holds a lease on the dataset; a catalog says which tables are the store's. +The store maps column names and types when it writes and restores them when it reads (option (a), +section 2). No hash, record path, layout or golden value moves. One run holds a lease on the +dataset. A table exists for Orcapod only once the catalog **publishes** it, after its first rows. | # | What the first version must solve | Known | |---|---|---| -| F1 | Table names reach 182 characters and **collide**: `my-fn` and `my_fn` share a result table, and the second is served the first one's results | Fake | -| F2 | `__` columns, dotted names, time zones and logical types are refused: 57 of 153 stored columns ([list](itl-1446/stored-columns.md)) | Fake | -| F3 | Two writers of one key: the last commit wins, silently. No data-commit conflict exists | Live | -| F4 | A first write that fails leaves a key-only table that refuses every later run | Live | -| F5 | Lookups cost a whole-table scan for each new row, and 4 listings for each row | Fake | -| F6 | Result record ids are random; a pipeline record's id does not cover the result it names, so an overwrite is not harmless | Read | -| F7 | Row order is not kept. **Accepted** (section 3.5) | Fake | +| F1 | Table names collide: `my-fn` and `my_fn` share a result table, and the second is served the first one's results. Job and function names over 82 characters break the 255 limit | Fake, Live | +| F2 | 57 of 153 stored columns are refused ([list](itl-1446/stored-columns.md)): `__`, dots, zones, logical types | Fake, Live | +| F3 | Two writers of one key: the last commit wins, silently | Live | +| F4 | A first write that fails or is killed breaks the table for every later run (7 of 7) | Live | +| F5 | One or two whole-table scans and about 4 listings for each new row: 68 s for 100 rows; 1,000 did not finish in 50 min | Live | +| F6 | Result ids are random; a pipeline record's id does not cover the result it names, so an overwrite is not harmless | Read | -**Honest size: about four L of work, not a few days** (section 10), with a narrow first version. +With the mapping done by scripts, a whole pipeline equals Delta at 100, 1,000 and 10,000 rows, and +with a per-run cache 10,000 rows take 351 s, a rerun 21 s (Live; Delta 44 s and 2.4 s). The floor +is the client: **2.5 s for a commit, about 1 s for any scan**. ## 2. Stored columns, and the options @@ -83,71 +79,54 @@ read and write as today. `;` starts an escape of two digits, because a literal `;` is escaped there. Checked on 200,000 adversarial names (Fake). The key column `__record_id` is stored as it is; no `E(c)` starts with `__`. -**Reading never decodes a name.** `E` is invertible only on its image (`ox_order` would decode to -`order`, which is not stored so). The manifest lists each column's logical and stored name, at -every depth; a read looks for exactly the **expected stored name**, and refuses a missing, extra -or repeated one. The earlier prototype looked for the logical name first, and so gave column -`ox_a;2Eb` the values of `a.b`; it is fixed, with a check. - -Refused before anything is written, naming the column: +**Reading never decodes a name.** `E` is invertible only on its image. The manifest lists the +stored name of every column at every depth; a read looks for exactly the **expected stored name** +and refuses a missing, extra or repeated one. -- a name or path component that is not valid UTF-8 (a lone surrogate); -- two siblings of one name, at the top level or among a struct's fields; -- a name over the service's limit, in characters or bytes, once probed. +Refused before anything is written: a name or path component that is not valid UTF-8; two siblings +of one name. Matching uses path components, never joined text. List items and map keys and values +keep Arrow's own field names, restored from the manifest with their metadata. `E` is applied to +struct fields inside lists too, where the service would accept more, so there is one rule. -Matching uses path components, never joined text. List item and map key/value names are Arrow's -own and are not encoded. - -**Case and Unicode folding: a rule that waits for P1, not a guess.** Upper case was kept live -(`B, C, a`, ITL-1367); whether two names that differ only in case or in normal form can be -siblings is unknown. If the service keeps them apart, nothing is added. If it folds or -normalises: names that it would change (even alone) are escaped, by adding exactly those -characters to the escaped set, so stored names are stable under the service and stay distinct. -Until P1 runs, the store refuses non-ASCII names and names with two siblings equal under -`casefold`. In either case the first commit of a table is **read back** and its column names must be -exactly the expected ones; otherwise the write fails and the table stays `intended` (5.3). +Live: the service refuses a `__` or `$` prefix and any `.`, **silently cuts NUL**, refused a +name that is exactly `*`, and kept every other ASCII character, the empty name, emoji, and 4,096 characters. Case pairs and NFC/NFD pairs +stayed apart, so names are stored as code points with no folding rule. The first commit's column +names are read back and must be exactly the expected ones, so a service that starts to fold is +found before the table is published. There is no branch for such a service: it would need a new +store format. ### 3.2 Types -All physical fields are nullable (a null in a non-null struct field is stored as zero, seen live, -ITL-936). Logical nullability is checked on write and read, a child's under its parent's validity; -the key has its own rule: never null. +Physical fields are all nullable (a null in a non-null struct field is stored as zero, ITL-936); +logical nullability is checked on write and read, a child's under its parent's validity. A key is +never null. -| Logical type | Physical | First version | +| Logical type | Physical | v1 | |---|---|---| -| timestamp with a zone, at any depth | the same integers without the zone (zero-copy view) | kept | -| logical type at the top level, a native container (`list[UUID]`, `set[int]`) included | its storage | kept; live when registered, else as field metadata | -| logical type inside a plain list or struct | - | refused (Orcapod refuses it at definition too) | -| text, binary, `large_list`, integer, bool, float32/64, date32, naive timestamp | native | kept once P3 shows it, float bits included | -| struct | encoded field names; SpiralDB sorts fields by name (live, ITL-1367); restored by name in the recorded order | kept | -| a **null struct** | - | refused when the batch is added, before it is buffered | -| `fixed_size_list`, map, `decimal`, `float16`, `date64`, `time` | native | kept only if both the fake and P3 keep it; until then refused | -| `fixed_size_binary`, `duration` | - | refused: pyspiral's own `Schema.from_arrow` raises (Read, offline) | -| `null` | - | refused; only inferred from a native error text, so P3 confirms it | -| renamed map, map field metadata, `interval` | - | refused | - -A data-tag's marker is field metadata, which the manifest keeps at every depth. - -**What "refused before anything is written" means.** A refusal by type or name happens when the -database is attached, or before the first row of the table. A refusal by **value** (a null struct, -a null in a non-null field) happens when that batch is added: batches committed earlier in the run -stay, as results that a rerun reuses. ITL-1446's wording is wider; this narrower promise is -decision 3. +| timestamp (zoned or not), time, duration, at any depth | the integers: `int64`, or `int32` for `time32`. No value is refused, whatever the service does to a temporal type | kept | +| logical type at the top level, native containers included | its storage | kept; live when registered, else field metadata | +| logical type nested in a plain list or struct | - | refused, as at definition | +| `fixed_size_binary[n]` | `large_binary`, width checked on read | kept | +| `null` | native (kept live) or `int8`; one is chosen in PR 2 | kept | +| bool, integers, floats (bit exact), decimals, text, binary, date, lists, lists of lists and of structs, fixed-size lists, maps `key`/`value` | native | kept (all measured) | +| struct | fields come back sorted by name; restored to the recorded order | kept | +| null struct, empty struct, `interval`, renamed map | - | refused; a null struct when its batch is added | +| map whose keys-sorted flag is set | raw pyspiral drops the flag; the manifest restores it | kept once tested | +| user classes, `File`, `Directory`, pandas, Polars, torch values, logical data-tags | their storage, as above | **not measured**: in the gate of PR 8 | + +Other SpiralDB readers see integers for instants; the docs say which unit. + +A refusal by type or name comes when the database is attached. A refusal by **value** comes when +that batch is added; earlier batches of the run stay and a rerun reuses them (decision 3). ### 3.3 The manifest -One manifest per table, written once at creation under the lease, never changed: format version, -record path, kind, and the logical schema (names with stored names, order, types, nullability, -metadata at every depth, in storage form). Chunks `__orcapod_store__//` first, then the -header `__orcapod_store__/`. - -- A read checks the full digest, the chunk count and order, the schema, and that the recorded path - is the one asked for. Chunks without a header are no manifest; two headers are refused. -- It replaces, for store tables, the nullability record and the Arrow metadata entry. The latter - is one entry of at most 8 KiB, above which a write raises today (Fake: 200 columns). -- Schemas are compared field by field at every depth, unknown logical types by name and metadata. -- **A manifest without value columns** (a crash before the first rows) reads as zero rows of the - recorded schema. The key-only table is never scanned, which the service refuses (live, ITL-926). +One per table, written before its first rows and never changed: format version, record path, kind, +attempt token, and the logical schema with stored names, at every depth, in storage form. Chunks +`__orcapod_store__//` first, then the header. A read checks digest, chunks, schema and +path; chunks without a header are no manifest; two headers are refused. It replaces, for store +tables, the nullability record and the single Arrow-metadata entry (which fails above 8 KiB, and +is rewritten on every commit). Metadata writes of different keys in parallel were both kept (Live). ### 3.4 Other programs, pushdown @@ -176,238 +155,264 @@ downstream; adding rows can regroup earlier ones; positional ids over a stored n does not keep append order either. Conformance tests use order-independent jobs and one explicit order-sensitive example. -## 4. The lease +## 4. The lease and the session -### 4.1 What the service gives +### 4.1 One table, created exclusively -| Primitive | Live result | -|---|---| -| `create_table(exist_ok=False)` | an **atomic test-and-set**: 25 rounds of 5 processes, exactly one winner, the others a 409; 0.12 s | -| dropping by table **id** | a late clearer gets a 404 and cannot drop a newer table of that name; takeover 10 of 10 rounds one winner | -| owner text in the key column's name | fits, so the owner is part of the atomic create | -| claim row, then check | works, but about 6 s, and two starts at once are both refused in 45 of 48 | -| data commits | no conflict; last commit of a key wins. A drop fences an open transaction on that table (404); a rename does not | - -### 4.2 Design: one table per dataset, `orcapod_lease_v1` - -- **Take**: `create_table("orcapod_lease_v1", exist_ok=False)` with one key column named - `own----`. The token is a new UUIDv7 for - each attempt, never reused, not even after a retry, a fork or a restart. The returned **table - id** is the lease. -- **409**: someone holds it. The refusal names the owner text and the table id. No retry loop: - one attempt, refuse at once. -- **Lost reply** (timeout, or the client's own retry got a 409): look the name up. My token in - the key column name: I own it, with that id. Anything else, or nothing, or an error: refuse. A - create that lands after that is a left-behind lease, never a second holder. -- **Before every commit**: look the name up; the id must be mine. Otherwise stop the run. -- **Release**: drop **by id**. 404 is success. An unclear reply: look up, drop the id again if it - is still there; a repeated or late drop of that id cannot touch a newer lease. If it cannot be - settled, the run raises (or adds a note to its own error) with the id to clear. -- **Reuse of the name** after a drop was measured with takeover; P11 repeats it across clients. - -[`lease_model.py`](itl-1446/lease_model.py) visits every interleaving of 2 to 4 writers with -crashes, lost replies, late creates and repeated drops: never two holders. Two holders are reached -in the two variants that break a rule: a live holder's table is cleared, or drops go by name. - -### 4.3 What is guaranteed, and the window that is not - -Two Orcapod runs never both hold one dataset, **if**: - -- L1. the service keeps creation of a name atomic, and a dropped id gone. Measured, not - documented: violations can be found by tests, not excluded. Ask SpiralDB to state it. -- L2. nobody drops or renames the lease table of a live writer. -- L3. every writer takes the lease: this version of Orcapod, in store mode. A program calling - pyspiral, or an older Orcapod, is not stopped. - -There is **no fencing** of data writes: if L2 is broken, the old holder notices at its next commit -check, but a commit already past that check lands. That check is detection, not a guarantee, and -so is the read-back after a commit (section 6.5). - -### 4.4 A crashed holder - -The lease stays. **No age, process id or host makes it expire**: a crash cannot be told from a -pause. A person runs `store.clear_lease(table_id)` with the id from the refusal, after making sure -the process is gone *and* that no request of it is in flight (the message says to wait for the -client's request timeout, P10). It drops exactly that id. Nothing renews or recreates a lease, so a -cleared writer never brings it back. - -### 4.5 Scope: a write session - -A **session** is one run's leases and the state decided under them. The order of a run: - -1. Collect every SpiralDB dataset the run may write: the pipeline and result databases, a pod's - `result_database` and `pod_cache_database`, cached operators', `CachedSource`s', observers'. -2. Take their leases, sorted by (endpoint, project, dataset), **before sources are checked and - before the plan**. If one is refused, release those taken and raise; report a failed release. -3. Drop everything remembered from before: indexes, table handles, "does not exist" answers, the - catalog, and once-per-object flags (`_pipeline_preflight_checked`, `_stale_tables_checked`). - Then check the catalog (5.2). -4. Check sources, plan, compute, deliver, commit: every read that decides work is under the lease. -5. Drain: wait for every task, thread and commit of this run, cancelled ones included (a - cancelled `to_thread` commit still runs). Then the final flush, then release. - -| Case | Rule | -|---|---| -| `job.run()`, `run_async()`, `node.run()` | a session. An unchanged rerun takes it too (about 0.3 s), because whether there is work is decided under it | -| `load_only=True`, `load`, `as_source()`, `head`, `get_*`, `trace`, reads of a held run | no session, **never refused**. They read the pipeline table first and results after, so a record's result is there (results commit first) | -| reading a `CachedSource` outside a run, a standalone tracked side effect | a session of its own, taken before the cache or log is read, or anything delivered. Refused while another run holds the dataset (decision 4); `cached.get_all_records()` is a pure read | -| `add_records` / `flush` by hand | only inside `with store.writing():`. Outside it, refused **before buffering**. At the end of a session the queue is empty: committed, or dropped with an error that counts the rows | -| whose writes are the session's | a context variable, set by the run and copied by Orcapod into its own tasks and threads. A user's thread, or another run on the same object, has none, so its write is refused | -| a user function | runs **without** the variable, so it cannot write with the run's authority. A nested job on the same dataset is refused | -| a task that outlives the run | its session is closed: refused | -| a fork | the session records the process id; a write from another is refused. Ray workers do not write | -| two datasets | both leases. A run sharing either dataset is refused, even if it would write other tables | -| one dataset, two connectors in one run | one lease: the 409's owner text holds this run's own token | -| the same service under two addresses | the second create sees the same name. Recognised by the token within a run, refused between runs | -| the process is killed, or draining fails | the lease stays (4.4) | +`create_table("orcapod_lease_v1", exist_ok=False)` is an atomic test-and-set (Live: 25 rounds of 5 +processes, one winner each, 0.12 s; takeover by id 10 of 10). The key column's name holds the +owner: `own----`, written atomically with the create. Releasing is a +drop by **table id** (`core.drop_table`), never by name: `Project.drop_table` looks the name up +again. A drop of a gone id is a 404 and cannot touch a newer lease. -## 5. Tables +- **A claim** is one run's wish to hold one dataset. Its token is fixed for all deliveries of its + create and never used for another claim, also not after a retry of the run, a fork or a restart. +- **Success**: the returned id is the lease. **409, timeout or any unclear answer**: look the name + up and parse the key column exactly. My claim's token, and my claim is still acquiring: mine, + with that id. Another token: refused, naming the owner. Nothing there, or a failed look-up: + refused, as unresolved. No second create is sent for a claim. +- **Before each commit, creation, metadata or catalog write**: the name's id must be mine. +- **Release**: drop by id; 404 is released; an unclear answer is retried with the same id, then + reported with the id. "The name is gone" alone is not taken as proof. -### 5.1 Names +[`lease_model.py`](itl-1446/lease_model.py): no two holders over 2 to 4 writers with crashes, lost +replies, late creates and repeated drops; two holders only if a live lease is cleared, or drops go +by name. It models one delivery of each create. A **replayed** create can land after a release and +leave a ghost lease that blocks the store: no second writer, but a person must clear it. -`op--`, the digest being the 64-hex SHA-256 of the path's compact JSON list (UTF-8, -non-ASCII as itself; a component that is not UTF-8 is refused earlier; `/` and NUL stay refused). -The hint: drop the components that match `([a-z]+:)?[0-9a-f]{64}`, replace every run of characters -outside `[A-Za-z0-9_]` by `_`, join by `_`, cut to 56. At most 124 characters; the limit is 255 on -the table part (Live). Because the hint is part of the name, its rule and the JSON form are frozen -as **store format 1** with test vectors: another rule would look for another name and find nothing. +### 4.2 What is guaranteed -The full path includes `base_path`, so `.at()` views agree on a table. The digest is a hash "in a -name" (bare hex), with a row in the hash site inventory. SQLite and PostgreSQL share the old -mapping and its collisions: the code goes in `ConnectorArrowDatabase`, switched on for SpiralDB -only; the others later (their tables would be rebuilt; nobody has any. PostgreSQL's 63 bytes hold -a hint of 27 and 32 hex digits; its long column names stay ITL-1166). +Two Orcapod runs never both hold a dataset if: **L1** creation of a name is exclusive and ids are +never reused (measured, not documented: ask SpiralDB); **L2** nobody drops or renames a live +holder's lease; **L3** every writer is this Orcapod in store mode, at one address of the service +(another address fails the create, so it is refused, not doubled). -### 5.2 The catalog, `orcapod_catalog_v1` +The check before a write is **detection**. There is no fencing of data: a commit (2.5 s or more) +that passed its check lands. -Key `physical_name`; columns `path` (JSON text), `kind`, `store_format`, `state` (`intended`, -`ready`), `table_id`. Written only under the lease. `kind` comes from the path's last component; -nothing is parsed from a name. +### 4.3 Clearing a crashed holder -**It fails closed.** A store's dataset holds only store tables, the catalog and the lease. At the -start of every session, and in `list_table_paths`, one listing is compared with the catalog: +By a person: `clear_lease(table_id)`. Nothing expires by age, pid or host. **No waiting time is +promised to be enough.** A dead process does not mean a quiet service: a request it sent can still +be carried out, the client gives no operation status, and no server deadline is documented. The +command says what must be known, and what is at stake if it is not: -| Found | Meaning | Action | -|---|---|---| -| nothing at all | a new store | create the catalog (exclusive) | -| tables, no catalog | lost catalog, or a foreign dataset | refuse: `rebuild_catalog()`, or another dataset | -| a table without a row | a lost row, or a foreign table | refuse, naming it | -| a `ready` row without its table, or with another table id | dropped or replaced by hand | refuse: never read as absent. `forget_table(path)` says it is meant | -| an `intended` row | an interrupted creation | finish it (5.3); a reader sees no rows | -| a row for the name with another path | a digest collision | refuse | -| another catalog version, or an unexpected schema | another Orcapod | refuse | +| Must be known | How | +|---|---| +| the process is gone, or will not run again | on its machine | +| none of its requests is still open at the service | **cannot be shown today.** A deadline from SpiralDB would do (ask with L1) | + +| A request of the dead run that lands later | Effect | +|---|---| +| creation, manifest, first rows | an orphan (5.2): never read | +| publication row | two publications of one path: the store refuses, nothing is lost (5.4) | +| a later batch of results or of cache rows | the same ids with the same rows, or ids nobody else has: harmless | +| a later batch of **pipeline records or side-effect log rows** | may replace rows of the same id that a later run wrote. The only silent loss; the read-back (6.4) does not see it | +| the lease's create | a ghost lease | + +Without that knowledge the advice is to use another dataset (a new store) and keep the old one +read-only; readers need no lease. + +### 4.4 The session: admission and drain + +A **session** is a run's claims and the state decided under them. It is an object with a state +(`open`, `closing`, `closed`), a pid, its datasets and lease ids, its own write buffers, and the +set of store operations in progress. + +- **Capability.** A store operation is admitted only with the session's capability, an object the + run gives to its nodes for the run. A context variable merely *finds* the session for internal + code; it grants nothing. Admission checks the state, pid, dataset and lease id, and registers the + operation. +- **User code never has either.** The variable is suspended, and no capability passed, around + function calls, side effects, hooks, observers, executors and their callbacks, user operators and + predicates, and the iteration of user sources. Copies made by `asyncio` tasks, `to_thread` or an + executor are therefore empty. User code may open its own session on a disjoint dataset; on this + one it is refused. +- **Buffers belong to the session.** Another run, thread, task or fork can neither add to them, + flush them, nor clear them. +- **Closing**: (1) stop admission; (2) wait for every registered operation to end, meaning the + thread or request itself, not the awaiter (a cancelled `to_thread` goes on); (3) the closer alone + does the final flush, then compares what it wrote; (4) revoke the capability; (5) release each + lease by id. If (2) or (3) cannot finish, **the lease is kept** and the error says so. + +| Order of a run | | +|---|---| +| 1 | collect the datasets it may write, reading nothing: both databases, pods' own databases, cached operators', `CachedSource`s', observers' | +| 2 | claim them, sorted; one claim each; if one is refused, release the others and raise | +| 3 | forget everything learned before: indexes, handles, "absent" answers, the catalog, `_stale_tables_checked`, `_pipeline_preflight_checked`, rows loaded from the store. Rows a node holds from its own run stay | +| 4 | read the catalog (5.3), check sources, plan, compute, deliver, commit | +| 5 | close | -So a stale-layout check never runs on a partial listing: the review showed that a missing row of -an old side-effect log lets a delivery through. For result lookups too, a missing row is an error -in the writer **and** the reader path, never a miss. An access or network failure is an error, -never "absent". +A `CachedSource` that ingests during a source check is inside the session; a lease or integrity +error there **fails the run** and is never the warning of `SourceCheckFailedWarning`. `load_only` +runs no source check that can write. -`rebuild_catalog()` takes the lease, reads every table's manifest, refuses if one is invalid, -repeated, or does not give its own name, writes the rows to a new table, and only then -makes it the catalog; a half-built one is never read. A table whose creation never reached its manifest has no known -path: it is listed for the person to drop. +| Entry | Rule | +|---|---| +| `job.run`, `run_async`, `node.run` | a session; `node.run` commits in batches as a job does (today one commit a row: 250 s for 20 rows, Live) | +| a `CachedSource` read outside a run; a standalone tracked side effect | its own session, before anything is read or delivered (decision 4) | +| `add_records`, `flush` by hand | only inside `with store.writing():`; refused before buffering elsewhere | +| two datasets | both claims; sharing either is refused | +| one dataset through `at()`, two connectors or objects in one run | one claim, by (address, project, dataset) | +| a second run in the process | refused while the first is open | +| readers: `load`, `load_only`, `as_source`, `head`, `trace`, `get_*` | never wait for or are refused by a lease. They can get a typed error: a store that is damaged, or a table deleted while it is read | + +## 5. Tables -### 5.3 Creating a table +### 5.1 The direction, and how it was judged -Under the lease. The live failure (F4) is a key-only table left by a failed first write. +A table becomes real by one catalog row written **after** its first rows, instead of being +created in place and repaired. Judged with [`publication_model.py`](itl-1446/publication_model.py): +every interleaving of two sessions that may crash at any point, with deletion, and a reader at any +time. -| Step | A crash after it leaves | Recovery by the next session | +| Variant | Result | +|---|---| +| as designed | no false refusal, no partial table read, no published table read as absent | +| a catalog row is lost | refused, never absent | +| the dead run's next request lands later (4.3) | never a wrong answer; "two publications" may need a person | +| the reader does not read the catalog again | a healthy store refuses itself | +| the marker before the row, or the drop before the tombstone | a healthy store refuses itself | + +**It survives, and replaces the earlier state machine.** What it gives up: the physical name is +no longer computed from the path alone. That **changes a developer decision** (a name that needs +no lookup) and is decision 5. The lookup costs one catalog scan a session, which the check needed +anyway. + +### 5.2 Creating + +Each **attempt** makes a new table, `op---`: the hint (path components that +are not `([a-z]+:)?[0-9a-f]{64}`, other characters as `_`, 56 at most), the first 32 hex digits of +the path's SHA-256, a new UUIDv7. At most 125 characters. Hint and digest are for people; nothing +is computed or parsed from a name, so their rule is not frozen. + +| Step | A crash after it leaves | Next session | |---|---|---| -| 1. the name is not listed; row `intended`, read back | a row, no table | go on from 2 | -| 2. `create_table(exist_ok=False)` | an empty key-only table | no value columns and no committed write: **drop it by id, create it again** | -| 3. manifest chunks, then header | the same, with a manifest | the same (a manifest of an empty table pins nothing) | -| 4. first rows, one atomic commit; names read back | a whole table | manifest valid and value columns present: go on to 5 | -| 5. row `ready` with the table id | done | - | - -- Step 2's 409 means the table appeared after step 1's listing. It is never adopted: refuse. -- The drop in recovery is safe only because the row is `intended` (so nobody may have results in - it), the lease is held, and the table has no value columns. A table with value columns and no - valid manifest is refused, never dropped. -- A lost reply at any step is settled by reading back before going on. - -Deleting (`delete_table(path)`, by a person, in a session): row to `intended`, drop by id, delete -row. Nothing is deleted automatically. Deleting a result table whose pipeline records remain makes -those records recompute, as on Delta; the method says so and asks for `force`. +| 1. `create_table(exist_ok=False)` | an empty orphan | a new attempt | +| 2. manifest, chunks then header | an orphan | a new attempt | +| 3. first rows, one commit; names and the ids read back | an orphan **with rows** | a new attempt; those rows are computed again | +| 4. catalog row: **published** | a published table without its marker | opens it, sets the marker | +| 5. marker in the table's metadata | done | - | + +- An orphan is never adopted, reused or dropped automatically. A lost reply at 1 to 3 may also just + abandon the attempt. A first commit that lands late lands in an orphan. +- Step 3's crash loses at most one batch, unread by anyone. For a side-effect log it means those + effects are delivered again: at least once, as for any crash between delivery and its log row. +- Pipeline records are committed only after their result table is **published**. +- A zero-row write is never sent (the native library panics). +- Cost of a new table: about 7 s (create, metadata, commit, read-back, row, marker), once. + +### 5.3 The catalog, `orcapod_catalog_v1` + +Rows are only added: `p:` (path, kind, table id, manifest digest, store format) and +`t:
` (tombstone). A row is never changed or deleted, so a request that lands twice or +late changes nothing already said. A table is **current** when it has a `p` row and no `t` row; its +id and manifest must be the row's. + +| Found | Action | +|---|---| +| no catalog, or a key-only one, and no marked table | an empty store. The lease and the catalog are excluded by their exact names **and** key schemas | +| a control name with another schema, another catalog version | refuse | +| a **marked** table without a row | a lost row: refuse (`rebuild_catalog`) | +| a current row whose table, opened by id, is gone | refuse (`forget_table` writes the tombstone) | +| two current rows of one path | refuse; a person tombstones one | +| an unmarked table without a row | an orphan or another program's: ignored | +| a table with a tombstone | deleted; ignored | + +**Order for a reader** (and a writer's check): catalog, then the listing, then the markers of +listed tables that have no row. On a marked table without a row, or a current row whose table is +gone: read the catalog **once more**, then judge. A row precedes its marker and a tombstone +precedes a drop, so a healthy store never refuses itself; this needs a read to see an earlier +commit from any client, which 4 in section 9 must confirm. A failed call is an error, never +"absent". + +**Cost of the markers.** A metadata read is 0.1 s. Only tables **without a row** are asked, and +only those whose name starts with `op-`, as every marked table's does (a renamed one shows as +"row without its table"). A clean store has none; each orphan costs 0.1 s a session, so the docs +say to drop orphans. The listing is filtered by dataset on the server (0.1 s); the catalog is one +scan (about 1 s). + +**A dataset may hold other tables**, at no cost if their names do not start with `op-`. The +recommendation stays one dataset per store, since permissions are per project and the lease stops +only Orcapod. + +**Not covered**: two faults at once (the row lost while the marker was not yet set): the table is +then ignored and its rows computed again. Recorded as accepted. + +### 5.4 Rebuild and deletion + +- `rebuild_catalog()`, by a person, under the lease: adds the `p` row of every marked table without + one. Adding is idempotent and needs no atomic switch; until it is complete the store refuses as + before. A marked table whose manifest is invalid is listed and the store stays refused. +- `delete_table(path, force=True)`, in a session: tombstone row, a `deleted` entry in the table's + metadata (so a rebuild does not bring it back), drop by id. A crash in between leaves a deleted + table that a later clean-up drops. +- **Deleting is the exception to what readers are promised**: it can remove results that pipeline + records (here or in another dataset) name. A reader in the middle gets `TableDeletedError`; later + the entry recomputes, as on Delta. References are not searched for. +- `orphans()` lists, `drop_orphans(ids)` drops, by id, after the person confirms no run is open and + none was cleared without 4.3's knowledge. ## 6. Reading and writing -### 6.1 What a run costs today (Fake, prototype's six-step job) - -| Rows | Run | list tables | look up | metadata reads | writes | whole-table scans | -|---|---|---|---|---|---|---| -| 2 | first | 35 | 15 | 5 | 5 | 3 | -| 50 | first | 227 | 15 | 5 | 5 | 3 | -| 50 | unchanged | 10 | 14 | 7 | 0 | 7 | -| 50 | 10 rows added | 48 | 89 | 48 | 5 | 34 | +### 6.1 Costs (Live) -Offered by the client (Read): `where=` with comparisons, `in_`, null tests; `to_record_batches( -key_table=)` (sorted, unique keys); `asof`; `last_modified_at`; projection. Not offered: -conditional writes, rows since a version, a transaction over two tables. +Lookup 0.2 s, listing 0.1, metadata 0.1, create 0.13; commit 2.5 s for 1 row, 3.4 for 10,000, 9.6 +for a million; any scan 0.8 to 1.3 s up to 100,000 rows, 3 to 4 s at a million, 2 to 3 times more +after many small commits. `where ==` and `in_` are **no faster than the whole table**; a read by +`key_table` is 1.1 to 1.5 s from 1 to 100,000 keys. So any per-row call is out: one index a table +and run, batched reads, 1,000 rows or more a commit. -### 6.2 One generation +### 6.2 Versions -A session pins, for each table, `(table id, manifest digest, version V)`. The index scan **and** -the payload reads use `asof=V`. A manifest never changes for an id. Under the lease only this -session changes a table, so V moves only by its own commits: the index is extended by the rows -**actually inserted** (not skipped, not ambiguous) and V is read again. A reader without a lease -pins V once for its read. The version must be exact and never reused for an id: P14. If it is not, -a session reads the latest (safe under the lease) and readers check the version before and after. +- **In a session**: the latest, under the lease. Only this session changes its tables, and one lock + a table makes its commit, its index update and its reads one after the other. Nothing is pinned. +- **Without a lease**: a read of one table is **one scan**, which is atomic. Pipeline first, then a + fresh scan of results: stores only gain rows, so every result it names is there (deletion + excepted). A read of several steps of one table needs an exact snapshot; `asof` read old versions + correctly, but `last_modified_at` as an exact, never reused token is unproven (P14). **There is + no before-and-after comparison**: until P14 holds, such reads are done as one scan. +- The index, a column added to it later, and payloads belong to one table id and manifest. ### 6.3 Lookups -- **Index**, read once per session and table: record id, the columns callers filter by, data - context, and `__pod_ts` for results. A lookup with a constraint on another column loads that - column into the index at the same V. -- **Misses cost no call.** A hit needs its full row. -- **Hits are read in batches.** A node hands over all its inputs' keys before its loop (sync: it - already lists them; async: what the channel holds without waiting, at most 1,000). One - `key_table` read serves up to 10,000 ids: 10,000 warm hits are 1 to 10 scans, not 10,000. - `ResultCache` gets `prefetch(inputs)`; a single `lookup` uses what was prefetched. -- **Side-effect checks**: the log's record ids are one index; a check is a set lookup. The lease - makes it authoritative for the session. -- **Equal `__pod_ts`**: the greater record id (UUIDv7 bytes) wins, on every database. Today the - first row returned wins, which depends on the backend. Decision 5, as it changes Delta's tie. -- **Budget**: 512 MiB of index and prefetched rows per session, counted in Arrow bytes. Over it, a - table falls back to `where=.in_(batch)` for each prefetch batch, never per row. The - earlier 250 bytes a row was not measured; PR 7 measures peak memory. - -### 6.4 The other whole-table reads - -| Read | First version | +- **Absent keys are not absent rows.** `key_table` returns a row of nulls for a key that is not + there (Live). Every keyed read selects `__data_context`, never null in any stored table, and drops + rows where it is null; keys are sorted and unique. A returned id is never proof of a commit. The + fake models it. +- **Index**: ids and the filtered columns of the rows this run can need. Candidates from `in_` are + filtered again in Arrow on the exact combination. Pending rows take part as today. +- **Sync**: a node knows all its inputs; hits are read in one `key_table` read for each 10,000. +- **Async**: misses cost nothing (the index). Hits that need a payload wait in a group that closes + at 1,000 rows, 2 s after its first, or at the end of the input, one read at a time for a node. + After **20** groups the node keeps all further hits until its input ends and reads them in + batches of 10,000. So at most 20 + ceil(hits / 10,000) reads a node, whatever the arrival order. + The input channel's limit still applies; a cancelled group drains as 4.4 says. +- **Budget**: 512 MiB a session of *resident* memory, estimated from `row_count_estimate` and + measured bytes a row before anything is loaded, with a factor PR 7 measures (Arrow bytes alone + undercount). Above it: **one** projected scan, streamed, that keeps only rows matching the run's + own keys; an async node first collects its input for that. If the matches themselves exceed it, + the run is refused with the numbers. Never a scan for each batch. +- **Side-effect log**: one index of ids; a delivered row is added when its log row is queued, so a + duplicate within the batch is seen; errors stay per row. +- **Equal `__pod_ts`**: the greater record id wins on every database (decision 6). + +| Other whole-table read | v1 | |---|---| -| `_fetch_joined_records` (pipeline, then results) | batched: a run asks for its base entry ids, then their result ids, through a new protocol method `get_records_by_column(path, column, values)`, implemented by every database | -| `as_source()`, `get_all_records()`, `trace` | whole, pipeline rows first; that is the request. Result payloads by id | -| `stored_data_contexts`, the data-context check | projection of one column | -| `CachedSource` ids and source-id check | projection of two columns, under the session | -| `CachedSource` rows, `REPLAY` operators | whole: they return every row. **Not bounded** | -| `skip_existing` | the index | -| `_stored_record_count` (at save) | projection with `where` | - -**Cost at 10,000 rows**, from the calls (not measured): each table that gets 10,000 new rows takes -100 commits at `commit_every_rows=100`, each with a lease look-up and a version read: about 300 -calls a table, 1,500 for five. The job suggests a larger `commit_every_rows` on SpiralDB. An -unchanged rerun: the listing and catalog, one index scan a table, and the batched reads. P9 and PR -7 measure calls, bytes, memory and time for: unchanged (same object, rebuilt job), many hits, new -rows, two result databases, and much old history. The issue's "acceptable cost" is judged on those. - -### 6.5 Writes - -- **Insert only.** A row whose id is stored is never overwritten, whatever `skip_duplicates` says, - as Delta's merge does. Under the lease and the index this holds without a window. Equal ids can - hold other float bits (`-0.0`, NaN); the first stored stays, bit for bit. -- **Results before records**, across databases too (`PendingCommits`, ITL-1412), unchanged. -- **A failed commit** keeps its rows queued for a retry in the session, with their guards, schema - checks and skip policy (today `ConnectorArrowDatabase` drops them). An **ambiguous** one is settled by - reading the ids back before a retry; results keep their UUIDs. -- **After a crash** the next session reads what is stored before it treats anything as a miss. -- **Read-back** of pipeline records and side-effect rows after a commit finds an overwrite by a - program outside the lease, and warns. Detection only; other tables have none. -- Run progress is partial: committed batches of a failed run stay. Side effects are at least once: - a crash between delivery and its log row delivers again. - -Why an overwrite of a pipeline record is not harmless (F6): the new record names another result, -run and time, while downstream rows were computed from the first, so `trace` breaks and history -changes. The recomputation index is read, then written, with the same exposure. +| `_fetch_joined_records` | by this run's keys, through `get_records_by_column` on every database; its warnings, empty-data handling and recomputation choices unchanged | +| data-context and stale checks, `CachedSource` ids, count at save | one projected scan each | +| `as_source`, `get_all_records`, `trace`, `CachedSource` rows, `REPLAY` | whole, **unbounded**, stated | + +### 6.4 Writes + +- **Insert only**: a stored id is never written again (Delta's rule); answered from the index. +- Results are published and committed before the records that name them, across datasets. +- A failed batch stays queued with its guards and is tried again in the session: the same ids and + rows, so a batch that did land changes nothing. What landed is settled by reading ids back with + 6.3's presence rule; if it cannot be settled the session fails and keeps its lease. +- The read-back of pipeline and log rows after a commit detects an overwrite from outside, not a + later one. +- A crash between a delivery and its log row delivers again. ## 7. Hashes, parity, credentials @@ -418,131 +423,117 @@ changes. The recomputation index is read, then written, with the same exposure. UUIDs, run ids, timestamps) cannot be equal: they are compared through a one-to-one mapping, and every reference must resolve. Delta accepts some inputs SpiralDB v1 refuses (schema evolution, null structs, the refused types). -- **Saved files**: `overrides` is saved only for `server.url`, and only as scheme, host, port and - path. User information, a query or a fragment is refused, in nested and separate databases too. +- **Saved files**: `overrides` is saved only as `server.url`, and only an `https` (or local test) + address of host and port: no user information, path, query or fragment, in nested and separate + databases too. Anything else is refused at save. - **Permissions are per project** (documentation: "A grant gives one role on one Project to a - principal"; pyspiral's grant call agrees). Datasets do not separate writers. Whether a dataset - must be created first, and which role the store needs, is P13. + principal"; pyspiral's grant call agrees). Datasets do not separate writers. A dataset + needs no creation: its first table makes it (Live). What each role may do is not measured. ## 8. Failure table | Failure | Result | |---|---| | a second run starts | refused before it reads, computes, delivers or writes | -| the holder crashes | its lease blocks until a person clears it | -| the lease is cleared while alive | detected at the next commit; a commit past the check lands | -| a first write fails or is killed | recovered by the next session (5.3) | -| a commit fails | retried in the session; else the run fails, earlier batches stay | -| catalog lost or partial | refused until rebuilt; no recomputation, no delivery | -| a table dropped by hand | refused until `forget_table` | -| network or access failure | an error, never "absent" | +| the holder crashes | its lease blocks until a person clears it (4.3) | +| a first write fails, is killed, or lands late | an orphan; the next attempt makes another table | +| a later commit fails | tried again; else the run fails, earlier batches stay, the rerun goes on | +| a catalog row, or the catalog, is lost | refused until rebuilt; nothing recomputed or delivered | +| a table dropped or renamed by hand | refused until `forget_table` | +| network or access failure, or a service the client no longer matches | an error, never "absent" | ## 9. Probes still needed -| # | Question | -|---|---| -| P1 | names: case and normal-form pairs, alone and as siblings, at depth; each ASCII class; length in characters and bytes | -| P3 | the type matrix in physical form, float bits, `null`, struct order | -| P4, P5 | `key_table` and `where in_`: key type, absent and repeated ids, `asof`; 1 to 100,000 ids | -| P6 | metadata entries: 1 to 130 chunks; read by another client at once | -| P8 | a read after a commit, from a second client (results before records) | -| P9 | time of every call; the runs listed in 6.4 | -| P10 | a write killed midway; duplicate keys in one write; the client's request timeout and retries | -| P11 | the lease across clients: name reuse, lost replies, a paused process, two endpoint addresses | -| P13 | dataset creation; what `viewer` and `editor` may do | -| P14 | `last_modified_at` and `asof`: exact, monotonic, never reused; two commits in one microsecond; after recreation | - -## 10. Pull requests - -A **store mode** switch (`SpiralDBConnector(..., store=True)`) stays private and refuses to open -until PR 8. Leaving jobs refused is not enough, because `ConnectorArrowDatabase` can be written to -directly. **No PR before 8 lets anything write a store table outside tests on the fake and the -throwaway project.** - -| PR | Content | Size | Mergeable alone? | -|---|---|---|---| -| 1 | Fake as strict as the service (names, 255 characters, key-only writes, duplicate keys, struct order, 409s, ids, drops by id); refusals the client confirms; types page regenerated | M | **yes** (a behaviour change of the direct connector, in the changelog) | -| 2 | Codec and manifest as pure functions, with property tests | M | **yes**, unused | -| 3 | `ConnectorArrowDatabase`: failed rows kept, insert only; the `__pod_ts` tie-breaker on every database | S | **yes** | -| 4 | `get_records_by_column` on every database; `_fetch_joined_records` and side-effect checks batched | M | **yes**, helps Delta too; the differential suite must show no change | -| 5 | Lease and sessions | L | inert: merges after 1, used by nothing | -| 6 | Catalog, names, creation and recovery, store reads and writes | L | inert: needs 2, 3, 5; behind the switch | -| 7 | Index, pinned generations, prefetch, budget; cost measured | L | inert: needs 4, 6 | -| 8 | Job integration, `CachedSource`, saved config, docs, **switch on** | L | no: needs all, ITL-1391, ITL-1381, and the gate | -| 9 | The store as an ongoing live job in CI | S | after 8 | - -**Gate for PR 8**, evidence in its PR: P1, P3, P4, P8, P10, P11, P14 answered; live lease races and -first-write kills; the full conformance suite on the fake (first run, rerun, added rows, changed -version, sync, async, save and load, `load_only`, `clear_cache`, separate result database, -`trace`, every table kind, every row of 4.5, 5.2 and 5.3 with a crash between steps) **and** the -same job live; measured costs. Live evidence comes before the switch, not after it. - -Decision 9 of the first draft (the 8 KiB limit for non-store tables) is integration work and gets -its own issue, not PR 2. - -**The first working version excludes**: several writers; null structs; `fixed_size_binary`, -`duration`, `null`, and every type P3 does not prove; non-ASCII names if P1 is not answered; -observers (one commit an event); bounded `CachedSource` and `REPLAY` reads; automatic clearing of -leases; stores shared with other tables in a dataset; SQLite and PostgreSQL names; schema -evolution; `spiral-sdk`; any promise of order. - -**Estimate.** Four L (a few days each, with review rounds), three M, two S; PRs 1 to 4 can go in -parallel, 5 to 8 mostly cannot. A demonstration on the fake is days away; a store fit for real -results is weeks, and the live probes may add to it. +| # | Question | Gate of | +|---|---|---| +| 1 | L1 and the request deadline, asked of SpiralDB; which client and endpoints are supported, and for how long (ITL-931) | 6 to 8 | +| 2 | types not measured (3.2), through the codec | 8 | +| 3 | replayed creates, two addresses, a paused process; id reuse | 5 | +| 4 | a read after a commit from another process, also for catalog rows and markers | 6 | +| 5 | a kill **after** the commit point; a late commit into an orphan | 6 | +| 6 | P14: an exact snapshot token | optional in 7 | +| 7 | keyed reads: presence column, projection without the key, 1 to 100,000 | 7 | +| 8 | memory and time: unchanged, many hits, added rows, large history, two databases, `node.run` | 7, 8 | +| 9 | roles: what viewer and editor may do | 8 | + +## 10. Pull requests and gates + +| PR | Size | May start now? | Not before | Evidence to merge | +|---|---|---|---|---| +| 1 Fake as strict as measured (absent keys, empty-write panic, ids, 409s, sorted structs, NUL, 255); confirmed refusals | M | **yes** | - | each rule cites its measurement; direct-connector changes in the changelog | +| 2 Codec and manifest, pure | M | **yes** | freezing the stored format: after its own review | property tests; type matrix round trip; format vectors | +| 3 Failed rows kept in the queue; a table with only key columns reads as having no rows | S | **yes**, for today's connectors | insert only for direct connectors; the `__pod_ts` tie: decision 6 | current-backend differential tests | +| 4 `get_records_by_column` on every database; batched fetch | M | **yes** | SpiralDB keys, async groups (PR 7); reordering side effects | each backend and wrapper against its whole-table read: empty, missing table, pending, duplicates, aliases, contexts, errors, warnings, empty data; whole-job differential | +| 5 Lease and session, inert | L | **yes**: one dataset, on a fake | `clear_lease`, two datasets, job wiring | model; every row of 4.4's rules, cancellation and threads included; probe 3 | +| 6 Publication, catalog, store reads and writes | L | state-machine tests only | probes 1, 4, 5; decision 5; PRs 2, 3, 5 | a crash between every two steps; rebuild stopped midway; a reader at each step, on the fake and live | +| 7 Index, groups, budget | L | pure fixtures and probes only | PRs 4, 6; probe 7 | call counts, worst async arrival order, memory | +| 8 Jobs, `CachedSource`, `node.run`, saved config, docs, **switch on** | L | no | all of the above, probes 2, 8, 9, ITL-1391, ITL-1381 | the conformance suite on the fake **and** live, every kind, sync and async; measured cost accepted | +| 9 Ongoing live job | S | the harness only | PR 8 | - | + +The store switch stays private and off until PR 8. Directly mergeable and useful alone: 1, 2 +(unused), 3, 4. Merged but unreachable: 5, 6, 7. + +**The first working version excludes**: several writers; safe clearing without 4.3's knowledge; +null and empty structs; observers; bounded `CachedSource` and `REPLAY` reads; stores at two +addresses; SQLite and PostgreSQL names; schema evolution; `spiral-sdk`; any order. + +**Size**: four L, three M, two S. PRs 1 to 5 can start now, in parallel; 6 to 8 follow each other. A +demonstration on the fake is days away, a store for real results weeks. The client's deprecation +is the largest risk: decision 1 comes before PR 6. ### Decisions for the developer | # | Decision | Recommended | |---|---|---| -| 1 | Accept the lease's conditions L1 to L3 and the stated window (4.3) | yes, with SpiralDB asked to confirm L1 | -| 2 | A crashed run's lease is cleared by a person only | yes | -| 3 | Value refusals (null struct) come per batch; earlier batches of the run stay | yes | -| 4 | Reading a `CachedSource` outside a run is a write, so it is refused while another run holds the dataset | yes | -| 5 | Equal `__pod_ts`: the greater record id wins, on every database | yes | -| 6 | A store's dataset holds nothing else; an unknown table refuses the store | yes | -| 7 | An unchanged rerun takes the lease too | yes | -| 8 | Hand writes only inside `with store.writing():` | yes | -| 9 | Order of work: correctness gate before the switch, even if the working version is later than hoped | yes | - -## 11. Answers to the review +| 1 | Build on pyspiral, deprecated endpoints included, or wait for a service contract (ITL-931) | start 1 to 5 now; decide before 6 | +| 2 | Accept L1 to L3, clearing by a person only, and 4.3's stated risk | yes, and ask SpiralDB for L1 and a deadline | +| 3 | A refusal by value comes with its batch; earlier batches stay | yes | +| 4 | A `CachedSource` read outside a run is a write | yes | +| 5 | Names with a token per attempt, found through the catalog, instead of a computed name | yes: it removes recovery | +| 6 | Equal `__pod_ts`: the greater record id, on every database | yes | +| 7 | An unchanged rerun takes the lease; hand writes only in `with store.writing():` | yes | +| 8 | Reads by `REPLAY` and `CachedSource` stay unbounded in v1 | yes | + +## 11. Answers to the second review + +Findings of the first review that the second calls resolved are kept as they were. | Finding | Answer | |---|---| -| `E` invertible only on its image; the prototype swaps `a.b` and `ox_a;2Eb` | taken: 3.1, reads by expected names; prototype fixed and checked | -| non-UTF-8 names, duplicate siblings, nested traversal, path components | taken: 3.1 | -| folding can break a single name | taken: 3.1, refuse until P1, then escape; read back the first commit | -| manifest integrity, incomplete chunks, schema pinned by an empty table, typed empty reads | taken: 3.3, 5.3. The grow-only set is dropped: under the lease there is one manifest | -| the row lease: token reuse, missing own row, ghost claims, both refused | taken by replacing it with the named table (4.2); the old model's wrong grant on an empty read is gone with it | -| canonical lease table, aliases, never-reused tokens | taken: 4.2, 4.5 | -| hold until all writes drained; run-scoped owner; threads, forks, flushes by hand | taken: 4.5. The shared-object exception is removed | -| decisions before the lease (source checks, cached indexes) | taken: 4.5, order of a run | -| clear only when quiescent; pid and age only diagnostic; renewals | taken: 4.4; there are no renewals | -| ambiguous delete | taken: 4.2 | -| destructive operations and references across datasets | partly: deletion needs a session on its own dataset and `force`. Refusing to delete a still-referenced result would need a scan of every store that may refer to it, which cannot be known; left to the person | -| catalog race, adoption of a foreign empty table, competing first schemas | taken: 5.2, 5.3; the lease covers the catalog from its first write | -| hint rule must be fixed by format | taken: 5.1 | -| `/` and NUL in components | already refused; kept | -| lost or partial catalog must fail closed, stale layouts and results, readers too | taken: 5.2 | -| losing a physical result table | taken, stricter: refused until `forget_table`, not recomputed | -| generation of index, payload, manifest; version semantics; refresh; own commits | taken: 6.2, P14 | -| a false miss is not only repeated work | taken: decisions are made under the lease at the pinned version | -| 10,000 hits are 10,000 scans; side-effect probes; new constraints | taken: 6.3 | -| tie on `__pod_ts` | taken: 6.3, for every database | -| byte budget; 250 bytes unmeasured | taken: 6.3 | -| remaining whole-table reads | taken: 6.4; `CachedSource` and `REPLAY` rows stay unbounded, stated | -| "none per row", "about 2 per table" unsubstantiated | taken: withdrawn; 6.4 has call estimates and says they are not measured | -| `ox_order`, clocks, high-water mark | no longer applies: no order is kept | -| generated ids differ; what the prototype did not compare | taken: 7 | -| Delta inserts only, the connector overwrites | taken: insert only, 6.5 | -| parent validity, key nullability, fixed-size lists, value-dependent refusal at row 101 | taken: 3.2; fixed-size lists refused until P3 | -| `server.url` can hold secrets | taken: 7 | -| `null`: refused or inferred? | taken: refused in v1, marked as inferred until P3 | -| PR 3 enables writing before the lease; live evidence after the switch | taken: 10 | +| 1 exclusion holds under its conditions; drop by id | kept; 4.1 | +| 2 claim, delivery and alias are different things | taken: 4.1, one claim, no second create; aliases refused | +| 3 a timeout is not quiescence; replayed creates | taken: 4.3 promises nothing and lists what each late request does | +| 4 a context variable propagates | taken: 4.4, a locator only, suspended around user code | +| 5 admission and drain barrier | taken: 4.4 | +| 6 collecting datasets, invalidation, `load_only`, swallowed errors | taken: 4.4 | +| 7 lease-only bootstrap | taken: 5.3, exact control tables | +| 8 a healthy store refuses itself | taken: 5.3's order, modelled with and without it | +| 9 one state for creating and deleting | taken: no states; rows only added, tombstones apart; a table is never adopted | +| 10 automatic drop in recovery | taken: there is no recovery and no automatic drop | +| 11 deletion against readers' promise | taken: 5.4 states the exception | +| 12 one generation; split stores | taken: 6.2, latest under the lease, or one scan; results after records | +| 13 before-and-after comparison | taken: removed | +| 14 absent-key rows | taken: 6.3 | +| 15 async batching; pairs of `in_` | taken: 6.3, bounded at 20 + ceil(hits / 10,000), exact match again | +| 16 over budget | taken: 6.3, one scan or a refusal | +| 17 oracle for PR 4 | taken: section 10 | +| 512 nested names, list items, empty structs | taken: 3.1, 3.2 | +| 513 folding branch | taken: removed; the measured domain, checked by reading back | +| 514 empty-manifest recovery | taken: no longer exists | +| 516, 517, 519 | as 2, 4, 5, 3 | +| 521 references | partly: the exception is stated; no search for references, which may be in datasets the person cannot read | +| 522, 526 | as 9 and 10 | +| 525 | as 7 and 8 | +| 527, 528 | as 12, 13, 14 | +| 529, 531, 533 | as 14, 15, 16; call counts are claimed only as 6.3's bound | +| 538 path in a saved address | taken: 7, no path | +| 539 `null` column | taken: 3.2, measured as kept | ## 12. Not verified here -- Everything in section 9. The live facts of 4.1 are the live worker's and await its report. -- The prototype maps names and top-level types for a job of numbers, text and UTC timestamps. It - implements no lease, catalog, manifest format, index or batched read, and did not run async, - save and load, `load_only` or `trace`. -- Costs in 6.4 and sizes in 10 are estimates. +- The live facts are another worker's, from one machine on one afternoon with other probes + running. Section 9 is open. +- The models assume an atomic namespace, ids never reused, and reads that see earlier commits. + They do not model replayed creates or draining. +- The prototype implements names and top-level types only. +- The numbers in 6.3 (20 groups, 2 s, 512 MiB) are proposals to be measured. diff --git a/docs/dev/specs/itl-1446/prototype.py b/docs/dev/specs/itl-1446/prototype.py index 3ff91a648..aad2d7210 100644 --- a/docs/dev/specs/itl-1446/prototype.py +++ b/docs/dev/specs/itl-1446/prototype.py @@ -503,7 +503,7 @@ def today(path: tuple[str, ...]) -> str: def proposed(path: tuple[str, ...]) -> str: - """The proposed name (section 5.3 of the design).""" + """A digest name, to show that colliding paths get different ones (illustrative).""" import json import re diff --git a/docs/dev/specs/itl-1446/publication_model.py b/docs/dev/specs/itl-1446/publication_model.py new file mode 100644 index 000000000..de7098cb9 --- /dev/null +++ b/docs/dev/specs/itl-1446/publication_model.py @@ -0,0 +1,165 @@ +"""ITL-1446: exhaustive check of publishing a table by its catalog row (section 5). + +One record path, two sessions one after the other (the lease), each creating its own table +when nothing is published. A session: create, commit first rows, publish (a catalog row), +mark the table; then perhaps tombstone (a row) and drop. The catalog only gains rows. A +session may crash at every point. + +A reader without a lease runs at any time: read the catalog; list the tables; read each +table's marker; on a marked table with no row, or a row whose table is gone, read the +catalog once more; then decide ``absent``, ``published`` or ``refuse``. + +Variants: ``late`` (the crashed session's next request may land at any later time, so the +lease was cleared before the service was quiet), ``lose`` (a publication row disappears), +``noreread`` (the reader does not read again), ``markfirst`` (the marker precedes the row), +``dropfirst`` (the drop precedes the tombstone). + +Run: ``uv run python docs/dev/specs/itl-1446/publication_model.py`` +""" + +from __future__ import annotations + +from typing import NamedTuple + +FS = frozenset[int] +NONE: FS = frozenset() + + +class S(NamedTuple): + """The service, the running session, requests in flight, and one reader.""" + + tables: FS = NONE # tables that exist + rows: FS = NONE # tables whose first rows are committed + marked: FS = NONE + pub: FS = NONE + tomb: FS = NONE + session: int = 0 + step: int = 0 # 0 not started; index into the program; -1 ended + flying: frozenset[tuple[str, int]] = frozenset() + complete: FS = NONE # marked by a session that was told so, and not deleted + lost: FS = NONE # publication rows taken away + rphase: str = "idle" + c_pub: FS = NONE + c_tomb: FS = NONE + listed: FS = NONE + r_marked: FS = NONE + r_todo: FS = NONE + r_complete: FS = NONE # complete before the read began + late_seen: bool = False + + +def program(options: frozenset[str]) -> list[str]: + """The session's requests, in order.""" + first = ["mark", "publish"] if "markfirst" in options else ["publish", "mark"] + last = ["drop", "tombstone"] if "dropfirst" in options else ["tombstone", "drop"] + return ["create", "commit", *first, *last] + + +def apply(s: S, op: str, i: int) -> S: + """The service carries out one request of session ``i``.""" + one = frozenset({i}) + if op == "create": + return s._replace(tables=s.tables | one) + if op == "commit": + return s._replace(rows=s.rows | (one & s.tables)) + if op == "publish": + return s._replace(pub=s.pub | one) + if op == "mark": + return s._replace(marked=s.marked | (one & s.tables)) + if op == "tombstone": + return s._replace(tomb=s.tomb | one, complete=s.complete - one) + return s._replace(tables=s.tables - one, complete=s.complete - one) + + +def writer(s: S, options: frozenset[str]) -> list[S]: + """What the session does next.""" + if s.session > 1: + return [] + ops = program(options) + over = s._replace(session=s.session + 1, step=0) + if s.step == 0 and s.pub - s.tomb: + return [over] # already published, refused, or opened: creates nothing + if s.step == 0 and s.marked - s.pub - s.tomb: + return [over] # a marked table without its row: refuses + out = [over] # ends or crashes here + if s.step < len(ops): + op, i = ops[s.step], s.session + done = apply(s, op, i)._replace(step=s.step + 1) + if s.step == 3: + done = done._replace(complete=done.complete | {i}) + out.append(done) + if "late" in options: + out.append(over._replace(flying=s.flying | {(op, i)}, late_seen=True)) + return out + + +def reader(s: S, options: frozenset[str], bad: set[str]) -> list[S]: + """What the reader does next; a wrong verdict is added to ``bad``.""" + again = "noreread" not in options + if s.rphase == "idle": + return [ + s._replace(rphase="list", c_pub=s.pub, c_tomb=s.tomb, r_complete=s.complete) + ] + if s.rphase == "list": + return [s._replace(rphase="marks", listed=s.tables, r_todo=s.tables)] + if s.rphase == "marks": + if s.r_todo: + t = min(s.r_todo) + found = frozenset({t}) & s.marked & s.tables + return [s._replace(r_todo=s.r_todo - {t}, r_marked=s.r_marked | found)] + odd = (s.r_marked - s.c_pub - s.c_tomb) | (s.c_pub - s.c_tomb - s.listed) + if odd and again: + return [s._replace(rphase="judge", c_pub=s.pub, c_tomb=s.tomb)] + return [s._replace(rphase="judge")] + if s.rphase == "judge": + live = s.c_pub - s.c_tomb + refuse = bool(s.r_marked - s.c_pub - s.c_tomb) or len(live) > 1 + # A row's table is opened by its id now; gone means the catalog is read again. + gone = live - s.tables + if gone and (not again or gone - s.tomb): + refuse = True + if gone and not refuse: + live -= gone + verdict = "refuse" if refuse else "published" if live else "absent" + if verdict == "refuse" and not s.lost and not s.late_seen: + bad.add("a healthy store refused") + if verdict == "absent" and s.r_complete & s.complete: + bad.add("a completed table read as absent") + if live - s.rows and verdict == "published": + bad.add("a table without its first rows read as published") + if verdict == "refuse" and s.late_seen and not s.lost: + bad.add("(late only) refused, for a person to resolve") + return [s._replace(rphase="done")] + return [] + + +def explore(*names: str) -> None: + """Visit every reachable state of one variant and print what was found.""" + options = frozenset(names) + visited, queue, bad = {S()}, [S()], set[str]() + while queue: + s = queue.pop() + new = writer(s, options) + reader(s, options, bad) + for op, i in s.flying: + new.append(apply(s, op, i)._replace(flying=s.flying - {(op, i)})) + if "lose" in options: + new += [ + s._replace(pub=s.pub - {i}, lost=s.lost | {i}) + for i in s.pub & s.complete + if not s.lost + ] + for n in new: + if n not in visited: + visited.add(n) + queue.append(n) + print(f"{', '.join(names) or 'base'}: {len(visited)} states; {sorted(bad) or 'ok'}") + + +if __name__ == "__main__": + explore() + explore("lose") + explore("late") + explore("late", "lose") + explore("noreread") + explore("markfirst") + explore("dropfirst")