Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
4435570
chore: merge main into SpiralDB cost work
eywalker Dec 3, 2026
b7d7355
perf(spiraldb): check the writer lease on its first write
eywalker Dec 3, 2026
1d7af35
perf(spiraldb): index stored side-effect completions once per execution
eywalker Dec 3, 2026
eb0be80
perf(spiraldb): reuse the writer lease key index at flush
eywalker Dec 3, 2026
723cbf4
perf(spiraldb): release a claim without scanning its state
eywalker Dec 3, 2026
fd3f701
perf(spiraldb): share stale-table discovery across a run
eywalker Dec 3, 2026
4d2b272
perf(spiraldb): mark tables after their first successful append
eywalker Dec 3, 2026
1096bf2
perf(spiraldb): batch function result commits during node runs
eywalker Dec 3, 2026
6aeaf09
perf(spiraldb): use table IDs after name resolution
eywalker Dec 3, 2026
b71d942
fix(spiraldb): copy nested Arrow buffers before appending
eywalker Dec 3, 2026
48aa8c8
fix(spiraldb): keep run lookup capabilities independent of database i…
eywalker Dec 3, 2026
1c7e530
fix(spiraldb): keep run-shared state coherent and node batching to Sp…
eywalker Dec 3, 2026
cb56f9f
fix(spiraldb): list a table after an ambiguous first append
eywalker Dec 3, 2026
86b7d13
docs(spiraldb): state which accepted rows an ambiguous batch reply le…
eywalker Dec 3, 2026
11efa83
perf(spiraldb): find the newest writer lease generation from one data…
eywalker Dec 3, 2026
d382892
perf(spiraldb): keep what a run read under its writer lease
eywalker Dec 3, 2026
2deae0f
feat(spiraldb): take the writer lease at a run's first write (ITL-1900)
eywalker Dec 3, 2026
e82c9f2
perf(spiraldb): skip a lease verification made within 60 seconds (ITL…
eywalker Dec 3, 2026
e5d2956
perf(spiraldb): list a dataset once per run (ITL-1899)
eywalker Dec 3, 2026
c482765
fix(spiraldb): address the review of the lazy writer lease (ITL-1899)
eywalker Dec 3, 2026
1c70cbe
refactor(spiraldb): replace keyed writer leases with write scopes
eywalker Dec 3, 2026
77ad91a
docs(spiraldb): document single-writer scopes and optional locks
eywalker Dec 3, 2026
270cb4f
merge(spiraldb): integrate main and update cache test expectations
eywalker Dec 3, 2026
a48cec4
chore: merge origin/main into writable database branch
eywalker Dec 3, 2026
9d8430c
fix(spiraldb): preserve commit dependencies during node writes
eywalker Dec 3, 2026
1ed6dd0
fix(spiraldb): guard side effects at the write boundary
eywalker Dec 3, 2026
38ebcbb
merge(spiraldb): integrate stage E commit dependency fixes
eywalker Dec 3, 2026
b0eada7
fix(spiraldb): share scopes across cached invocations
eywalker Dec 3, 2026
b244986
perf: build SpiralDB key sets on demand
eywalker Dec 3, 2026
22d9d02
fix: isolate standalone SpiralDB executions
eywalker Dec 3, 2026
8e56c86
docs(spiraldb): clarify write scope limitations
eywalker Dec 3, 2026
183b7e0
fix: restore async pod overrides and align database checks
eywalker Dec 3, 2026
d9ce39b
test(spiraldb): compare batch retries with per-row commits
eywalker Dec 3, 2026
cefb1d8
chore(spiraldb): merge writable database base updates
eywalker Dec 3, 2026
7b5c0ef
fix(spiraldb): preserve write scopes through review edge cases
eywalker Dec 3, 2026
bc14f50
fix(spiraldb): preserve write scope guarantees
eywalker Dec 3, 2026
928f25f
chore: merge main into database run optimizations
eywalker Dec 3, 2026
6f95fc0
chore: merge writable database base updates
eywalker Dec 3, 2026
f4b893e
fix(spiraldb): guard node batching and scope append retries
eywalker Dec 3, 2026
fcee739
chore(spiraldb): merge append retry and node batching fixes
eywalker Dec 3, 2026
9aa1062
fix(spiraldb): settle ordered retries before annotating errors
eywalker Dec 3, 2026
c43a983
fix(spiraldb): separate snapshot opens from append failures
eywalker Dec 3, 2026
bd084a7
fix(spiraldb): keep write scopes open during cancelled calls
eywalker Dec 3, 2026
98c96ae
fix(spiraldb): retry node batches and refresh table bindings
eywalker Dec 3, 2026
de03a25
fix(database): merge ordered node retries into write scopes
eywalker Dec 3, 2026
c761db3
fix(database): propagate write lock refusals from node execution
eywalker Dec 3, 2026
662e67f
chore: merge main into writable database changes
eywalker Dec 4, 2026
b1bf4d4
fix(database): preserve primary write scope errors
eywalker Dec 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion changelog.d/ITL-1502.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
### Changed

- Writable SpiralDB jobs reuse lease verification, stored-key and completion
- Writable SpiralDB jobs reuse stored-key and completion
lookups, and stale-table discovery across a run, shared by every connector and
thread of the run. Connections reuse resolved table IDs within each write scope.
- A job node's `run()` commits a function node's writes every 100 rows and at its
Expand Down
22 changes: 22 additions & 0 deletions changelog.d/ITL-1899.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
### Changed

- Writable SpiralDB databases assume one writer process per keyed dataset at a
time. Concurrent writers are unsupported and can store duplicate results,
deliver side effects twice, or overwrite a cached source instead of refusing
the conflicting write. Orcapod no longer creates or checks writer lease
generation tables.
- A run opens one write scope per dataset. A write outside a run opens a fresh
scope for that call. A second open scope on the same dataset in the process
raises `SpiralDBScopeOpenError`.
- Each run lists the dataset once and shares its catalog, key index and kept
reads across connectors in the run. That avoids rescanning keys on each flush,
opening tables known to be absent, and reading back newly created tables.
Whole-table reads are kept within a 256 MiB budget.

### Added

- Writable `SpiralDBConnector` accepts a `WriteLock` provider from
`orcapod.databases.write_lock`. The default
`NoWriteLock` performs no cross-process coordination. A scope acquires its
lock before the first write or side effect and releases its handle when the
scope ends, including on failure.
6 changes: 6 additions & 0 deletions docs/api/databases.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,9 @@ the underlying database classes (ITL-1539), so its public form may change.
::: orcapod.databases.PostgreSQLConnector

::: orcapod.databases.SpiralDBConnector

::: orcapod.databases.write_lock.WriteLock

::: orcapod.databases.write_lock.WriteLockHandle

::: orcapod.databases.write_lock.NoWriteLock
2 changes: 1 addition & 1 deletion docs/api/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ These exceptions and warnings report storage, schema, and connector problems.

::: orcapod.errors.SpiralDBObserverNotSupportedError

::: orcapod.errors.SpiralDBLeaseRequiredError
::: orcapod.errors.SpiralDBScopeOpenError

::: orcapod.errors.SpiralDBSignInError

Expand Down
151 changes: 56 additions & 95 deletions docs/concepts/spiraldb-database.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ records, operator caches, cached sources and side-effect logs. Open the dataset

!!! warning "Provisional in 0.4.0"
The writable SpiralDB database is provisional. The format of its tables (how a table is named,
what its metadata records, how values are encoded) and its writer lease may change in
what its metadata records, how values are encoded) may change in
a later version, and a later version may not read tables written now. Nothing of the
database enters a hash: a job's hashes, ids and stored paths are the same on SpiralDB as
on Delta.
Expand Down Expand Up @@ -40,50 +40,42 @@ and writes only the tables it made: it does not take over a table it did not wri

## One writer at a time

The SpiralDB database has one writer at a time. Every run of a job (`job.run()`, `job.run_async()`,
a job node's `run()`, and a load-only run that reads a cached source) takes the
dataset's **writer lease** before it checks a source, computes or writes anything, and
releases it when it ends, also when it fails. A run whose database and result database
are on one dataset takes one lease.

While one run holds the lease, a second writer, in this process or another, is refused
when its run starts, with `LeaseBusyError`. Nothing of its run has happened then: no
source was checked, nothing computed, no data table made. (A run that writes
several datasets takes their leases one after another, so a dataset whose lease it took
before the refusal may hold a new lease table, released.) The error names the lease's table
id and who holds it. The lease is refuse-only: the second writer does not wait and never
takes the lease over, and a lease does not expire.

<!-- docs-test: skip -->
```python
from orcapod.databases.spiraldb_lease import LeaseBusyError

try:
job.run()
except LeaseBusyError as refused:
print(refused)
# SpiralDB dataset 'pipeline_results' has a conflicting writer lease (owner ..., table ID ...). ...
```

Only a job run writes the SpiralDB database, through the writable connectors it holds the
lease with (those of its databases and of the cached sources it reads). A write through
any other writable connector (a cached source read outside a run, a `ConnectorArrowDatabase` over a
connector of its own or over a `share_client()` copy, flushed directly) raises `SpiralDBLeaseRequiredError` before
anything is written, also while a run holds the dataset's lease. A write through a
running job's own databases from outside the run (another thread, an observer) is not
told apart from the run's own: do not write through them while the job runs. A
load-only run of a job writes no node's table, so it takes a lease only for a cached
source it reads. A run takes one lease per dataset of one service: writable connectors
whose client reaches the same service share it, whether their address was left to the
default or given (`overrides={"server.url": ...}`).

The run checks for stored keys using an index shared by its writable connectors.
Every write any of them commits, from any thread, updates it, and so does the run's
listing of the dataset's tables: a side-effect receipt or a table written during the
run is seen at once by every later lookup of the run. After an append whose outcome
is unknown (a lost reply), the index is read again from the table as it is then.
Every writer must respect the dataset's lease. Writes from outside the lease can
invalidate the index and are unsupported.
Orcapod assumes **one writer process per keyed dataset at a time**. Concurrent
writers are unsupported. If two processes write to the same dataset, they can
store duplicate results, deliver side effects twice, or overwrite a cached
source where a conflicting write would previously have been refused.

Within one process, starting a second independent execution on the same dataset
while a run holds its write scope is also unsupported. This includes starting it
inside a function or a task it starts, or calling `execute()` directly on another
job's sink. Orcapod does not always refuse the second execution.

A job run opens one write scope per writable dataset before checking sources.
Connectors in the run that reach the same service, project and dataset share the
scope. A second scope for the same project and dataset in the process raises
`SpiralDBScopeOpenError`, including when another thread tries to flush during a
run. A direct flush or a cache write outside a run opens a scope just for that
call and discards its state afterward. A standalone async pod execution
shares one scope per dataset across its nested caches and concurrent rows.

The scope lists the dataset once on first use. Its connectors share the table
catalog, stored key index and recent whole-table reads. A commit updates
the shared state so subsequent reads see new tables and receipts. After an
append with an unknown outcome, the next key lookup refreshes the affected
index from the service.

### Optional write lock

`SpiralDBConnector(..., write_lock=provider)` accepts a `WriteLock` provider
from `orcapod.databases.write_lock`.
`None` uses `NoWriteLock`, which performs no coordination across processes.
When several connectors share a scope, give them the same custom provider.
A scope calls `provider.acquire(project_id, dataset)` before the first table
create or append. It also acquires the lock before a tracked side effect's
first delivery or a context-taking function's first call. The call returns a
handle whose `release()` method runs when the scope ends, including on failure.
An acquisition error reaches the caller unchanged and prevents the write or
delivery. A scope that has no writes or effects to perform never acquires the lock.

A function job node's `run()` can commit every 100 rows and at the end of the node.
Batching requires an attached pipeline database and a pod that takes no invocation
Expand All @@ -96,15 +88,18 @@ context-taking function node commits each result before starting the next call.

If a batched result append fails, the node retries the rows one at a time in order.
It stops at the first failing row and raises that row's error. A read or validation
failure before the append stops the run immediately. After a definite
append failure, the results and pipeline records for the successful prefix stay
stored, as they do with per-row commits. After an ambiguous reply (the service may
have accepted some of the batch's rows), the ordered retry publishes a pipeline record
for every row before the first failing row, including a row the service had already
accepted (the retry finds it stored and does not append it again). Only a row the
service accepted beyond that prefix, from the failing row on, can stay stored with
no pipeline record pointing to it; a later run finds it by input hash as a cached
result. No pipeline record ever points to a result that is not stored.
failure before the append stops the run immediately. If the ordered retry runs
to completion, including when it stops on an ordinary append error, the results
and pipeline records for the successful prefix stay stored. After an ambiguous
reply (the service may have accepted some of the batch's rows), this prefix
includes results the retry finds already stored. An already accepted result
beyond the prefix can stay stored without its pipeline record.

If a `KeyboardInterrupt` or another `BaseException` interrupts the ordered
retry, even a result confirmed earlier in the retry can remain stored without
its pipeline record. A later run can reuse stored results by input hash and
write their missing pipeline records. No pipeline record ever points to a
result that is not stored.

A failed batched pipeline-record append also retries the records in order. The
records before the first permanent failure stay published. The results were
Expand All @@ -116,39 +111,6 @@ A connection resolves a table by name and checks its recorded path when it finds
the table. Later operations use the resolved table ID. Each new write scope
resolves the names it uses again, so a replacement between runs is picked up.

### A lease left behind

A process that stops in the middle of a run (killed, or a lost connection) leaves its
lease held, and every later run is refused. Once you are sure that writer has stopped,
and every write it sent has settled, clear the lease by the project, dataset and table
id the refusal named (its message spells out the call):

<!-- docs-test: skip -->
```python
import spiral

from orcapod.databases import spiraldb_lease

spiraldb_lease.clear(
spiral.Client(),
"<project>",
"<dataset>",
"<table id from the refusal>",
confirm_writer_stopped=True,
)
```

`spiral.Client()` connects to the default service. When the job's connector was made
for another service address (`SpiralDBConnector(..., overrides={"server.url": ...})`),
make the client for that same address, with a sign-in allowed to update the dataset:
a client of another service does not find the table id. Only the dataset's newest lease
table can be cleared: any other table id is refused and nothing is written.

The run verifies each acquired lease at its first write. Clearing a lease while its
writer is still running is unsupported and can let a second writer in while the first
is still writing. Each lease is a small keyed table of the dataset. Keep all generations,
including released ones, because removing a generation by hand can let two writers in.

## Saving and loading a job

A job saved on the SpiralDB database records the connector (`connector_type`, project,
Expand All @@ -172,14 +134,13 @@ read different tables.

## Limits

- In a writable run, the first key check for an existing table reads its whole
key column if the lease has yet to index it. The next check after index
invalidation scans it again. Routine checks use the lease's key index, which
successful appends update without a rescan. Each read of stored rows reads the
whole table, so these reads grow with the table's history.
- Only a job run writes the SpiralDB database: a cached source over it is read within a
run. A
way to hold the lease outside a run is planned (ITL-1849).
- In a write scope, a key check scans the whole key column of a table with rows
when the scope has neither an index nor reusable keys from an earlier read or
append. This can happen on the first check or after a failed append invalidates
the index. Successful appends update the index, and later checks reuse it
across flushes. Outside a write scope, every check for one or more keys in a
table with rows scans the key column. Reads of stored rows load the whole
table and can be reused within a write scope under a 256 MiB budget.
- Status and logging observers do not write to SpiralDB: they raise
`SpiralDBObserverNotSupportedError` at setup; give them another database such as
Delta.
Expand Down
69 changes: 17 additions & 52 deletions docs/dev/scripts/itl_1844_database_evaluation.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,17 @@
Scenarios: a first run (sync), a second run with one more input row, a REPLAY run of the
operator, an async run (``run_async``) and a node run on fresh job names, a separate
result database on the same dataset, a saved job loaded with the database and read back, a
load-only run, and a second writer refused while a lease is held.
load-only run, and a second write scope refused while the same process holds a scope
for that dataset.

uv run python docs/dev/scripts/itl_1844_database_evaluation.py fake
uv run python docs/dev/scripts/itl_1844_database_evaluation.py live \\
--project <test project> --dataset <test dataset>

``live`` needs a sign-in spiral-sdk finds (the ``SPIRAL_*`` environment variables) and
writes into the given dataset only: database tables of job names starting with
``itl1844_eval_<UTC stamp>``, and one lease table per run. spiral-sdk cannot drop a keyed
table, so they stay; the report lists every one. Prints a JSON report.
``itl1844_eval_<UTC stamp>``. spiral-sdk cannot drop a keyed table, so they stay.
The JSON report includes the scenario outcomes and an inventory of those database tables.
"""

from __future__ import annotations
Expand Down Expand Up @@ -48,11 +49,9 @@
DeltaTableDatabase,
SpiralDBConnector,
)
from orcapod.databases import spiraldb_lease # noqa: E402
from orcapod.databases.spiral_database_identity import spiral_table_name # noqa: E402
from orcapod.databases.spiraldb_connector import _open_keyed_table # noqa: E402
from orcapod.databases.spiraldb_write_scope import take_lease # noqa: E402
from orcapod.databases.store_table_names import spiral_lease_table_name # noqa: E402
from orcapod.errors import SpiralDBScopeOpenError # noqa: E402
from orcapod.databases.spiraldb_write_scope import database_writes # noqa: E402
from orcapod.side_effects import SideEffectPod, sink_pod # noqa: E402
from orcapod.sources import ArrowTableSource # noqa: E402
from orcapod.types import CacheMode # noqa: E402
Expand Down Expand Up @@ -265,7 +264,7 @@ def spiral_db() -> ConnectorArrowDatabase:
_ = run(build(fresh, delta, n=6))
s[label] = compare(spiral_db(), delta, (fresh,))

# 6. a separate result database on the same dataset (one lease).
# 6. a separate result database on the same dataset (one scope).
fresh = f"itl1844_eval_{stamp}_results"
results_delta = DeltaTableDatabase(work / "delta_results")
_ = build(
Expand Down Expand Up @@ -294,19 +293,15 @@ def spiral_db() -> ConnectorArrowDatabase:
loaded.nodes["select"].as_table().num_rows,
)

# 8. a second writer is refused while another holds the lease.
_, release = take_lease(
SpiralDBConnector(project, dataset, writable=True), "evaluation: another writer"
)
# 8. A concurrent scope is refused within this process.
fresh = f"itl1844_eval_{stamp}_refused"
try:
build(fresh, spiral_db(), n=6).run()
refused = False
except spiraldb_lease.LeaseBusyError:
refused = True
finally:
release()
s["second writer"] = {
with database_writes([spiral_db()]):
try:
build(fresh, spiral_db(), n=6).run()
refused = False
except SpiralDBScopeOpenError:
refused = True
s["second scope"] = {
"refused": refused,
"nothing_written": spiral_db().list_table_paths((fresh,)) == [],
}
Expand Down Expand Up @@ -350,12 +345,12 @@ def succeeded(scenarios: dict[str, Any]) -> bool:

The first run computes all six rows; the new row is the only one computed and
delivered; the database flag is saved; the load-only run loads seven rows; a refused
writer wrote nothing.
scope wrote nothing.
"""
first, new = scenarios.get("first run", {}), scenarios.get("new row", {})
saved, second = (
scenarios.get("save and load", {}),
scenarios.get("second writer", {}),
scenarios.get("second scope", {}),
)
return (
all(v.get("ok", True) for v in scenarios.values())
Expand Down Expand Up @@ -389,21 +384,6 @@ def database_tables(project: str, dataset: str, stamp: str) -> list[dict[str, st
]


def lease_tables(project: str, dataset: str) -> list[dict[str, str]]:
"""The dataset's lease generation tables (contiguous from 1), by name and id."""
connector = SpiralDBConnector(project, dataset)
client = connector._client # pyright: ignore[reportPrivateUsage] # a listing for the report
found: list[dict[str, str]] = []
generation = 1
while True:
name = spiral_lease_table_name(generation)
table = _open_keyed_table(client, project, dataset, name)
if table is None:
return found
found.append({"name": name, "id": str(table.resource_id)})
generation += 1


def inventory(
report: dict[str, Any], label: str, listing: Callable[[], list[dict[str, str]]]
) -> list[dict[str, str]] | None:
Expand Down Expand Up @@ -440,11 +420,6 @@ def main() -> int:
stack.enter_context(fake_service(work))
report: dict[str, Any] = {"stamp": stamp, "scenarios": {}, "ok": False}
print(f"stamp {stamp}", file=sys.stderr)
before = inventory(
report,
"lease tables before",
lambda: lease_tables(args.project, args.dataset),
)
try:
evaluate(args.project, args.dataset, stamp, work, report)
except Exception as exc: # reported with every table made so far
Expand All @@ -457,16 +432,6 @@ def main() -> int:
"database tables",
lambda: database_tables(args.project, args.dataset, stamp),
)
after = inventory(
report,
"lease tables after",
lambda: lease_tables(args.project, args.dataset),
)
if before is not None and after is not None:
known = {t["name"] for t in before}
report["lease_tables_created"] = [
t for t in after if t["name"] not in known
]
if "inventory_errors" in report: # the tables made are not all known
report["ok"] = False
report["mode"] = args.mode
Expand Down
Loading
Loading