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..d5e21ed56 --- /dev/null +++ b/docs/dev/specs/itl-1446-spiral-columns.md @@ -0,0 +1,539 @@ +# ITL-1446: storing a pipeline in SpiralDB + +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; one catalog per dataset; a store is a **set of rows**, with no order. + +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 + +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 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 | + +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 + +[`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 | +|---|---|---|---| +| 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 | + +**(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 + +### 3.1 Names + +`E(c)`, the stored name of a value column, or of a struct field among its siblings: + +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 | +|---|---| +| `x`, `_source_x`, `_tag_source_id::`, `a;b`, `a;2Eb`, `é` | unchanged | +| `__data_context` | `ox___data_context` | +| `a.b` | `ox_a;2Eb` | +| `ox_a;2Eb` | `ox_ox_a;3B2Eb` | +| the empty name | `ox_` | + +**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 `__`. + +**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. + +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. + +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 + +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 | v1 | +|---|---|---| +| 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 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 + +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): + +| 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 | + +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. + +## 4. The lease and the session + +### 4.1 One table, created exclusively + +`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. + +- **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. + +[`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. + +### 4.2 What is guaranteed + +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). + +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. + +### 4.3 Clearing a crashed holder + +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: + +| 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 | + +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. + +| 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.1 The direction, and how it was judged + +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. + +| 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. `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 Costs (Live) + +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 Versions + +- **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 + +- **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` | 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 + +- 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 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. 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 (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 | 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 | 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 | +|---|---| +| 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 + +- 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/lease_model.py b/docs/dev/specs/itl-1446/lease_model.py new file mode 100644 index 000000000..e232b27f1 --- /dev/null +++ b/docs/dev/specs/itl-1446/lease_model.py @@ -0,0 +1,106 @@ +"""ITL-1446: exhaustive check of the named-table lease (section 4 of the design). + +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 + +from typing import NamedTuple + +HOLDING = ("hold", "wrote") + + +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(s.phases): + + 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": + 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(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(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, **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: + 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, {', '.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(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 new file mode 100644 index 000000000..d01707dee --- /dev/null +++ b/docs/dev/specs/itl-1446/prototype-output.md @@ -0,0 +1,55 @@ +# Prototype output (generated: `PYTHONPATH=. uv run python docs/dev/specs/itl-1446/prototype.py`) + +```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 +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 | +|---|---|---|---|---|---|---|---|---| +| 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..aad2d7210 --- /dev/null +++ b/docs/dev/specs/itl-1446/prototype.py @@ -0,0 +1,588 @@ +"""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, DerivedSource +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 CacheMode, 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: + # 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: + 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_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): + 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_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( + "\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: + """A digest name, to show that colliding paths get different ones (illustrative).""" + 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_lookalike() + check_job() + check_order() + check_cached_source_order() + check_positional_ids() + check_cost() + check_names() + check_wrong_result() 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") 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()