Skip to content

feat(api): multi-write transactions - #2023

Merged
bplatz merged 13 commits into
mainfrom
feat/engine-transactions
Oct 7, 2026
Merged

bplatz merged 13 commits into
mainfrom
feat/engine-transactions

Conversation

@bplatz

@bplatz bplatz commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

A transaction API for embedding hosts: several writes, staged one at a time and committed as one commit. The Python package's ledger.transaction() is built on it.

  • Fluree::begin_transaction(ledger, TransactionOptions) → Transaction. Each stage(TxnOperation) — JSON-LD, Turtle, or SPARQL UPDATE — applies over the ones before it and is validated as it is added (policy, SHACL, uniqueness); a write that fails to stage is left out and the transaction carries on as it was. db() reads the staged state; commit() writes everything as one commit through the existing write path, netting reversed facts as a ;-separated SPARQL UPDATE does.
  • Options. TransactionOptions carries the governance, tracking (one tracker across the whole transaction, so max_fuel bounds it and the tally comes back on the commit) and an optional index config.
  • Concurrency. If another commit lands first, a transaction that was only written to is re-based over it (different subjects) or staged again on the new head, under the policy the ledger has then. One that was also read — through db(), or a Cypher RETURN — fails with CommitConflict instead, since what was read may have decided what was written. Transaction commits count in write_path_stats().
  • Cypher writes stage in the same transaction (stage_cypher), with skolem ids kept so a re-stage creates the same identities. cypher_import::split_statements is public so a host can stage a ; script statement by statement.
  • Savepoints. savepoint() / rollback_to() discard the operations staged after a point, for a group that must stage all or nothing. A savepoint a rollback discarded is refused.
  • Local commit only, like Bolt's explicit transactions.

Follow-up: #2031 (Bolt's explicit transactions on Transaction)
Follow-up: #2032 (a harness that drops async mutating methods at each await point)

@bplatz
bplatz added this pull request to stack #2026 October 6, 2026 03:23
@bplatz bplatz added the enhancement New feature or request label Oct 6, 2026
@bplatz bplatz changed the title feat/engine transactions feat(api): multi-write transactions Oct 6, 2026
@bplatz bplatz added the area:transact Staging, commit, import/bulk-import, novelty, retraction semantics label Oct 6, 2026
@bplatz
bplatz requested review from aaj3f and zonotope October 6, 2026 03:23
@bplatz
bplatz marked this pull request as ready for review October 6, 2026 03:23
@bplatz
bplatz force-pushed the feat/engine-transactions branch 2 times, most recently from fc8aba5 to 2d8a172 Compare October 6, 2026 10:26

@aaj3f aaj3f left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is neat @bplatz and I quite like it. There are some recommendations in the full review below, but a few things maybe worth highlighting.

It seems there are both txn parity/correctness issues and performance issues stemming from how the PR is handling recovery currently. For a failed stage or rollback_to, recovery is established currently by re-running the operations from base (I should mention "re-run ops from base" does seem correct to me for a third scenario, which is commit-time re-stage of an unread txn). In any event, it seems a cheaper and correctness-guaranteed option would be to keep the pre-op virtual state until a stage succeeds (a clone w/ all Arc fields, for example). So failed or dropped stages leave transactions exactly as they were w/out re-running anything. More details below.

Maybe not the work of this PR, but CypherTransaction (Bolt) and Transaction now coexist and have slightly different conflict semantics. Since Transaction can now stage Cypher, perhaps Bolt's BEGIN/COMMIT could plausibly sit on it. Likely not a decision to be acted on here, but whether CypherTransaction and Transaction should continue to exist in isoloation from one another is worth a decision after this PR

You'll see some review commentary below on a class of issue that has been seen in this PR before (#1261, #1718), namely state can get "torn" in scenarios where, for example, a method moves state out of self (or mutates part of it) and then awaits in order to update/restore. That is, if the caller can drop the future (timeout/select! or client disconnect on HTTP), then it leaves self "torn". We've resolved previous cases ad hoc before and my recommendations below are also a similar point-fix rec solution, but perhaps we ought to also introduce a more class-of-issue-oriented PR (I'm struggling to think exactly how to do that other than, if nothing else, a kind of test harness dropping each public async mutating method at every await point).

Full review below:


Transaction is mostly a thin owner of SequentialStager plus the single-write commit loop (rebase_stage, commit_and_finalize, the refresh-and-retry), which is exactly the altitude I'd hope for in an API Python is about to build on. I spent most of my time trying to break the concurrency story, and it held up better than I expected: uniqueness and sh:class races across subjects refuse at commit, WHERE-bearing updates re-stage rather than lose an update, Cypher identities survive a rollback, and the read rule is pinned by the tests (I disabled it and two went red). Two things need to land first:

  1. A re-stage checks the writes against the policy from when the transaction began (fluree-db-api/src/transaction.rs:298). A deny rule committed while a transaction is open doesn't apply to it, even though the transaction commits after the rule (t=4 vs t=3 in my repro). Rebuilding the policy context from the state being staged on fixes it; I tried that and the open transaction is refused, with the 10 tests green.
  2. rollback_to truncates operations before it rebuilds the stager (fluree-db-api/src/transaction.rs:217). If it's dropped or fails at the await, len() reports the rollback while commit() writes the rolled-back operations. Building the new stager first and truncating after fixes it (three lines, verified locally).

The rest, roughly by importance:

  • 🟠 Recovering from a failed stage by re-running everything changes blank nodes and STRUUID()/NOW() values the caller already read, costs as much as the whole transaction, and a dropped stage leaves the next call panicking (transaction.rs:237, tx.rs:205). Keeping the pre-operation state until a stage succeeds fixed all three in my local trial.
  • Inherited from #2022, not introduced here: Transaction::commit nets through the same stager.finish() (transaction.rs:277), so it inherits the named-graph lookup in rebase::current_asserted_for_key (rebase.rs:969 keeps flake.g == key.g, but index-resident rows come back with g: None). I ran it through begin_transaction on a cold index: staging INSERT DATA { GRAPH <g> { x } } and then DELETE DATA { GRAPH <g> { x } } for an existing x commits nothing (t stays 1) and x survives; the default graph is fine. The fix belongs in #2022. Once it lands, a regression test here through begin_transaction would keep this path covered, since it's the one Python's ledger.transaction() uses.
  • 🟡 Nothing pins the re-base path (it_transaction.rs:179); begin_transaction has no tracking or index options (transaction.rs:119); a Savepoint survives a rollback past it (transaction.rs:72); two doc additions (rust-api.md:697).
  • ❓ Whether a validation or policy rejection should count as a read (transaction.rs:179). I'm fine with the statement-level default itself; the reasoning is inline.
  • ❓ This is more of a question than a suggestion: now that Transaction can stage Cypher and tracks reads, do you see Bolt's CypherTransaction (cypher_txn.rs) eventually sitting on it? Today they disagree on conflicts (Bolt refuses any moved head; this re-bases or re-stages unless read), and two engines for one concept tend to drift. The policy-on-re-stage gap above is a place where they already differ. Not for this PR; I'd just like to know which one is meant to be the long-term shape.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ extends SequentialStager and the single-write commit loop rather than adding a third path; ❓ a second transaction engine next to CypherTransaction (question above).
  • Performance (speed first, memory second): ✔ no hot path touched: the existing stage_plan callers pass policy: None, and SequentialStager::stage delegates to a generic closure. The transaction's own failure path costs a full re-stage per failed stage (inline), and an unread transaction that loses a race re-stages all of its operations under the ledger's write lock, which is fine for now but worth knowing for bulk loads.
  • Deployment targets: ✔ embed-only (no server or CLI route uses it), and n/a for solo's Lambdas, which can't hold a transaction across invocations. #2025's block_on runs engine futures to completion, so the cancellation findings reach Rust embedders, not Python. commit is local-commit only, like CypherTransaction (doc note inline).
  • Testing: ⚠️ 10 integration tests that run (in CI's nextest and locally, by name), and the read conflict is pinned (two red under mutation). The re-base path, cancellation and policy on re-stage aren't pinned.
  • Conventions: ✔ multi-line commit bodies, fmt and clippy -D warnings green in CI, and docs updated with precise wording for the atomicity and read rules (two additions inline).

Verified locally at branch HEAD: cargo test -p fluree-db-api --features shacl --test grp_transact -- it_transaction (10/10 by name) plus 13 scratch probes for the races and recovery paths above; two mutations (read check off: 2 red; re-base off: 0 red); trial fixes for the policy re-stage, the rollback_to ordering and keeping the pre-operation state, each with the 10 tests green.

Approving now so you can merge without waiting on another pass from me. Just be sure the first two are in before you do, and ideally the 🟠 one too.

Comment thread fluree-db-api/src/transaction.rs Outdated
let stage = match rebased {
Some(stage) => stage,
None => {
stage_all(&fluree, guard.clone_state(), &operations, &context)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Must address before merge: a re-stage over a newer head checks the writes against the policy the ledger had when the transaction began, not the one it has now.

begin_transaction builds context.policy once, from the base (transaction.rs:129-137). When the head has moved and the transaction wasn't read, this branch re-stages every operation against guard.clone_state(), so SHACL and uniqueness re-run against the new head, but the operations are still checked under that begin-time PolicyContext. Any write staged under a policy is Unbounded, so this is the path every governed transaction takes when it loses a race. CypherTransaction can't get here (it builds the context per statement and refuses a moved head), and the single-write path builds its context per request, so its window is one request rather than the life of a transaction.

Concretely, with config f:defaultAllow true and f:policyClass ex:WritePolicy: I began a transaction and staged ex:bob ex:ssn "999-99-9999", then committed a required f:allow false rule on ex:ssn from elsewhere. A transaction begun after that rule is refused ("Policy enforcement prevents modification"), but the open one commits bob's SSN at t=4, after the rule landed at t=3.

Rebuilding the policy context from the state we're about to stage on fixes it. I tried this locally (with mut context in the destructure): the open transaction is then refused, and the 10 tests stay green.

let state = guard.clone_state();
context.policy = crate::build_transact_policy_context(
    &fluree,
    &state.snapshot,
    state.novelty.as_ref(),
    Some(state.novelty.as_ref()),
    state.t(),
    &context.governance,
)
.await?;
stage_all(&fluree, state, &operations, &context)
    .await?
    .finish()
    .await?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 1f73050

Comment thread fluree-db-api/src/transaction.rs Outdated
if savepoint.0 >= self.operations.len() {
return Ok(());
}
self.operations.truncate(savepoint.0);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Must address before merge: a rollback_to that is dropped or fails part way leaves the transaction committing the operations it reports as rolled back.

rollback_to truncates self.operations here and only then awaits stage_all to rebuild self.stager. If that future is dropped at the await (a tokio::time::timeout or select! around it, an axum handler whose client disconnected) or stage_all returns an error, operations is already truncated but stager still holds every operation's flakes, and commit() on an unmoved head commits the old stager.

I reproduced it on a file-backed ledger: stage keep, take a savepoint, stage discard1 and discard2, poll rollback_to(sp) once and drop it. len() then says 1, and commit() writes all three. It's the same shape as #1261 and #1718 (state torn across an .await), and 9e68d18's commit message already names an embedded caller with a timeout as a reachable path.

Building the new stager before touching operations makes a dropped or failed rollback leave the transaction exactly as it was. With this locally, the repro reports len() == 3 and commits what it reports, and the 10 tests stay green:

let stager = stage_all(
    &self.fluree,
    self.base.clone(),
    &self.operations[..savepoint.0],
    &self.context,
)
.await?;
self.operations.truncate(savepoint.0);
self.stager = stager;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 660c195

In-tree storage never returns Pending at that await, so a drop can't be reproduced in a test here; the test makes the same await fail instead (re-staging exceeds a fuel limit), which leaves the same state behind.

Comment thread fluree-db-api/src/transaction.rs Outdated
Err(e) => {
// A failed stage consumes the stager's state; rebuild it from
// the operations that did stage.
self.stager = stage_all(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 Should address: recovering from a failed stage by re-running every earlier operation changes values the caller already read, and costs as much as the whole transaction.

A failed stage loses the virtual state, because SequentialStager::stage_with take()s it before awaiting (tx.rs:205), so this branch rebuilds by re-staging every operation from the base. Three consequences I could show:

  • Re-staging re-mints blank nodes and re-evaluates STRUUID()/UUID()/NOW(). I staged a JSON-LD insert with a blank node and INSERT { ex:order ex:token ?t } WHERE { BIND(STRUUID() AS ?t) }, read both through db(), then staged a typo. After the error, db() showed a different blank node and a different token, and commit() wrote the new ones. The read flag doesn't fire because the head never moved, so the module docs' promise that a read transaction commits on what it read breaks without an error.
  • One failed stage after 1,000 staged inserts took 304 ms, against 287 ms to stage all 1,000 and 0.2 ms for a normal stage (debug build). A Python loader that catches and skips bad rows pays for the whole transaction again on every bad row.
  • If the stage future itself is dropped at an await, nothing rebuilds, and the next stage() or db() panics with virtual state consumed by a final non-advancing stage (reproduced on a file-backed ledger; in a panic = "abort" host that's a process abort). A rebuild that fails here (the ? on line 243) leaves the same state.

What I tried locally: stage_with keeps the pre-operation state in current (all Arc fields, so the clone is refcount bumps) and clears it only once the stage returns Ok, before the in-place apply; push then returns a failed stage's error without rebuilding. The token and blank node survive the failed stage and are what commits, the dropped-stage panic is gone, the failed stage is cheap, and the 10 tests plus the 49 it_transact_update tests (whose multi-operation cases share SequentialStager) stay green. The rebuild is still needed when a Cypher statement staged but its RETURN formatting failed, and rollback_to still has to re-run; for those, pinning a skolem_txn_id per operation, as stage_cypher already does on line 196 (and as graph sync and upsert do), keeps blank nodes stable, and the value functions are worth a sentence in the docs.

@bplatz bplatz Oct 7, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 275bcef

SPARQL updates don't pin a skolem id (a ; request's operations would share one), so their blank nodes and NOW()/UUID() values can still change on rollback_to; the docs say so.

.await
.unwrap();

let result = txn.commit(CommitOpts::default()).await.unwrap();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Optional: this test passes whether the commit re-based or re-staged, so nothing pins the re-base path.

Both routes produce the same ledger here. I changed transaction.rs:292 to Some(_stage) => None (never re-base) and all 10 tests still passed. Transaction::commit also doesn't call note_write_path the way commit_with_handle does (tx_builder.rs:2385-2394), so write_path_stats() can't tell the two apart either.

Noting the path in commit and asserting rebased == 1 here (and restaged == 1 in restages_over_a_concurrent_write_its_update_matches) would pin it, and would give operators the same counters for transaction commits that single writes already get. Minor and non-blocking, but if you agree it's right, I'd rather see it folded in now than lost in the backlog.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in b7dea46

/// Open a transaction on `ledger_id` at its current head. Operations
/// staged on it are checked against the policy `governance` describes
/// (`None`: the ledger's configured defaults only).
pub async fn begin_transaction(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Optional: begin_transaction has no way to bound a transaction's work, and the signature gets harder to change once #2025 ships it.

begin_cypher_transaction takes TrackingOptions, but this takes only governance, and stage_one stages with no tracker. So SPARQL, Turtle and Cypher stages run with no fuel limit (a JSON-LD stage only honours an inline opts.max-fuel). The index config is hard-coded to server_defaults::default_index_config() (line 149), so a host's own reindex_max_bytes doesn't govern the transaction's backpressure. And #2025's block_on can't interrupt a stage, so fuel is the only bound a Python caller could get.

A small options struct (governance, tracking, index_config) would avoid a breaking change later. This is more of a suggestion than a must, but if you agree, I'd rather do it before there's a Python surface on top of it.

@bplatz bplatz Oct 7, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 6c60137

Comment thread fluree-db-api/src/transaction.rs Outdated
/// A point in a [`Transaction`]'s staged operations; see
/// [`Transaction::savepoint`].
#[derive(Clone, Copy, Debug)]
pub struct Savepoint(usize);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Optional: a Savepoint is a bare index, so one taken before a rollback past it silently rolls back to a different point.

Stage a, take sp1, stage b, take sp2, rollback_to(sp1), stage c and d, rollback_to(sp2): it returns Ok, drops d, keeps c (which sp2 never saw), and the commit writes a and c. SQL treats sp2 as destroyed by the rollback to sp1 and errors if you use it.

A generation counter in Savepoint, bumped by rollback_to, plus an error for a savepoint from a discarded history, would close it. #2025 only uses savepoints internally today, so this is about the Rust API. Minor and non-blocking, but if you agree it's right, I'd rather see it in this PR than lost in the backlog.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in c988363

Comment thread docs/getting-started/rust-api.md Outdated
}
```

Pass `GovernanceOptions` to `begin_transaction` to check every write against

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Optional: two things this section could add.

  • The commit is local-only, like Bolt's CypherTransaction (cypher_txn.rs:39-40: "local-commit deployments only — Raft/peer modes must reject BEGIN at the transport layer"). Transaction::commit takes the same lock_for_write + commit_and_finalize path, so a Raft host would have to keep it off its transport too, and the module docs could say so as well.
  • savepoint() / rollback_to() aren't mentioned here. If the re-run in rollback_to stays, one sentence saying the operations before the savepoint are staged again (so STRUUID() / NOW() values and, without a pinned skolem id, blank nodes can change) would save someone a surprise.

The atomicity and read rules above are stated precisely, which I appreciated.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in d135b1c (local-commit only) and 275bcef (what rollback_to stages again)

/// Apply `operation` over those already staged. An operation that fails
/// to stage — a parse error, a policy denial, a SHACL violation — is
/// not added, and the transaction stays as it was.
pub async fn stage(&mut self, operation: TxnOperation) -> Result<()> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❓ Question: should a stage that's rejected by validation or policy count as a read?

I checked the "a failed write is left out and the transaction carries on" default against mainstream databases: it's statement-level rollback (Oracle, MySQL/InnoDB, SQLite) rather than Postgres' aborted transaction. With the error returned synchronously, Result being #[must_use], and #2025's with block rolling back on an uncaught exception, I think it's the right default.

The one thing it lets through: a caller that catches the rejection has learned something about the data ("this email is taken", "this order fails the stock shape") and may stage an alternative because of it. That's the same "decided from what it read" case the read flag exists for, but the flag isn't set, so an unread transaction re-stages over a concurrent commit that changed the fact that caused the rejection. Setting read when a stage fails for a data-dependent reason (a SHACL, uniqueness or policy rejection, not a parse error) would make those conflict instead. I'm honestly not sure it's worth it, and I could see arguing either way.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Kept the statement-level default: a re-stage re-runs SHACL, uniqueness and policy against the new head, so the integrity side holds, and a caller that branches on a rejection can read the transaction through db() to make the commit require the head it decided on. Documented in d135b1c.

Comment thread fluree-db-api/src/transaction.rs Outdated
}
let rebased = match prestaged.take() {
Some(stage) if unchanged => Some(stage),
Some(stage) => Fluree::rebase_stage(&guard, stage, base_t, base_head.as_ref()),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 I tried to break the re-base with constraints that span subjects: two transactions each inserting the same f:enforceUnique email on different subjects, and an sh:class whose target lost its type in a concurrent commit. Both refuse at commit (Unique constraint violation…, SHACL validation failed…), because any stage SHACL or uniqueness validated is Unbounded and goes through the re-stage rather than here. The variable-subject increment re-stages too (1, then a concurrent 10, commits 11). Worth keeping that invariant loud if WriteScope ever grows.

@bplatz
bplatz force-pushed the feat/engine-transactions branch 3 times, most recently from 12ea019 to 1a0b238 Compare October 7, 2026 18:48
Base automatically changed from fix/engine-fixes-from-python to main October 7, 2026 18:49
bplatz added 5 commits October 7, 2026 14:49
fluree_db_api::Transaction (Fluree::begin_transaction) stages writes one at a
time over each other, reads the staged state through db(), and commits them
as one commit through the existing write path: under the ledger lock,
re-based over a concurrent commit to other subjects, otherwise staged again
on the new head.
Transaction::commit staged every operation again when another commit had
landed since the transaction began. That is right for operations that decide
their own effect, but a caller that read the staged state through db() may
have chosen its writes from what it read, and replaying them over data it
never saw loses the other commit's update. A read transaction now fails with
CommitConflict when the head has moved; unread transactions still re-base or
re-stage.
So a host can stage a `;` Cypher script one statement at a time, inside a
Transaction.
Transaction::stage_cypher stages a Cypher write — single statements,
conditional MERGE (its probe policy-wrapped), multi-clause writes — over the
operations before it, so one commit can mix Cypher, SPARQL UPDATE and
JSON-LD, each seeing the others. A statement keeps its skolem id, so staging
it again over a concurrent commit creates the same identities. RETURN rows
come back typed; receiving them counts as a read, so the commit then refuses
a ledger that moved.

begin_transaction takes GovernanceOptions instead of a built PolicyContext:
a MERGE's probe needs the options, and the context is built from the same
base state the operations stage on.
Transaction::savepoint() marks the operations staged so far and
rollback_to() discards those staged after it, rebuilding the staged state.
A caller staging a group that must apply all or nothing, such as a ;
Cypher script, uses it to undo the group's earlier operations when a later
one fails.
@bplatz
bplatz force-pushed the feat/engine-transactions branch from 1a0b238 to 7801824 Compare October 7, 2026 18:49
bplatz added 8 commits October 7, 2026 15:45
A transaction had no way to bound its work: stages ran with no tracker,
so SPARQL, Turtle and Cypher writes had no fuel limit, and the index
config was always the server default, so a host's own novelty limits
didn't govern the commit.

TransactionOptions carries the governance, a TrackingOptions and an
optional IndexConfig. One tracker spans the whole transaction, as it does
for Bolt's explicit transactions: every stage charges it, a max_fuel
limit bounds the transaction as a whole, and the tally comes back on the
commit result.
…olicy

begin_transaction built the policy context once, from the state the
transaction began on. When the head moved and the commit staged every
operation again over it, the writes were still checked under that
begin-time policy, so a deny rule committed while the transaction was
open didn't apply to it, though the transaction committed after the rule.

The re-stage now builds the policy context from the state it stages on.
That also covers a transaction begun with no policy at all, once a commit
in between configures one: such a commit touches the config graph, which
a re-base never crosses, so the transaction stages again under it.
rollback_to truncated the operations before it awaited the rebuild of
the stager. If that rebuild failed, or the call was dropped at the await
(a timeout, a select!, a request whose client went away), len() reported
the rollback while the old stager still held every operation, and
commit() wrote the operations reported as rolled back.

The new stager is now built first, and the operations truncated only
once it is in hand.
SequentialStager::stage_with took the virtual state before awaiting the
stage, so a failed stage lost it and Transaction rebuilt it by staging
every earlier operation again from the base. That re-minted blank nodes
and re-evaluated STRUUID()/NOW() values the caller had already read, cost
as much as the whole transaction for each failed stage, and a stage whose
future was dropped left nothing to rebuild from: the next call panicked.

stage_with now keeps the pre-operation state until the stage succeeds
(every field is an Arc, so the clone is refcount bumps) and releases it
before the in-place apply. A failed or dropped stage leaves the stager
untouched, and Transaction returns the error without re-staging.

Two paths still stage again. A Cypher write whose RETURN fails after it
staged marks the transaction stale before answering it, so a failure or
drop there has the next call stage the recorded operations again rather
than keep the statement. And rollback_to re-stages the operations before
its savepoint: JSON-LD inserts and updates and Turtle inserts now stage
under a skolem id pinned when they were added, as Cypher writes already
did, so their blank nodes keep the identities the caller read.
A Savepoint was a bare operation count, so one taken before a rollback
past it pointed into whatever was staged since: stage a, take sp1, stage
b, take sp2, roll back to sp1, stage c and d, and rolling back to sp2
kept c, which sp2 never saw.

Each staged operation now has an id, and a savepoint records the id of
the operation it follows. Returning to a savepoint whose operation a
rollback discarded is a NotFound error, as SQL treats a savepoint
released by a rollback past it.
Transaction::commit didn't note its path the way a single write's commit
does, so write_path_stats() couldn't tell a transaction that re-based
over a concurrent commit from one that staged again, and no test could
either: the re-base test passed with re-basing switched off.

The commit now notes Direct, Rebased or Restaged, and the two concurrent
commit tests assert which path they took.
…index

The netting fix for index-resident named-graph rows landed with the
single-write path's tests. begin_transaction nets through the same
stager, and is the path the Python package's ledger.transaction() takes,
so pin it there too: on a cold index, inserting and then deleting a
value the index holds in a named graph deletes it.
… read

Transaction::commit takes the process's own write path, as Bolt's
explicit transactions do, so a Raft or peer host must keep transactions
off its transport. Say so in the module docs and the Rust API guide.

An operation that fails to stage is left out without counting as a read,
the statement-level rollback most databases use. A caller that chooses
its next write from such an error has learned something about the data,
so the docs now point it at db(), which makes the commit require the
head the choice was made on.
@bplatz

bplatz commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

From the review summary:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:transact Staging, commit, import/bulk-import, novelty, retraction semantics enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants