Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 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
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
d9ce39b
test(spiraldb): compare batch retries with per-row commits
eywalker Dec 3, 2026
928f25f
chore: merge main into database run optimizations
eywalker Dec 3, 2026
f4b893e
fix(spiraldb): guard node batching and scope append retries
eywalker Dec 3, 2026
98c96ae
fix(spiraldb): retry node batches and refresh table bindings
eywalker Dec 3, 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
23 changes: 23 additions & 0 deletions changelog.d/ITL-1502.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
### Changed

- Writable SpiralDB jobs reuse lease verification, 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
end when it has a pipeline database, the pod takes no invocation context, and
every database the node commits to is a writable SpiralDB database or an
`InMemoryArrowDatabase`, including at least one writable SpiralDB database.
Other node runs keep per-row commits. A failed batched result append is retried
one row at a time in order. Read and validation errors before the append stop the
run immediately. After a definite append failure, the results and pipeline records
before the failing row stay stored, as with per-row commits. After an ambiguous
reply, each row before the first failing row gets its pipeline record, including
rows the service already accepted. A result the service accepted beyond that prefix
can stay stored without a pipeline record and be reused by a later run.
Failed pipeline-record appends also retry one row at a time. An interrupted node
run withdraws its pending results and pipeline records.

### Fixed

- Writable SpiralDB appends copy Arrow buffers before writing, including slices
that leave string or binary lists empty.
54 changes: 48 additions & 6 deletions docs/concepts/spiraldb-database.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,45 @@ source it reads. A run takes one lease per dataset of one service: writable conn
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
Comment thread
eywalker marked this conversation as resolved.
Resolved
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.

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
context. The node must commit only to writable SpiralDB databases or
`InMemoryArrowDatabase` instances, including at least one writable SpiralDB database.
Other node runs commit after each row. This includes a standalone function node
with only an ephemeral result database and a node writing to a store such as Delta
or PostgreSQL, where another reader can see each result as it is stored. A
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.

A failed batched pipeline-record append also retries the records in order. The
records before the first permanent failure stay published. The results were
committed first, so later runs can reuse them even if publishing their records
failed. An interrupted node run withdraws its still-pending results and pipeline
records. Results and records already committed stay stored.

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
Expand Down Expand Up @@ -105,9 +144,10 @@ make the client for that same address, with a sign-in allowed to update the data
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.

Clearing the lease of a writer that is still running lets a second writer in while the
first is still writing. Each lease is a small keyed table of the dataset; keep every
one, also released ones: removing one by hand can let two writers in.
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

Expand All @@ -132,9 +172,11 @@ read different tables.

## Limits

- Each check of which rows a table holds reads the table's whole key column, and each
read of stored rows reads the whole table, so the cost of a run grows with the
table's history.
- 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).
Expand Down
14 changes: 12 additions & 2 deletions src/orcapod/contexts/stored.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
OrcapodDatabaseContentWarning,
TableListingNotSupportedError,
)
from orcapod.protocols.spiraldb_run import SpiralDBRunLookupProtocol
from orcapod.system_constants import (
OPERATOR_DB_SCHEMA_VERSION,
PIPELINE_DB_SCHEMA_VERSION,
Expand Down Expand Up @@ -466,8 +467,11 @@ def find_stale_tables(
Args:
database: The database the paths belong to.
current: The table's current path and the current data context key, to also
look for rows of another data context in the current table (this reads
the whole table). ``None`` skips that search.
look for rows of another data context in the current table. This reads
the whole table, except on a writable SpiralDB database
whose table records the current data context and whose pending rows hold
it too (``spiral_records_match_context``): its metadata answers, and no
row is read. ``None`` skips that search.
name_path: The beginning of the table's path up to the name of its function
or pod, the part that holds no hash. ``None`` skips the listing.
result_revision: For a result cache, the revision of its data function type's
Expand Down Expand Up @@ -503,6 +507,12 @@ def find_stale_tables(
)
if current is not None:
current_path, current_context = current
# SpiralDB records a single data context for the table. Read rows only
# when the report needs to count them under another context.
if isinstance(
database, SpiralDBRunLookupProtocol
) and database.spiral_records_match_context(current_path, current_context):
return found
for key, rows in sorted(stored_data_contexts(database, current_path).items()):
if key != current_context:
found.tables.append(
Expand Down
15 changes: 14 additions & 1 deletion src/orcapod/core/database_writes.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from dataclasses import dataclass
from typing import TYPE_CHECKING, Protocol

from orcapod.databases._pending_commits import observe_records
from orcapod.databases._pending_commits import observe_queue, observe_records

if TYPE_CHECKING:
from collections.abc import Callable, Collection, Iterator, Set
Expand All @@ -31,6 +31,13 @@ def stores_records(self) -> bool:
...


def shared_database_queue(database: WriteDatabase) -> PendingCommits | None:
"""Identify a view's native pending queue through its forwarded path."""
with observe_queue() as queues:
_ = database.base_path
return queues[0] if len(queues) == 1 else None


@dataclass
class _Write:
"""One write site that still needs its database's final whole flush."""
Expand Down Expand Up @@ -92,6 +99,12 @@ def function_databases(self) -> dict[int, WriteDatabase]:
if write.function
}

def withdraw_pending_function_writes(self) -> None:
"""Withdraw function results and pipeline records still pending from this run."""
for (_, (key, _)), write in self._writes.items():
if write.function:
write.pending.withdraw_pending(key, write.ids)

def logs_to_replay(self, queue: int) -> dict[LogTable, set[bytes]] | None:
"""Keep the IDs from pending logs without querying the store after failure."""
logs: dict[LogTable, set[bytes]] = {}
Expand Down
52 changes: 46 additions & 6 deletions src/orcapod/core/nodes/function_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@
)
from orcapod.protocols.database_protocols import ArrowDatabaseProtocol
from orcapod.protocols.hashing_protocols import IdentityWalkProtocol
from orcapod.protocols.spiraldb_run import InOrderFlushProtocol
from orcapod.protocols.observability_protocols import (
DataExecutionLoggerProtocol,
ExecutionObserverProtocol,
Expand Down Expand Up @@ -1548,6 +1549,7 @@ def __init__(
self._row_count_checked: bool = False
# Batched commits, set only while PipelineJob.run runs the node (ITL-919).
self._commit_every_rows: int | None = None
self._results_in_order = False
self._rows_since_commit = 0
self._commit_failed = False

Expand Down Expand Up @@ -2005,6 +2007,7 @@ def from_descriptor(
node._expected_row_count = expected_row_count
node._row_count_checked = False
node._commit_every_rows = None
node._results_in_order = False
node._rows_since_commit = 0
node._commit_failed = False

Expand Down Expand Up @@ -2451,18 +2454,40 @@ def _require_pipeline_database(self) -> ArrowDatabaseProtocol:
# Batched commits (ITL-919)
# ------------------------------------------------------------------

def _committed_databases(self) -> list[ArrowDatabaseProtocol]:
"""The databases this node's commits write: its pipeline database, its result
database, and its ephemeral result database when its results are ephemeral."""
databases: list[ArrowDatabaseProtocol] = []
if self._pipeline_database is not None:
databases.append(self._pipeline_database)
pod = self._cached_function_pod
if isinstance(pod, CachedFunctionPod):
databases.append(pod.result_database)
ephemeral = self._ephemeral_cached_pod
if self._node_config.is_result_ephemeral and isinstance(
ephemeral, CachedFunctionPod
):
databases.append(ephemeral.result_database)
return databases

@contextlib.contextmanager
def _batched_commits(self, rows_per_commit: int) -> Iterator[None]:
def _batched_commits(
self, rows_per_commit: int, *, results_in_order: bool = False
) -> Iterator[None]:
"""Commit this node's writes every ``rows_per_commit`` rows inside the block.

``PipelineJob.run`` runs each function node inside this block. Its result
caches stop committing after every stored result, and the node commits its
pending writes (ephemeral results, then its result table, then the pipeline
records) every ``rows_per_commit`` rows and at its end. Outside the block
(a node run on its own) every result is committed as it is stored.
records) every ``rows_per_commit`` rows and at its end. A node run uses the
same block when ``node_run.batches_node_commits`` says so. Outside it every
result is committed as it is stored.

Args:
rows_per_commit: How many processed rows' writes one commit holds.
results_in_order: Retry failed result and pipeline-record appends one
row at a time up to the first failure, where the store supports
ordered retry (``InOrderFlushProtocol``).

Yields:
Nothing; the node commits in batches while the block runs.
Expand All @@ -2473,6 +2498,7 @@ def _batched_commits(self, rows_per_commit: int) -> Iterator[None]:
if isinstance(pod, CachedFunctionPod)
]
self._commit_every_rows = rows_per_commit
self._results_in_order = results_in_order
self._rows_since_commit = 0
self._commit_failed = False
for pod in pods:
Expand All @@ -2481,6 +2507,7 @@ def _batched_commits(self, rows_per_commit: int) -> Iterator[None]:
yield
finally:
self._commit_every_rows = None
self._results_in_order = False
for pod in pods:
pod.set_auto_flush(True)

Expand All @@ -2494,8 +2521,18 @@ def _flush_node_table(
) -> None:
"""Flush one batch and withdraw dependent records if a result write fails."""
try:
if result:
if (
result
and self._results_in_order
and isinstance(database, InOrderFlushProtocol)
):
database.flush_result_batch_in_order(
path, publish_records=publish_records
)
elif result:
database.flush_result_batch(path, publish_records=publish_records)
elif self._results_in_order and isinstance(database, InOrderFlushProtocol):
database.flush_batch_in_order(path)
else:
database.flush_batch(path)
except BaseException as exc:
Expand Down Expand Up @@ -4532,7 +4569,7 @@ def _run_alone(
"""
from dataclasses import replace

from orcapod.pipeline.node_run import commit_run
from orcapod.pipeline.node_run import batch_node_commits, commit_run
from orcapod.pipeline.restrictions import restrictions_in_force
from orcapod.pipeline.run_summary import RunCountingObserver, RunSummary
from orcapod.utils.database_errors import flush_best_effort
Expand All @@ -4551,7 +4588,10 @@ def _run_alone(
if database is not None
]
try:
_ = self.execute(self._input_stream, observer=counter, load_only=load_only)
with batch_node_commits([self], load_only=load_only):
_ = self.execute(
self._input_stream, observer=counter, load_only=load_only
)
Comment thread
eywalker marked this conversation as resolved.
Resolved
except Exception as run_error:
if not load_only:
# Commit what succeeded; a load-only run writes nothing (ITL-1095).
Expand Down
Loading
Loading