Repository navigation
Description
Spun off from architectural-audit tracking issue #1228, finding B8. Backend-only; parallel-safe with all current frontend and #1243 work.
Background (from audit #1228)
B8 β Possible TOCTOU in bulk ops π‘
bulk_update_nodesandbulk_create_hierarchycallget_node()before / outside the surrounding transaction β read-then-update race; bulk op can partially complete.
Action: move reads inside the transaction or document the partial-failure contract.
Verified current state
packages/core/src/db/sqlite_store.rs:
bulk_update (line ~1611)
let tx = self.db.transaction().await?; // 1626: open transaction
for (id, update) in &updates {
let current = self.get_node(id).await? // 1633: READ via self.db POOL β outside tx!
.ok_or_else(|| anyhow!("Node not found: {}", id))?;
let updated_content = update.content.clone().unwrap_or(current.content);
let updated_node_type = update.node_type.clone().unwrap_or(current.node_type);
tx.execute("UPDATE node SET content=?1, node_type=?2, version=version+1, modified_at=?3 WHERE id=?4", ...) // 1641: WRITE via tx
}
tx.commit().await?;Two distinct problems:
- The read escapes the transaction.
get_node(line ~470) runs onself.db(the pool), not ontx. So the "read current values to fill unspecified fields" happens against connection state that is not the transaction's snapshot. Under SQLite's serialized writes the window is small, but the read-then-write is still not atomic with respect to the surroundingtx. - No OCC/version check in the bulk path.
bulk_updatereadscurrent.content/current.node_typeto preserve unspecified fields, then unconditionallyversion = version + 1. A concurrent single-node update between the read (1633) and thetx.execute(1641) is clobbered with noVersionConflictβ unlike the single-nodeupdate_nodepath which is version-checked. The "current" snapshot can be stale.
bulk_create_hierarchy (line ~1659)
Inserts within tx (lines ~1696+) and calls self.validate_node_type(node_type) (line ~1684) inside the loop. validate_node_type may itself touch the DB (schema lookup) outside tx. Lower risk than bulk_update (it's INSERTs of new ids, not read-modify-write of existing rows), but the validation read should be confirmed to not depend on uncommitted state, and a partial-failure mid-loop before commit should roll back cleanly (it does β tx drops without commit on the ? early-return β but document this).
The task
Pick ONE of the two approaches the audit allows, per function:
Option A β make the read transactional (preferred for bulk_update). Read current through tx (tx.query(...) against the same transaction) instead of self.get_node() on the pool, so the read-modify-write is one atomic unit. This closes the TOCTOU window.
Option B β restructure to avoid the read (cleaner if feasible). bulk_update only reads current to preserve content/node_type when the update leaves them unspecified. A single SQL UPDATE ... SET content = COALESCE(?1, content), node_type = COALESCE(?2, node_type), version = version + 1 ... does the "keep existing if not provided" entirely in SQL β no read needed, no TOCTOU. This is the cleanest fix and removes the read entirely. Use it unless an update field can't be expressed as COALESCE.
OCC decision (call it explicitly). Decide and document whether bulk_update should be version-checked like single-node update_node:
- If callers of
bulk_updateare trusted/internal batch paths where last-write-wins is acceptable β document thatbulk_updateis intentionally non-OCC (a deliberate fast-path), so the absence of version checking is a contract, not an oversight. - If any caller needs conflict detection β thread a per-node expected version through and abort the transaction on mismatch (
VersionConflict), matching the single-node contract. - Check the callers (
NodeService::bulk_update, the daemonupdate_nodes_batchRPC) to decide which.
bulk_create_hierarchy: confirm validate_node_type doesn't read uncommitted state, and document the partial-failure contract (early-return before commit rolls back the whole batch β verify and state it in a doc comment).
Acceptance criteria
-
bulk_update's read-modify-write is atomic: either the read goes throughtx(Option A) or the read is eliminated via in-SQL COALESCE (Option B). Noself.get_node()/pool read betweentxopen andtx.commit. - The OCC behavior of
bulk_updateis decided and documented in a doc comment (either version-checked, or explicitly last-write-wins-by-design with rationale). -
bulk_create_hierarchy: validation reads confirmed not to depend on uncommitted state; partial-failure/rollback contract documented in a doc comment. - No
#[allow(...)], no lint suppression.cargo clippy --workspace --all-targets -- -D warningsclean.
Testing
- Test that
bulk_updatewith partial field updates (onlycontent, onlynode_type) preserves the unspecified field correctly (proves the COALESCE/transactional-read path works). - Test that a failed bulk op (one bad id mid-batch) rolls back ALL changes β no partial commit (the audit's "bulk op can partially complete" concern).
- If OCC is added: test a version mismatch aborts the whole bulk update.
-
cargo test -p nodespace-core+cargo test --workspacegreen.
Coordination
- Backend-only, parallel-safe. No overlap with B4 follow-up: fold remaining 11 CollectionService::new daemon sites into core (collection_ops)Β #1243 (daemon collection_ops) or any frontend work.
- Note: B7 (B7: Remove SurrealDB-era fractional-ordering jitter β make ordering deterministic under SQLiteΒ #1256, merged) made ordering deterministic; this is unrelated (data integrity, not ordering).
Standard NodeSpace startup / PR sequence
EnterWorktree({name: "issue-<N>-bulk-op-toctou"}); bun install; baseline cargo test -p nodespace-core; bun run gh:assign/gh:status. Before PR: cargo test --workspace + bun run test:all (no new failures), bun run quality:fix (revert unrelated cargo fmt churn via git status), bun run gh:pr <N>, /pragmatic-code-review, then ExitWorktree + gh pr merge --squash --delete-branch.
Spun off from #1228 (architectural audit), finding B8.
Activity
fix(core): close TOCTOU in bulk_update via SQL COALESCE, document bulβ¦
fix(core): close TOCTOU in bulk_update via SQL COALESCE, document bulβ¦