diff --git a/docs/architecture/engine/store/README.md b/docs/architecture/engine/store/README.md index 09b94d8232..ba40977aa2 100644 --- a/docs/architecture/engine/store/README.md +++ b/docs/architecture/engine/store/README.md @@ -173,7 +173,7 @@ A PostgreSQL Store has no profile; its write setting is `synchronous_commit`. | `BackendError` | `PersistenceError` | `HistoryError` | Meaning | | --- | --- | --- | --- | | `Busy` | `Busy` | `Busy` | Another writer held the lock | -| `Closed` | `Refused "Closed"` | `OwnershipUnavailable` | Store closed before this call's turn | +| `Closed` | `Refused "Closed"` | `OwnershipUnavailable` | Store closed before this call's turn, or (PostgreSQL) a nested write found its lane lost and rolled back | | `Rejected` | `Refused "Rejected"` | `OwnershipUnavailable` | PostgreSQL refused a new connection | | `Cancelled` | `Refused "Cancelled"` | `OwnershipUnavailable` | A signal interrupted the writer wait (Linux and macOS) | | `ReadOnly` | `Refused "ReadOnly"` | `ContinuityUnavailable` | Write on a read-only session | @@ -181,7 +181,7 @@ A PostgreSQL Store has no profile; its write setting is `synchronous_commit`. | `Integrity` | `Malformed` | `Integrity("persistence")` | Stored or supplied data broke a rule | | `SchemaVersion1` | `Refused` (names the conversion) | `Integrity` | A schema version 1 SQLite Store | | `UnsupportedSchemaVersion` | `Refused` | `Unsupported` | Diagnostic open of an unknown layout | -| `Unknown` | `Uncertain` | `UnknownOutcome` | Outcome unknown; session quarantined | +| `Unknown` | `Uncertain` | `UnknownOutcome` | Outcome unknown; session quarantined, its connection closed and the writer lane released ([SQLite](sqlite.md#quarantine), [PostgreSQL](postgresql.md#session)) | Source: [`records.rs`](../../../../engine/crates/layerfs-persistence/src/backend/records.rs). @@ -191,7 +191,9 @@ Source: [`records.rs`](../../../../engine/crates/layerfs-persistence/src/backend | --- | --- | --- | --- | | [`heads.rs`](../../../../engine/crates/layerfs-persistence/tests/heads.rs) | `cargo +1.85.1 test --locked -p layerfs-persistence --test heads` | macOS, Linux (no-sidecar check Linux only) | Project, fork and Commit change the heads exactly; a snapshot has the same heads | | [`writer_admission.rs`](../../../../engine/crates/layerfs-persistence/tests/writer_admission.rs) | `cargo +1.85.1 test --locked -p layerfs-persistence --test writer_admission` | macOS, Linux (`Cancelled` Linux only) | FIFO order, `Closed` on close, writers queued behind the lane, self re-entry refused, the directory lock across processes and concurrent opens, its hand-over, and `Cancelled` | -| [`diagnostics_during_lane.rs`](../../../../engine/crates/layerfs-persistence/tests/diagnostics_during_lane.rs) | `cargo +1.85.1 test --locked -p layerfs-persistence --test diagnostics_during_lane` | any | Counter reads return while another thread holds the lane | +| [`diagnostics_during_lane.rs`](../../../../engine/crates/layerfs-persistence/tests/diagnostics_during_lane.rs) | `cargo +1.85.1 test --locked -p layerfs-persistence --test diagnostics_during_lane` | any (the foreign-lane case macOS, Linux) | Counter reads return while another thread holds the lane, and while the session waits for another session's lane | +| [`sqlite_quarantine_release.rs`](../../../../engine/crates/layerfs-persistence/tests/sqlite_quarantine_release.rs) | `cargo +1.85.1 test --locked -p layerfs-persistence --test sqlite_quarantine_release` | macOS, Linux; needs `python3` | An uncertain write, alone or nested in a held lane, closes its connection and frees the lane: a raw writer and a second session write at once, and the first session stays quarantined | +| [`postgresql_lane_liveness.rs`](../../../../engine/crates/layerfs-persistence/tests/postgresql_lane_liveness.rs) | `LAYERFS_TEST_POSTGRES_URL=… cargo +1.85.1 test --locked -p layerfs-persistence --test postgresql_lane_liveness` | a PostgreSQL server; prints `NOT_RUN` without the variable | A quarantined session closes its connection (no backend is left idle in its aborted transaction) and the lane row is free; a nested write after its lane connection was terminated fails `Closed` and writes nothing | | [`layerstack_removal.rs`](../../../../engine/crates/layerfs-persistence/tests/layerstack_removal.rs) | `cargo +1.85.1 test --locked -p layerfs-persistence --test layerstack_removal` | macOS, Linux; also PostgreSQL when `LAYERFS_TEST_POSTGRES_URL` is set | Removing one of two projects leaves the other whole, frees the name and takes its logical bytes out of the totals | | [`binding_hint_blocks.rs`](../../../../engine/crates/layerfs-persistence/tests/binding_hint_blocks.rs) | `cargo +1.85.1 test --locked -p layerfs-persistence --test binding_hint_blocks` | macOS, Linux | Hints merge across blocks without repeats | | [`postgresql_acquisition.rs`](../../../../engine/crates/layerfs-persistence/tests/postgresql_acquisition.rs) | `LAYERFS_TEST_POSTGRES_URL=… cargo +1.85.1 test --locked -p layerfs-persistence --test postgresql_acquisition` | a PostgreSQL server; prints `NOT_RUN` without the variable | Creating a PostgreSQL Store, refusing a second create, and Init's acquisition over it | diff --git a/docs/architecture/engine/store/postgresql.md b/docs/architecture/engine/store/postgresql.md index 9339cdfe84..7dba0d8961 100644 --- a/docs/architecture/engine/store/postgresql.md +++ b/docs/architecture/engine/store/postgresql.md @@ -36,7 +36,7 @@ There is no `postgresql` cargo feature: every build serves both Store kinds. | --- | --- | --- | | Types and order | `bigint`, `bytea`; history names `COLLATE "C"`, so paging matches SQLite byte order | [`schema.sql`](../../../../engine/crates/layerfs-persistence/sql/postgresql/schema.sql) | | Pack bodies | one `bytea` per pack, `STORAGE EXTERNAL` (uncompressed, out of line) for ranged `substring` reads; no `pack_unit` table | same | -| Object locations | narrow rows; no unique key on the id but a B-tree `object_location_prefix` on its first eight bytes, with the full id compared in the heap; a location is inserted only when its id is absent, which is unique because every location insert holds the lane | [`objects/publish.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/objects/publish.rs), [`metadata/reads.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/metadata/reads.rs) | +| Object locations | narrow rows; no unique key on the id but a B-tree `object_location_prefix` on its first eight bytes, with the full id compared in the heap; a location is inserted only when its id is absent, which is unique because every location insert holds the lane, including a nested one whose lane connection dies (see [the lane barrier](#lane-barrier)) | [`objects/publish.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/objects/publish.rs), [`metadata/reads.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/metadata/reads.rs) | | Short values | bounded `bytea`/`text` columns and both block bodies are `STORAGE PLAIN` (column storage in `CREATE TABLE`, PostgreSQL 16 or newer), so those tables have no TOAST relation | [`schema.sql`](../../../../engine/crates/layerfs-persistence/sql/postgresql/schema.sql) | | Merge records | `pg_temp` tables of the writer connection: outside the checked schema, seen by that connection only, gone with it; writes are `Stage` transactions | [`merge_records.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/merge_records.rs) | | Schema version | `SCHEMA_VERSION = 2`; 19 tables, or 22 with acquisition; version 1 is refused (`Integrity`), never converted | [`schema.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/schema.rs) | @@ -101,8 +101,10 @@ compaction holds one already and never retains the URL. admission: Admission FIFO turn, as on SQLite state: Mutex client (statement cache 256), quarantined, work counters - lane: Mutex> second connection, opened on first - hold_lane + lane: Mutex> + second connection, opened on first + hold_lane, with the id of its open + lane transaction settings: schema, synchronous_commit, lock_timeout_ms connector: Config + the process's one TLS connector, or none for sslmode=disable @@ -112,7 +114,8 @@ compaction holds one already and never retains the URL. | --- | --- | --- | | New connection answered with an error | `Rejected` | [`connection.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/session/connection.rs) | | No connection made, or none made and logged in within 5 s (the URL's `connect_timeout` when set; LF13) | `Closed` | same | -| Lost reply inside a transaction | `Unknown`; session quarantined | [`transaction.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/session/transaction.rs) | +| Lost reply inside a transaction, or a SQLSTATE without a definite rule (class 58, class XX, ...) | `Unknown`; session quarantined and its connection closed (below) | [`transaction.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/session/transaction.rs), [`rows.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/session/rows.rs) | +| A statement refused with a reply in class 21, 22, 23, 42, P0 (PL/pgSQL, such as the `pack_immutable` trigger's `P0001`) or 54 outside the capacity codes | `Integrity`, definite; the transaction is rolled back | [`rows.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/session/rows.rs) | | `COMMIT` refused (deferred constraint) | the error; counted as a rollback | same | | `round_trips` | each exchange that waits for the server; the handshake is not one | same | | `prepares`, `connects` | statement-cache misses and COPY statements; new connections (session and lane) | same | @@ -126,14 +129,29 @@ once per process, at the first connection whose `sslmode` may negotiate TLS. Every setting is `SET LOCAL` in the same round trip as `BEGIN`, so a transaction-pooling proxy never carries one session's settings to another. +A quarantine closes the session's ordinary connection (finding #3), and +the server ends its backend. Kept open, that backend stayed until the +process exited: a transaction the server aborted with an error has already +released its row locks, but the session's advisory keys (mount and +compaction presence) survive any abort, and an uncertain outcome that left +the transaction live (a lost reply, or a body error classed uncertain) kept +every row lock, a write's `store_lane` row included, so every other writer +failed `Busy` after its lock wait. Closing ends all of it. Nothing is replayed, +the outcome stays unknown, every later call is refused before it reaches a +connection, and `PostgresStorage::usable` answers `false`, so the caller +opens a new session. GC intent rows are untouched: an intent's owner stays +live by its recorded process, not by this connection. A diagnostic driver +keeps its read-only connection, whose deadline and cancellation outcome are +still read ([`connection.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/session/connection.rs)). + ## Transactions | `Mode` | `BEGIN` | Lane row | Used by | | --- | --- | --- | --- | | `Read` | `REPEATABLE READ READ ONLY` | no | history reads, policy, signatures | -| `Write` | `READ COMMITTED` + `synchronous_commit` + `lock_timeout` | `FOR UPDATE`, unless nested in the held lane | history writes, allocation, acquisition writes | +| `Write` | `READ COMMITTED` + `synchronous_commit` + `lock_timeout` | `FOR UPDATE` and the lane barrier; nested in the held lane: the barrier key shared and a lane check before `COMMIT` | history writes, allocation, acquisition writes | | `Stage` | `READ COMMITTED` + `synchronous_commit` | no | schema create, merge records | -| `Publish` | as `Write` | `FOR UPDATE` after the pack bodies, unless nested | one Save publication, up to 16 MiB − 1 | +| `Publish` | as `Write` | `FOR UPDATE` and the lane barrier after the pack bodies; nested: as a nested `Write` | one Save publication, up to 16 MiB − 1 | | `Snapshot` | `REPEATABLE READ` + `synchronous_commit` + `jit` off | no | the garbage-collection mark: reads history, locators and packs from one snapshot and writes only `kept_node` | | `Immutable` | none; autocommit statements | no | locates, pack reads, inode values | | `Statement` | none; exactly one autocommit statement | no | `branch_snapshot`, a Commit or Layer by id, a LayerStack by name, `digest_roots` (up to `FILE_DIGEST_WINDOW` = 1,024 contents) | @@ -291,9 +309,12 @@ Store. validate(batch) shared bounds, no SQL BEGIN; SET LOCAL ... ids already reserved: COPY BINARY pack bodies no lane needed yet - SELECT 1 FROM store_lane ... FOR UPDATE (skipped if nested) + SELECT 1 FROM store_lane ... FOR UPDATE; (skipped if nested: the + lane barrier barrier key is held + shared from BEGIN) one statement: INSERT locations ... RETURNING, totals, inode value blocks, released ordinals, signatures + nested? the lane check lost -> ROLLBACK, Closed COMMIT any failure rolls the whole publication back; ids are never reused ``` @@ -311,6 +332,36 @@ transactions. Dropping `LaneHold` rolls the lane transaction back (it wrote nothing) and releases the turn ([`lane.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/lane/lane.rs)). +### Lane barrier + +A nested write commits on the session connection while the row lock lives +in the lane connection's transaction. That connection can die mid-lane (an +`idle_in_transaction_session_timeout`, a keepalive, a failover or an +administrator), freeing the row while a nested write is still running, and +the head check and the `object_location` existence probe rely on the row +(finding #10). Two rules keep them exact without a unique key or a second +database ([`profile.rs`](../../../../engine/crates/layerfs-persistence/src/backend/postgresql/session/profile.rs)): + +```text + every writer, right after it locks store_lane (same round trip, same + lock_timeout): pg_advisory_lock(class, key); pg_advisory_unlock(class, key) + every nested Write/Publish: BEGIN ...; pg_advisory_xact_lock_shared(class, key) + body + lane check, one round trip on the lane connection: + pg_current_xact_id_if_assigned() = the id recorded at hold_lane? + no, or any error -> close the lane connection; ROLLBACK; Closed + COMMIT +``` + +The barrier key is a two-key advisory lock (a fixed class and a hash of the +schema name), a key space apart from the GC keys. A new lane holder takes it +exclusively and lets it go at once, so it cannot read anything until every +nested write of the previous holder that started before the row was freed +has ended; a nested write that starts after that point fails its lane +check, rolls back and answers `Closed` (`OwnershipUnavailable` in history +terms): nothing of it was kept. Its own holder never takes the key +exclusively while its lane is held, so its nested writes never wait for it. + | `SynchronousCommit` | Write acknowledged after | | --- | --- | | `Off` (default) | the server accepts it, before the WAL flush | diff --git a/docs/architecture/engine/store/sqlite.md b/docs/architecture/engine/store/sqlite.md index 3fd117ea4e..a353c3ed2c 100644 --- a/docs/architecture/engine/store/sqlite.md +++ b/docs/architecture/engine/store/sqlite.md @@ -55,8 +55,8 @@ UPDATE and DELETE on `pack` and `pack_unit`. Open checks `application_id`, | Open | `READ_WRITE` or `READ_ONLY`, `NO_MUTEX`; statement cache 64 | [`connection.rs`](../../../../engine/crates/layerfs-persistence/src/backend/sqlite/session/connection.rs) | | Guard | `busy_timeout=0`; `SQLITE_DBCONFIG_DEFENSIVE` on | same | | Settings | `profile::apply`, then read back into `ConnectionProfile`; a mismatch is `Integrity`; an existing Store not in `wal` mode is refused | [`profile.rs`](../../../../engine/crates/layerfs-persistence/src/backend/sqlite/session/profile.rs) | -| Checkpoint thread | writable Normal session only: a second connection on its own thread, opened with the session's `synchronous` value and read back; failure to start it refuses the open | [`background.rs`](../../../../engine/crates/layerfs-persistence/src/backend/sqlite/session/background.rs) | -| Last close | A writable session's close waits for `Writer::acquire(path)` like any write (or reuses the lane an uncertain transaction already holds), so its close, which may be SQLite's last, checkpoints and removes `-wal`/`-shm` under the lane; a pull's verify close and a restore's in-use check rely on that. If the wait itself fails (interrupted, or the directory cannot be opened), the close sets `SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE` first, so SQLite takes no exclusive lock, runs no checkpoint and removes nothing; there is no second attempt. If even that setting fails, the connection is kept until process exit. A read-only or diagnostic session cannot checkpoint or remove those files and takes no lane, so it never waits behind a writer kept after an uncertain write. The checkpoint thread's connection closes first and never takes it. One exception: an open whose checkpoint thread fails to start drops its new connection after the open's lane is released | [`lifecycle.rs`](../../../../engine/crates/layerfs-persistence/src/backend/sqlite/session/lifecycle.rs) | +| Checkpoint thread | writable Normal session only: a second connection on its own thread, opened with the session's `synchronous` value and `checkpoint_fullfsync=0`, both read back (the second as `ConnectionProfile::checkpoint_thread_checkpoint_fullfsync`); failure to start it refuses the open. It runs only the routine PASSIVE passes; the idle TRUNCATE and the last close run on the session's own connection, which has `checkpoint_fullfsync=1` (finding #11, narrowed by the owner 2026-11-23; see [Checkpoints](#checkpoints)) | [`background.rs`](../../../../engine/crates/layerfs-persistence/src/backend/sqlite/session/background.rs) | +| Last close | A writable session's close waits for `Writer::acquire(path)` like any write (or reuses the lane an uncertain transaction already holds), so its close, which may be SQLite's last, checkpoints and removes `-wal`/`-shm` under the lane; a pull's verify close and a restore's in-use check rely on that. If the wait itself fails (interrupted, or the directory cannot be opened), the close sets `SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE` first, so SQLite takes no exclusive lock, runs no checkpoint and removes nothing; there is no second attempt. If even that setting fails, the connection is kept until process exit. A read-only or diagnostic session cannot checkpoint or remove those files and takes no lane. The checkpoint thread's connection closes first and never takes it; after a quarantine closed the session's connection (see [Quarantine](#quarantine)) it may be SQLite's last, so it then closes with `SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE` and leaves `-wal`/`-shm` in place (kept until process exit if that setting fails). One exception: an open whose checkpoint thread fails to start drops its new connection after the open's lane is released | [`lifecycle.rs`](../../../../engine/crates/layerfs-persistence/src/backend/sqlite/session/lifecycle.rs) | | Setting | Normal | Source | | --- | --- | --- | @@ -83,12 +83,14 @@ SQL work to the calling thread's counters ```text SQLite write: Session::run(true, body) 1 admission.enter in-process FIFO turn on this session - 2 state mutex the connection - 3 Writer::acquire flock(LOCK_EX) on the Store's parent directory + 2 Writer::acquire flock(LOCK_EX) on the Store's parent directory (Linux and macOS) (skipped if nested) + 3 state mutex the connection; quarantined? release, Unknown; + identity checked under the lane 4 BEGIN IMMEDIATE busy_timeout 0 -> Busy 5 body; COMMIT or ROLLBACK; Unknown -> quarantine - 6 release the flock; drop the turn + 6 release the flock (after closing a quarantined connection); + drop the turn Session::hold_lane() -> LaneHold (!Send) writable? else ReadOnly; admission turn (nested -> Integrity); @@ -100,7 +102,10 @@ The lock is taken on a separate descriptor of the Store's directory (on macOS, a `flock` on the main file itself would meet SQLite's own `fcntl` locks), never on the main, WAL or SHM file: closing a main-file descriptor would drop SQLite's own POSIX locks. Several Store files in one directory -share it. It is the same lane on Linux and macOS: a holder process that +share it. The kernel wait happens before the state mutex, so a write +waiting for another process's lane never blocks `diagnostics()` or anything +else that takes only that mutex (finding #20); the FIFO turn already keeps +the session's other callers out. It is the same lane on Linux and macOS: a holder process that exits releases it, a signal during the wait is `Cancelled`, and a writable open takes it too, so concurrent first openers serialize their opening PRAGMA statements instead of meeting SQLite's `Busy`; the schema statements @@ -108,11 +113,36 @@ a first open runs then take it once per transaction. Only a writer that bypasses the lane is left with the exact `Busy`. The lane is one held admission turn plus that lock, kept by one thread across several short transactions, and no publication of any process interleaves. `LaneHold` is -`!Send`: it belongs to the thread that took it; a failed release on its drop -quarantines the session and keeps the lock +`!Send`: it belongs to the thread that took it; its drop first closes the +connection of a session that nested work quarantined (see below), and a +failed release quarantines the session and keeps the lock ([`writer_admission.rs`](../../../../engine/crates/layerfs-persistence/src/backend/sqlite/lane/writer_admission.rs), [`lane.rs`](../../../../engine/crates/layerfs-persistence/src/backend/sqlite/lane/lane.rs)). +### Quarantine + +An unknown outcome (`SQLITE_IOERR`, `SQLITE_CANTOPEN`, a generic +`SQLITE_ERROR` and every other code without a definite rule, or a body +error that is uncertain at a higher level) quarantines the session: every +later call is refused `Unknown` and nothing is replayed. SQLite may still +hold the attempt's write transaction, which keeps other connections out +just as the lane does, so the lane cannot simply be released. Instead, +while the lane is still held by this thread (the job's own writer, or a +held `LaneHold` around nested work), the quarantined connection is closed: +`sqlite3_close` rolls back whatever transaction is open and drops SQLite's +locks, and may run SQLite's last-close checkpoint under that same lane. +Only then is the lane released, so SQLite teardown still precedes advisory +release, and other sessions and processes take the lane at once instead +of waiting until this session drops, which for a daemon was process exit +(finding #2). The outcome stays unknown and the session stays quarantined; +its caller opens a new session. rusqlite flushes its statement cache before +the close and every statement or BLOB handle borrows the connection, so +SQLite has nothing to refuse the close on; if it ever did with a +transaction still open, the lane would stay with the connection until the +session drops, as before +([`lifecycle.rs`](../../../../engine/crates/layerfs-persistence/src/backend/sqlite/session/lifecycle.rs)). +A read that quarantines holds no lane and closes nothing. + ## Checkpoints ```text @@ -133,6 +163,8 @@ quarantines the session and keeps the lock | --- | --- | | A pass that cannot copy every frame leaves them valid; the next wake, the idle checkpoint or the last close copies them. Each wake is a new pass, never a retry. | [`background.rs`](../../../../engine/crates/layerfs-persistence/src/backend/sqlite/session/background.rs) | | A PASSIVE checkpoint takes no lock a writer needs, so it adds no `Busy`. | same | +| Routine passes sync the Store file with plain `fsync` (`checkpoint_fullfsync=0` on the thread's connection). The idle TRUNCATE, `checkpoint_holding` and the last close run on the session's own connection with `checkpoint_fullfsync=1`, so on macOS a checkpoint there syncs with `F_FULLFSYNC` (owner, 2026-11-23: narrowed from every pass, which on the macOS host pushed `kept_node_closure`, `kept_objects_sort_files` and store-service `scale_lineage_cap` past the 120 s test ceiling; one sample each). Linux ignores both settings. | same | +| **Remaining window (macOS only).** On macOS `fsync` does not flush the drive's write cache, so after a routine pass the copied pages may still sit only in that cache. Once a pass has copied every frame, the next write restarts the log over those frames; a power loss before the pages leave the cache can then lose database pages, not only the last commits. A later `F_FULLFSYNC` flushes the whole drive cache and closes the window, but SQLite syncs the Store file during a checkpoint only when that checkpoint copies at least one frame: an idle TRUNCATE or last close that finds every frame already copied truncates or deletes the log with no sync at all. Linux is unaffected. No power-loss guarantee is claimed for the Normal profile until layerfs-project#155 §7.5/§7.6 runs. | [`sqlite3.c`](https://sqlite.org/src/file/src/wal.c) `walCheckpoint` | | The idle TRUNCATE takes the writer lane first, because it holds SQLite's WAL write lock; `Ok(false)` is never retried. The Store stays open. Every host that opens a SQLite Store takes this lane, so a writer waits for it or the checkpoint is left, and only a writer that bypasses the lane meets exact `Busy`. | [`checkpoint.rs`](../../../../engine/crates/layerfs-persistence/src/backend/sqlite/session/checkpoint.rs) | | Control's open-Store cache calls it when the last call or Sandbox on a Store returns. | [`open.rs`](../../../../control/crates/layerfs-store/src/open.rs) | diff --git a/engine/crates/layerfs-persistence/src/backend/postgresql/lane/lane.rs b/engine/crates/layerfs-persistence/src/backend/postgresql/lane/lane.rs index 865d8f283c..b3f06d2325 100644 --- a/engine/crates/layerfs-persistence/src/backend/postgresql/lane/lane.rs +++ b/engine/crates/layerfs-persistence/src/backend/postgresql/lane/lane.rs @@ -5,11 +5,30 @@ //! at its own COMMIT; every other writer, in any process, waits for the row. //! Never SERIALIZABLE and never retried: a wait that reaches the timeout is //! `Busy`. Dropping the hold rolls its transaction back (it wrote nothing). +//! The lane transaction's id is recorded when it begins, so a nested write +//! can prove, before its COMMIT, that the row lock it relies on still exists +//! (finding #10; the barrier is described in `session/profile.rs`). use crate::backend::postgresql::session::{connection::Session, rows}; use crate::backend::records::BackendError; use layerfs_telemetry::timer::waits::Wait; +use postgres::{Client, SimpleQueryMessage}; use std::{marker::PhantomData, sync::Arc}; +/// The connection that holds the lane, and the id of its open lane +/// transaction while a hold lives. +pub(crate) struct LaneConnection { + client: Client, + xid: Option, +} + +/// The last row's first column of a simple-query reply. +fn last_value(messages: &[SimpleQueryMessage]) -> Option { + messages.iter().rev().find_map(|message| match message { + SimpleQueryMessage::Row(row) => row.get(0).map(str::to_owned), + _ => None, + }) +} + /// A held lane; dropping it releases the lane row, then the turn. pub struct LaneHold { session: Arc, @@ -29,21 +48,38 @@ impl Session { let mut lane = self.lane.lock().map_err(|_| BackendError::Unknown)?; if lane.is_none() { self.lane_work.add(1, 0); - *lane = Some(self.connector.connect()?); + *lane = Some(LaneConnection { + client: self.connector.connect()?, + xid: None, + }); } - let client = lane.as_mut().ok_or(BackendError::Unknown)?; + let connection = lane.as_mut().ok_or(BackendError::Unknown)?; self.lane_work.add(0, 1); - if let Err(e) = client.batch_execute(&self.settings.lane_begin()) { - let error = rows::error(&e); - if error != BackendError::Unknown { - self.lane_work.add(0, 1); - if client.batch_execute("ROLLBACK").is_ok() { - return Err(error); + let begin = format!( + "{}; SELECT pg_current_xact_id()::text", + self.settings.lane_begin() + ); + match connection.client.simple_query(&begin) { + Ok(messages) => match last_value(&messages) { + Some(xid) => connection.xid = Some(xid), + None => { + // No id came back: the lane cannot be proven later. + *lane = None; + return Err(BackendError::Unknown); } + }, + Err(e) => { + let error = rows::error(&e); + if error != BackendError::Unknown { + self.lane_work.add(0, 1); + if connection.client.batch_execute("ROLLBACK").is_ok() { + return Err(error); + } + } + // Closing the connection ends whatever the server still holds. + *lane = None; + return Err(BackendError::Unknown); } - // Closing the connection ends whatever the server still holds. - *lane = None; - return Err(BackendError::Unknown); } drop(lane); turn.hold()?; @@ -54,6 +90,38 @@ impl Session { } } +impl Session { + /// One round trip on the lane connection, before a nested write's + /// COMMIT: `Ok` only when the lane transaction recorded at `hold_lane` is + /// still the open transaction of a live connection, so the lane row is + /// still locked. Anything else (a closed connection, an error, another or + /// no transaction) closes the lane connection and is `Closed`: the caller + /// rolls its write back, a definite failure. The barrier key the write + /// holds keeps a new lane holder out until then. + pub(crate) fn lane_still_held(&self) -> Result<(), BackendError> { + let mut lane = self.lane.lock().map_err(|_| BackendError::Unknown)?; + let Some(connection) = lane.as_mut() else { + return Err(BackendError::Closed); + }; + let Some(expected) = connection.xid.clone() else { + return Err(BackendError::Closed); + }; + self.lane_work.add(0, 1); + let held = connection + .client + .simple_query("SELECT pg_current_xact_id_if_assigned()::text") + .ok() + .and_then(|messages| last_value(&messages)) + .is_some_and(|xid| xid == expected); + if !held { + // Closing it ends whatever that connection still holds. + *lane = None; + return Err(BackendError::Closed); + } + Ok(()) + } +} + impl Drop for LaneHold { fn drop(&mut self) { let mut lane = self @@ -61,9 +129,10 @@ impl Drop for LaneHold { .lane .lock() .unwrap_or_else(|poison| poison.into_inner()); - if let Some(client) = lane.as_mut() { + if let Some(connection) = lane.as_mut() { + connection.xid = None; self.session.lane_work.add(0, 1); - if client.batch_execute("ROLLBACK").is_err() { + if connection.client.batch_execute("ROLLBACK").is_err() { // The server ends the transaction, and its row lock, with the connection. *lane = None; } diff --git a/engine/crates/layerfs-persistence/src/backend/postgresql/session/connection.rs b/engine/crates/layerfs-persistence/src/backend/postgresql/session/connection.rs index 787613bff2..8c51efb9b4 100644 --- a/engine/crates/layerfs-persistence/src/backend/postgresql/session/connection.rs +++ b/engine/crates/layerfs-persistence/src/backend/postgresql/session/connection.rs @@ -31,6 +31,32 @@ pub(crate) struct State { } impl State { + /// Quarantines the session after an uncertain outcome. An ordinary + /// connection is closed (finding #3), so the server ends its backend. + /// Kept open, that backend stayed until this process exited: a + /// transaction the server aborted with an error has already released its + /// row locks, but session advisory keys survive any abort, and an + /// uncertain outcome that left the transaction live (a lost reply, or a + /// body error classed uncertain) kept every row lock, a write's + /// `store_lane` row included, so every other writer met `Busy` after its + /// lock wait. Closing ends all of it. Nothing is replayed and the outcome + /// stays unknown; every later call is refused before it reaches a + /// connection, and the caller opens a new session. GC intent rows are not + /// touched: an intent's owner stays live by its recorded process, not by + /// this connection. A diagnostic driver keeps its connection: it is + /// read-only, holds no lane, and its deadline and cancellation outcome + /// are still read. + pub(crate) fn quarantine(&mut self) { + self.quarantined = true; + if matches!(self.client, super::driver::Driver::Sync(_)) { + self.statements.clear(); + drop(std::mem::replace( + &mut self.client, + super::driver::Driver::Closed, + )); + } + } + /// One prepared statement for `sql`, prepared once per connection. pub(crate) fn statement(&mut self, sql: &str) -> Result { if let Some(statement) = self.statements.get(sql) { @@ -182,7 +208,7 @@ pub(crate) struct Session { pub(crate) admission: Admission, pub(crate) state: Mutex, /// The connection that holds the publication lane, opened on first use. - pub(crate) lane: Mutex>, + pub(crate) lane: Mutex>, pub(crate) writable: bool, pub(crate) settings: Settings, /// The server's version and the Store's frozen policy, read by the diff --git a/engine/crates/layerfs-persistence/src/backend/postgresql/session/driver.rs b/engine/crates/layerfs-persistence/src/backend/postgresql/session/driver.rs index ed6cf45586..30d0df0f2a 100644 --- a/engine/crates/layerfs-persistence/src/backend/postgresql/session/driver.rs +++ b/engine/crates/layerfs-persistence/src/backend/postgresql/session/driver.rs @@ -47,6 +47,9 @@ impl Error { pub(crate) enum Driver { Sync(Client), Diagnostic(Diagnostic), + /// An ordinary connection closed by quarantine (`State::quarantine`); + /// every call is refused as an unknown outcome without reaching a server. + Closed, } pub(crate) struct Diagnostic { client: tokio_postgres::Client, @@ -241,6 +244,7 @@ impl Driver { match self { Self::Sync(client) => client.prepare(sql).map_err(Into::into), Self::Diagnostic(client) => client.run(client.client.prepare(sql)), + Self::Closed => Err(Error::Refused(BackendError::Unknown)), } } pub(crate) fn query( @@ -251,6 +255,7 @@ impl Driver { match self { Self::Sync(client) => client.query(statement, params).map_err(Into::into), Self::Diagnostic(client) => client.run(client.client.query(statement, params)), + Self::Closed => Err(Error::Refused(BackendError::Unknown)), } } pub(crate) fn query_one( @@ -269,36 +274,42 @@ impl Driver { match self { Self::Sync(client) => client.simple_query(sql).map_err(Into::into), Self::Diagnostic(client) => client.run(client.client.simple_query(sql)), + Self::Closed => Err(Error::Refused(BackendError::Unknown)), } } pub(crate) fn batch_execute(&mut self, sql: &str) -> Result<(), Error> { match self { Self::Sync(client) => client.batch_execute(sql).map_err(Into::into), Self::Diagnostic(client) => client.run(client.client.batch_execute(sql)), + Self::Closed => Err(Error::Refused(BackendError::Unknown)), } } pub(crate) fn copy_in(&mut self, statement: &Statement) -> Result, Error> { match self { Self::Sync(client) => client.copy_in(statement).map_err(Into::into), Self::Diagnostic(_) => Err(Error::Refused(BackendError::ReadOnly)), + Self::Closed => Err(Error::Refused(BackendError::Unknown)), } } pub(crate) fn is_valid(&mut self, timeout: Duration) -> Result<(), Error> { match self { Self::Sync(client) => client.is_valid(timeout).map_err(Into::into), Self::Diagnostic(client) => client.run(client.client.batch_execute("")), + Self::Closed => Err(Error::Refused(BackendError::Unknown)), } } pub(crate) fn cancellation(&self) -> Option> { match self { Self::Sync(_) => None, Self::Diagnostic(client) => Some(client.cancelled.clone()), + Self::Closed => None, } } pub(crate) fn released(&self) -> Option { match self { Self::Sync(_) => None, Self::Diagnostic(client) => client.released.get(), + Self::Closed => None, } } pub(crate) fn close(self) -> Result<(), Error> { @@ -308,6 +319,7 @@ impl Driver { drop(client); Ok(()) } + Self::Closed => Ok(()), } } } diff --git a/engine/crates/layerfs-persistence/src/backend/postgresql/session/profile.rs b/engine/crates/layerfs-persistence/src/backend/postgresql/session/profile.rs index f5ea0b81a8..fc2b101545 100644 --- a/engine/crates/layerfs-persistence/src/backend/postgresql/session/profile.rs +++ b/engine/crates/layerfs-persistence/src/backend/postgresql/session/profile.rs @@ -79,7 +79,7 @@ impl Settings { /// A publication: like `write_begin(false)` with the lane's /// `lock_timeout`; the body takes the lane row itself, after its pack - /// bodies are sent, with [`Self::LANE_ROW`]. + /// bodies are sent, with [`Self::lane_row`]. pub(crate) fn publish_begin(&self) -> String { format!( "{}; SET LOCAL lock_timeout TO {}", @@ -88,8 +88,22 @@ impl Settings { ) } - /// The statement that waits for and locks the Store's lane row. - pub(crate) const LANE_ROW: &'static str = "SELECT 1 FROM store_lane WHERE id = 1 FOR UPDATE"; + /// The statements that wait for and lock the Store's lane row, then pass + /// the lane barrier (see [`lane_barrier`]). + pub(crate) fn lane_row(schema: &str) -> String { + format!( + "SELECT 1 FROM store_lane WHERE id = 1 FOR UPDATE; {}", + lane_barrier(schema) + ) + } + + /// Appended to the `BEGIN` of a write nested in this thread's held lane: + /// the barrier key, held shared until the transaction ends, so a new lane + /// holder's barrier waits for this write (see [`lane_barrier`]). + pub(crate) fn in_lane(&self) -> String { + let (class, key) = barrier_key(&self.schema); + format!("; SELECT pg_advisory_xact_lock_shared({class}, {key})") + } /// The held publication lane: one open transaction owning the lane row. pub(crate) fn lane_begin(&self) -> String { @@ -104,7 +118,35 @@ impl Settings { format!( "; SET LOCAL lock_timeout TO {}; {}", self.lock_timeout_ms, - Self::LANE_ROW + Self::lane_row(&self.schema) ) } } + +/// The two-key advisory lock of one Store's lane barrier (finding #10): a +/// fixed class and a stable hash of the schema name. The two-key form is a +/// separate key space from the one-key GC advisory keys; two schemas whose +/// hashes collide only share a barrier, which can make one wait, never pass. +fn barrier_key(schema: &str) -> (i32, i32) { + // FNV-1a, 32 bits: stable across processes, builds and machines. + let hash = schema.bytes().fold(0x811c_9dc5_u32, |hash, byte| { + (hash ^ u32::from(byte)).wrapping_mul(0x0100_0193) + }); + (0x4c46_4c4e, hash as i32) +} + +/// Run by every writer right after it locks the lane row, under the same +/// `lock_timeout`. Writes nested in a held lane commit on the session +/// connection while the row lock lives in the lane connection's transaction; +/// if that connection dies (an idle-in-transaction timeout, a keepalive or an +/// administrator), the row is free while such a write may still be running. +/// Each nested write holds the barrier key shared for its whole transaction +/// and checks before `COMMIT` that its lane transaction is still open; a new +/// holder takes the key exclusively and lets it go at once, so it waits for +/// any nested write of the previous holder still in flight before it reads +/// anything. Together they keep the head check and the `object_location` +/// existence probe exact without a unique key or a second database. +fn lane_barrier(schema: &str) -> String { + let (class, key) = barrier_key(schema); + format!("SELECT pg_advisory_lock({class}, {key}); SELECT pg_advisory_unlock({class}, {key})") +} diff --git a/engine/crates/layerfs-persistence/src/backend/postgresql/session/rows.rs b/engine/crates/layerfs-persistence/src/backend/postgresql/session/rows.rs index 9a149b159e..c05a290206 100644 --- a/engine/crates/layerfs-persistence/src/backend/postgresql/session/rows.rs +++ b/engine/crates/layerfs-persistence/src/backend/postgresql/session/rows.rs @@ -44,6 +44,11 @@ pub fn sqlstate(code: &str) -> BackendError { _ if code.starts_with("23") || code.starts_with("22") || code.starts_with("42") => { BackendError::Integrity } + // A statement the server refused with a reply: cardinality violation + // (class 21) and PL/pgSQL errors (class P0), among them `P0001` from + // the `pack_immutable` trigger's RAISE EXCEPTION. The statement, and + // the transaction it ran in, definitely failed; nothing was committed. + _ if code.starts_with("21") || code.starts_with("P0") => BackendError::Integrity, // Connection, shutdown, resource-class and internal failures: the // outcome is unknown. _ => BackendError::Unknown, diff --git a/engine/crates/layerfs-persistence/src/backend/postgresql/session/transaction.rs b/engine/crates/layerfs-persistence/src/backend/postgresql/session/transaction.rs index aa83347dc6..44f5ca0ce2 100644 --- a/engine/crates/layerfs-persistence/src/backend/postgresql/session/transaction.rs +++ b/engine/crates/layerfs-persistence/src/backend/postgresql/session/transaction.rs @@ -230,7 +230,7 @@ impl Transaction<'_> { /// transaction that is not already inside this thread's held lane. pub(crate) fn lane(&self) -> Result<(), BackendError> { if self.lane.replace(false) { - self.query(super::profile::Settings::LANE_ROW, Vec::new())?; + self.batch(&super::profile::Settings::lane_row(self.schema))?; } Ok(()) } @@ -346,11 +346,17 @@ impl Session { ); let expected = generation.filter(|_| transactional); let autocommit = generation.filter(|_| matches!(mode, Mode::Immutable | Mode::Statement)); + // A write nested in this thread's held lane relies on the lane + // connection's row lock: it holds the lane barrier shared and checks + // that lane transaction before its COMMIT (finding #10). + let in_lane = turn.nested && matches!(mode, Mode::Write | Mode::Publish); let begin = match mode { Mode::Read => self.settings.read_begin(), Mode::Snapshot => self.settings.snapshot_begin(), - Mode::Write => self.settings.write_begin(!turn.nested), + Mode::Write if in_lane => self.settings.write_begin(false) + &self.settings.in_lane(), + Mode::Write => self.settings.write_begin(true), Mode::Stage => self.settings.write_begin(false), + Mode::Publish if in_lane => self.settings.publish_begin() + &self.settings.in_lane(), Mode::Publish => self.settings.publish_begin(), Mode::Immutable | Mode::Statement => { let single = (mode == Mode::Statement).then(|| Cell::new(false)); @@ -379,7 +385,7 @@ impl Session { .ok_or(BackendError::Integrity)?; if generation != expected { if rollback(state).is_err() { - state.quarantined = true; + state.quarantine(); return Err(BackendError::Unknown.into()); } state.work.rollbacks += 1; @@ -389,7 +395,7 @@ impl Session { Err(e) => { let error = e.backend(); if error == BackendError::Unknown || rollback(state).is_err() { - state.quarantined = true; + state.quarantine(); return Err(BackendError::Unknown.into()); } state.work.rollbacks += 1; @@ -399,7 +405,7 @@ impl Session { } else if let Err(e) = state.client.batch_execute(&begin) { let error = e.backend(); if error == BackendError::Unknown || rollback(state).is_err() { - state.quarantined = true; + state.quarantine(); return Err(BackendError::Unknown.into()); } state.work.rollbacks += 1; @@ -428,10 +434,19 @@ impl Session { (result, uncertain) }; if uncertain { - state.quarantined = true; + state.quarantine(); return Err(BackendError::Unknown.into()); } match result { + Ok(_) if in_lane && self.lane_still_held().is_err() => { + // The lane was lost: nothing of this write is kept. + if rollback(state).is_err() { + state.quarantine(); + return Err(BackendError::Unknown.into()); + } + state.work.rollbacks += 1; + Err(BackendError::Closed.into()) + } Ok(value) => { let commit = Instant::now(); state.work.round_trips += 1; @@ -450,7 +465,7 @@ impl Session { // the server refused (a deferred constraint) rolled back. let error = e.backend(); if error == BackendError::Unknown { - state.quarantined = true; + state.quarantine(); } else { state.work.rollbacks += 1; } @@ -460,7 +475,7 @@ impl Session { } Err(e) => { if rollback(state).is_err() { - state.quarantined = true; + state.quarantine(); return Err(BackendError::Unknown.into()); } state.work.rollbacks += 1; @@ -563,7 +578,7 @@ fn immutable + OutcomeError>( (result, uncertain) }; if uncertain || result.as_ref().err().is_some_and(OutcomeError::uncertain) { - state.quarantined = true; + state.quarantine(); return Err(BackendError::Unknown.into()); } result diff --git a/engine/crates/layerfs-persistence/src/backend/postgresql/storage/provider.rs b/engine/crates/layerfs-persistence/src/backend/postgresql/storage/provider.rs index 3aa8e72f8c..fb2bbfff11 100644 --- a/engine/crates/layerfs-persistence/src/backend/postgresql/storage/provider.rs +++ b/engine/crates/layerfs-persistence/src/backend/postgresql/storage/provider.rs @@ -46,7 +46,7 @@ impl PostgresStorage { state.work.round_trips += 1; let alive = state.client.is_valid(std::time::Duration::from_secs(5)); if alive.is_err() { - state.quarantined = true; + state.quarantine(); } alive.is_ok() } diff --git a/engine/crates/layerfs-persistence/src/backend/sqlite/lane/lane.rs b/engine/crates/layerfs-persistence/src/backend/sqlite/lane/lane.rs index 3d58695311..a5f267e626 100644 --- a/engine/crates/layerfs-persistence/src/backend/sqlite/lane/lane.rs +++ b/engine/crates/layerfs-persistence/src/backend/sqlite/lane/lane.rs @@ -52,7 +52,18 @@ impl LaneHold { impl Drop for LaneHold { fn drop(&mut self) { if let Some(writer) = self.writer.take() { - if let Err(retained) = writer.release() { + // Nested work that quarantined the session may have left a write + // transaction open on its connection. That connection is closed + // here, while this thread still holds the lane, before the lane + // is released (finding #2); if SQLite refuses the close with a + // transaction open, the lane stays with the connection instead. + let mut writer = Some(writer); + if let Ok(mut state) = self.session.state.lock() { + if state.quarantined && !state.close_quarantined(self.session.background.as_ref()) { + state.writer_hold = writer.take(); + } + } + if let Some(Err(retained)) = writer.map(Writer::release) { // As a failed per-job release: keep the lock, refuse later work. if let Ok(mut state) = self.session.state.lock() { state.quarantined = true; diff --git a/engine/crates/layerfs-persistence/src/backend/sqlite/lane/writer_admission.rs b/engine/crates/layerfs-persistence/src/backend/sqlite/lane/writer_admission.rs index 2c58af8ecb..cae7a6872e 100644 --- a/engine/crates/layerfs-persistence/src/backend/sqlite/lane/writer_admission.rs +++ b/engine/crates/layerfs-persistence/src/backend/sqlite/lane/writer_admission.rs @@ -110,18 +110,28 @@ impl Writer { } impl crate::backend::sqlite::session::connection::State { - pub(crate) fn finish_writer(&mut self) -> Result<(), BackendError> { - if self.quarantined { - // Connection is declared before this retained owner in State, so - // SQLite teardown precedes advisory release at last-session drop. + /// Releases the writer this State holds for one job. A quarantined + /// State first closes its connection under that writer, so SQLite + /// teardown (the rollback of any transaction the uncertain attempt left + /// open, and a last close's checkpoint) still precedes advisory release, + /// and the lane is not kept until the Session drops (finding #2). + pub(crate) fn finish_writer( + &mut self, + background: Option<&crate::backend::sqlite::session::background::Checkpointer>, + ) -> Result<(), BackendError> { + let Some(writer) = self.writer_hold.take() else { + return Ok(()); + }; + if self.quarantined && !self.close_quarantined(background) { + // SQLite may still hold a write transaction: the writer stays + // with the connection, declared before it in State. + self.writer_hold = Some(writer); return Ok(()); } - if let Some(writer) = self.writer_hold.take() { - if let Err(retained) = writer.release() { - self.quarantined = true; - self.writer_hold = Some(retained); - return Err(BackendError::Unknown); - } + if let Err(retained) = writer.release() { + self.quarantined = true; + self.writer_hold = Some(retained); + return Err(BackendError::Unknown); } Ok(()) } diff --git a/engine/crates/layerfs-persistence/src/backend/sqlite/session/background.rs b/engine/crates/layerfs-persistence/src/backend/sqlite/session/background.rs index 6f1cdbc999..6e98aa2b01 100644 --- a/engine/crates/layerfs-persistence/src/backend/sqlite/session/background.rs +++ b/engine/crates/layerfs-persistence/src/backend/sqlite/session/background.rs @@ -16,6 +16,7 @@ use super::{query, rows}; use crate::backend::records::BackendError; use rusqlite::{Connection, OpenFlags}; use std::path::Path; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{mpsc, Arc, Mutex, MutexGuard}; use std::thread::JoinHandle; @@ -25,6 +26,10 @@ const LOG_BYTES: u64 = 4_194_304; pub(crate) struct Checkpointer { /// Held by the thread for one pass, and by an idle checkpoint. pass: Arc>, + /// Set once the session's own connection was closed under quarantine + /// (finding #2): this connection may then be SQLite's last, and it closes + /// without the lane, so it must not checkpoint or remove `-wal`/`-shm`. + quiet: Arc, wake: Option>, thread: Option>, } @@ -39,7 +44,16 @@ impl Checkpointer { /// frames into the database file, so it must synchronize exactly as the /// session does: under NORMAL a pass at 0 would mark frames copied that /// never reached the disk, and the writer would restart the log over them. - pub(crate) fn start(path: &Path, synchronous: i64) -> Result { + /// + /// The connection sets `checkpoint_fullfsync=0` and reads it back: a + /// routine pass syncs the Store file with plain `fsync`, which on macOS + /// does not flush the drive's cache (owner, 2026-11-23: F_FULLFSYNC on + /// every pass pushed write-heavy suites past the 120 s test ceiling). The + /// idle TRUNCATE and the last close run on the session's own connection, + /// which sets `checkpoint_fullfsync=1` (`profile.rs`, finding #11); the + /// window this leaves is in `docs/architecture/engine/store/sqlite.md`. + /// Returns the read-back value. + pub(crate) fn start(path: &Path, synchronous: i64) -> Result<(Self, i64), BackendError> { let connection = Connection::open_with_flags( path, OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_NO_MUTEX, @@ -55,6 +69,7 @@ impl Checkpointer { for pragma in [ format!("PRAGMA synchronous={synchronous}"), "PRAGMA fullfsync=0".to_owned(), + "PRAGMA checkpoint_fullfsync=0".to_owned(), "PRAGMA wal_autocheckpoint=0".to_owned(), ] { query::run(&connection, &pragma, vec![], &work)?; @@ -66,6 +81,14 @@ impl Checkpointer { if applied != synchronous { return Err(BackendError::Integrity); } + let checkpoint_fullfsync = + query::run(&connection, "PRAGMA checkpoint_fullfsync", vec![], &work)? + .first() + .ok_or(BackendError::Integrity)? + .get::(0)?; + if checkpoint_fullfsync != 0 { + return Err(BackendError::Integrity); + } let mode = query::run(&connection, "PRAGMA journal_mode", vec![], &work)? .first() .ok_or(BackendError::Integrity)? @@ -74,8 +97,10 @@ impl Checkpointer { return Err(BackendError::Integrity); } let pass = Arc::new(Mutex::new(())); + let quiet = Arc::new(AtomicBool::new(false)); let (wake, woken) = mpsc::sync_channel::<()>(1); let held = pass.clone(); + let quietly = quiet.clone(); let thread = std::thread::Builder::new() .name("layerfs-store-checkpoint".to_owned()) .spawn(move || { @@ -86,13 +111,35 @@ impl Checkpointer { let _ = query::run(&connection, "PRAGMA wal_checkpoint(PASSIVE)", vec![], &work); } + if quietly.load(Ordering::Acquire) + && connection + .set_db_config( + rusqlite::config::DbConfig::SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, + true, + ) + .is_err() + { + // As `State::drop`: retain it until process exit rather + // than tear the WAL down outside the lane. + std::mem::forget(connection); + } }) .map_err(|_| BackendError::Unknown)?; - Ok(Self { - pass, - wake: Some(wake), - thread: Some(thread), - }) + Ok(( + Self { + pass, + quiet, + wake: Some(wake), + thread: Some(thread), + }, + checkpoint_fullfsync, + )) + } + + /// Makes this connection's eventual close skip SQLite's checkpoint and + /// sidecar removal (finding #2): see `State::close_quarantined`. + pub(crate) fn close_quietly(&self) { + self.quiet.store(true, Ordering::Release); } /// After a write commits: wakes the thread when the log at `path` is @@ -115,9 +162,11 @@ impl Checkpointer { impl Drop for Checkpointer { /// Ends the thread after its current pass and closes its connection, /// before the session's own connection closes. - /// This connection is therefore never SQLite's last one: State still owns - /// the main connection. Do not reacquire its directory lane here; a - /// quarantined State may already retain it while this join completes. + /// This connection is SQLite's last one only after a quarantined State + /// closed the main connection, and that close set `quiet`, so this close + /// then neither checkpoints nor removes the WAL and SHM files. Do not + /// reacquire the directory lane here; a quarantined State may still + /// retain it while this join completes. fn drop(&mut self) { self.wake.take(); if let Some(thread) = self.thread.take() { diff --git a/engine/crates/layerfs-persistence/src/backend/sqlite/session/checkpoint.rs b/engine/crates/layerfs-persistence/src/backend/sqlite/session/checkpoint.rs index ae2af52d8f..af00f07f40 100644 --- a/engine/crates/layerfs-persistence/src/backend/sqlite/session/checkpoint.rs +++ b/engine/crates/layerfs-persistence/src/backend/sqlite/session/checkpoint.rs @@ -60,7 +60,7 @@ impl Session { if !state.connection.is_autocommit() { state.quarantined = true; } - state.finish_writer()?; + state.finish_writer(self.background.as_ref())?; let rows = result?; let busy = rows.first().ok_or(BackendError::Integrity)?.get::(0)?; Ok(busy == 0) diff --git a/engine/crates/layerfs-persistence/src/backend/sqlite/session/connection.rs b/engine/crates/layerfs-persistence/src/backend/sqlite/session/connection.rs index e5dd259e22..d9988e8560 100644 --- a/engine/crates/layerfs-persistence/src/backend/sqlite/session/connection.rs +++ b/engine/crates/layerfs-persistence/src/backend/sqlite/session/connection.rs @@ -40,6 +40,12 @@ pub struct ConnectionProfile { pub fullfsync: i64, /// macOS checkpoint full-sync selection. pub checkpoint_fullfsync: i64, + /// The same setting read back from the checkpoint thread's connection, + /// which runs the routine PASSIVE passes of a Normal session: 0, plain + /// `fsync`; the idle and last-close checkpoints run on this session's + /// connection (`checkpoint_fullfsync` above). `None` when the session has + /// no checkpoint thread (read-only and diagnostic sessions). + pub checkpoint_thread_checkpoint_fullfsync: Option, /// Database page bytes. pub page_size: i64, /// Stored page-reclamation mode: 0 for retained Stores, 2 for new acquisition Stores. @@ -290,7 +296,7 @@ impl Session { .iter() .map(|r| r.get::(0)) .collect::, _>>()?; - let profile = ConnectionProfile { + let mut profile = ConnectionProfile { persistence: selected, pack_layout: layout, acquisition, @@ -304,6 +310,7 @@ impl Session { foreign_keys: integer("foreign_keys")?, fullfsync: integer("fullfsync")?, checkpoint_fullfsync: integer("checkpoint_fullfsync")?, + checkpoint_thread_checkpoint_fullfsync: None, page_size: integer("page_size")?, auto_vacuum: integer("auto_vacuum")?, wal_autocheckpoint: integer("wal_autocheckpoint")?, @@ -332,9 +339,16 @@ impl Session { writer.release().map_err(|_| BackendError::Unknown)?; } super::thread_work::add(&work.borrow()); - let background = (writable && selected.background_checkpoint()) + let background = match (writable && selected.background_checkpoint()) .then(|| super::background::Checkpointer::start(path, selected.synchronous())) - .transpose()?; + .transpose()? + { + Some((background, checkpoint_fullfsync)) => { + profile.checkpoint_thread_checkpoint_fullfsync = Some(checkpoint_fullfsync); + Some(background) + } + None => None, + }; // §10: the record every later transaction is fenced against. let identity = FileIdentity::capture(path).map_err(|_| BackendError::Integrity)?; Ok(Self { diff --git a/engine/crates/layerfs-persistence/src/backend/sqlite/session/lifecycle.rs b/engine/crates/layerfs-persistence/src/backend/sqlite/session/lifecycle.rs index 20a22f5e84..b94b558a4e 100644 --- a/engine/crates/layerfs-persistence/src/backend/sqlite/session/lifecycle.rs +++ b/engine/crates/layerfs-persistence/src/backend/sqlite/session/lifecycle.rs @@ -34,6 +34,42 @@ impl Deref for ConnectionSlot { } } +impl State { + /// Ends SQLite's custody of a quarantined connection while the calling + /// thread holds the Store's writer lane (finding #2). `sqlite3_close` + /// rolls back any transaction the uncertain attempt left open and frees + /// SQLite's file locks, so the lane can be released to other processes; + /// nothing is replayed and the Session stays quarantined, refusing every + /// later call before it touches the connection. The checkpoint thread's + /// connection may now be SQLite's last, and it closes without the lane, + /// so it is told to close without checkpointing or removing `-wal`/`-shm`. + /// `true`: SQLite holds no transaction for this State. `false`: the close + /// was refused with a transaction still open, and the caller keeps the + /// lane. (rusqlite flushes its statement cache first and every statement + /// or BLOB handle borrows the connection, so an owned connection has + /// nothing left for SQLite to refuse the close on.) + pub(crate) fn close_quarantined( + &mut self, + background: Option<&super::background::Checkpointer>, + ) -> bool { + debug_assert!(self.quarantined); + let Some(connection) = self.connection.take() else { + return true; + }; + if let Some(background) = background { + background.close_quietly(); + } + match connection.close() { + Ok(()) => true, + Err((connection, _)) => { + let idle = connection.is_autocommit(); + self.connection.restore(connection); + idle + } + } + } +} + impl Drop for State { fn drop(&mut self) { if self.connection.is_closed() { diff --git a/engine/crates/layerfs-persistence/src/backend/sqlite/session/transaction.rs b/engine/crates/layerfs-persistence/src/backend/sqlite/session/transaction.rs index 640fb566aa..bd3f61327a 100644 --- a/engine/crates/layerfs-persistence/src/backend/sqlite/session/transaction.rs +++ b/engine/crates/layerfs-persistence/src/backend/sqlite/session/transaction.rs @@ -274,22 +274,52 @@ impl Session { } let start = Instant::now(); let turn = self.admission.enter(self.wait_kind()).map_err(E::from)?; + let background = self.background.as_ref(); + // The cross-process writer lock is waited for before the state lock + // (finding #20): a wait on another process's lane must not block + // `diagnostics()` or anything else that takes only the state lock. + // The FIFO turn already keeps this Session's other callers out, so no + // other thread can take this Session's writer meanwhile. A held + // publication lane already owns the writer for its nested work. + let writer = if writable && !turn.nested { + if self + .state + .lock() + .map_err(|_| E::from(BackendError::Unknown))? + .quarantined + { + return Err(BackendError::Unknown.into()); + } + Some( + crate::backend::sqlite::lane::writer_admission::Writer::acquire(&self.path) + .map_err(E::from)?, + ) + } else { + None + }; + // A poisoned lock drops `writer` here, which releases it: nothing has + // been attempted under it. let mut s = self .state .lock() .map_err(|_| E::from(BackendError::Unknown))?; super::thread_work::attributed(&mut s, |s| { + // State owns the writer before BEGIN, including across a poisoned + // unwind, and every exit below hands it to `finish_writer`. A + // call that took none leaves a writer retained after an earlier + // quarantine where it is. + if let Some(writer) = writer { + s.writer_hold = Some(writer); + } if s.quarantined { + s.finish_writer(background).map_err(E::from)?; return Err(BackendError::Unknown.into()); } - self.check_identity().map_err(E::from)?; - // A held publication lane already owns the writer for its nested work. - if writable && !turn.nested { - // State owns this before BEGIN, including across a poisoned unwind. - s.writer_hold = Some( - crate::backend::sqlite::lane::writer_admission::Writer::acquire(&self.path) - .map_err(E::from)?, - ); + // Checked with the lane held, so a Store replaced while this call + // waited for it is refused before BEGIN. + if let Err(error) = self.check_identity() { + s.finish_writer(background).map_err(E::from)?; + return Err(error.into()); } let tx = Transaction { connection: &s.connection, @@ -301,7 +331,7 @@ impl Session { if e == BackendError::Unknown { s.quarantined = true; } - s.finish_writer().map_err(E::from)?; + s.finish_writer(background).map_err(E::from)?; s.work.borrow_mut().transaction_ns += start.elapsed().as_nanos() as u64; return Err(e.into()); } @@ -314,7 +344,7 @@ impl Session { tx.uncertain.get() || result.as_ref().err().is_some_and(OutcomeError::uncertain); if uncertain { s.quarantined = true; - s.finish_writer().map_err(E::from)?; + s.finish_writer(background).map_err(E::from)?; s.work.borrow_mut().transaction_ns += start.elapsed().as_nanos() as u64; return Err(BackendError::Unknown.into()); } @@ -384,7 +414,7 @@ impl Session { } } }; - s.finish_writer().map_err(E::from)?; + s.finish_writer(background).map_err(E::from)?; s.work.borrow_mut().transaction_ns += start.elapsed().as_nanos() as u64; // Only a COMMIT can lengthen the log; a rolled-back body must not // wake the checkpoint thread as if it had written. diff --git a/engine/crates/layerfs-persistence/tests/background_checkpoint.rs b/engine/crates/layerfs-persistence/tests/background_checkpoint.rs index 803f03b9c4..6362051735 100644 --- a/engine/crates/layerfs-persistence/tests/background_checkpoint.rs +++ b/engine/crates/layerfs-persistence/tests/background_checkpoint.rs @@ -2,12 +2,14 @@ //! 2026-11-07; Normal since 2026-11-17): COMMIT does not checkpoint //! (`wal_autocheckpoint=0`); a log longer than 4 MiB is copied into the Store //! file while the session stays open, with no idle checkpoint, seal or close. +//! Routine passes sync with plain fsync; the idle checkpoint and the last +//! close run on the session's connection with `checkpoint_fullfsync=1`. #![cfg(any(target_os = "macos", target_os = "linux"))] mod support; use layerfs_content::{construct_bytes, read_range}; use layerfs_history::HistoryCatalogConfig; -use layerfs_persistence::{PersistenceConfig, SqliteHandles, SqlitePersistenceProfile}; +use layerfs_persistence::{PersistenceConfig, SqliteHandles, SqlitePersistenceProfile, StoreFile}; use layerfs_storage::{Storage, StoragePolicy}; use layerfs_telemetry::timer::Timing; use std::path::Path; @@ -63,6 +65,15 @@ fn copied(profile: SqlitePersistenceProfile, synchronous: i64) { assert_eq!(handles.profile().synchronous, synchronous); assert_eq!(handles.profile().fullfsync, 0); assert_eq!(handles.profile().wal_autocheckpoint, 0); + // Routine passes run on the checkpoint thread's connection with plain + // fsync; the idle TRUNCATE and the last close run on the session's own + // connection with F_FULLFSYNC on macOS (finding #11, narrowed by the + // owner 2026-11-23). Neither connection changes its setting after open. + assert_eq!(handles.profile().checkpoint_fullfsync, 1); + assert_eq!( + handles.profile().checkpoint_thread_checkpoint_fullfsync, + Some(0) + ); let storage = Storage::new(handles.storage.clone()).unwrap(); let bytes = random(BYTES); let save = storage.begin_save().unwrap(); @@ -103,10 +114,16 @@ fn copied(profile: SqlitePersistenceProfile, synchronous: i64) { .0 .unwrap(); assert!(read == bytes); + // The routine passes above copied the frames but never shrink the log: + // PASSIVE neither truncates nor deletes it. The idle checkpoint does, and + // only the session's own connection (checkpoint_fullfsync=1) runs it. + let mut wal = path.as_os_str().to_os_string(); + wal.push("-wal"); + assert!(size(Path::new(&wal)) > 0, "a routine pass leaves the log"); + assert!(StoreFile::checkpoint(&*handles.storage).unwrap()); + assert_eq!(size(Path::new(&wal)), 0, "the idle checkpoint truncates it"); drop(storage); drop(handles); // The last close leaves no log behind. - let mut wal = path.as_os_str().to_os_string(); - wal.push("-wal"); assert_eq!(size(Path::new(&wal)), 0); } diff --git a/engine/crates/layerfs-persistence/tests/diagnostics_during_lane.rs b/engine/crates/layerfs-persistence/tests/diagnostics_during_lane.rs index 3ad3ba6558..247d25377b 100644 --- a/engine/crates/layerfs-persistence/tests/diagnostics_during_lane.rs +++ b/engine/crates/layerfs-persistence/tests/diagnostics_during_lane.rs @@ -50,3 +50,61 @@ fn counters_are_read_while_the_lane_is_held() { }); assert!(took < LIMIT, "counters waited {took:?} for the held lane"); } + +/// A writer that waits for another Session's lane (on Linux and macOS, the +/// Store directory's `flock`, which separate Sessions and processes share) +/// waits outside its Session's state lock, so that Session's counters stay +/// readable meanwhile (finding #20). Before the fix the waiter held the state +/// lock across the kernel wait and `diagnostics()` queued behind it. +#[cfg(any(target_os = "linux", target_os = "macos"))] +#[test] +fn counters_are_read_while_the_session_waits_for_another_sessions_lane() { + use layerfs_storage::port::{PackPersistence, Reserve}; + let temp = Temp::new("diagnostics-during-foreign-lane"); + let path = temp.join("store"); + let config = + PersistenceConfig::sqlite(&path).with_sqlite_profile(SqlitePersistenceProfile::Normal); + let authority = HistoryCatalogConfig { + binding_key: b"diagnostics-foreign".to_vec(), + cursor_key: [9; 32], + incarnation: 3, + }; + let holder = + SqliteHandles::create(config.clone(), StoragePolicy::frozen_default(), &authority).unwrap(); + let waiter = + SqliteHandles::open_writable(config, &authority.binding_key, authority.cursor_key).unwrap(); + let (took, reserved) = std::thread::scope(|scope| { + let (held, holding) = mpsc::channel(); + let history = &holder.history; + let lane = scope.spawn(move || { + let lane = history.publish_lane().expect("publication lane"); + held.send(()).ok(); + std::thread::sleep(HELD); + drop(lane); + }); + holding + .recv_timeout(Duration::from_secs(10)) + .expect("the lane is held"); + let storage = &waiter.storage; + let writer = scope.spawn(move || { + storage.reserve(Reserve { + packs: 1, + ordinals: 0, + }) + }); + // Setup, not a threshold: lets the writer reach the kernel wait. + std::thread::sleep(Duration::from_millis(500)); + let started = Instant::now(); + let counters = waiter.diagnostics(); + let took = started.elapsed(); + lane.join().expect("lane holder"); + let reserved = writer.join().expect("waiting writer"); + counters.expect("waiting Session counters"); + (took, reserved) + }); + reserved.expect("the waiting writer reserves once the lane is released"); + assert!( + took < LIMIT, + "counters waited {took:?} for another Session's lane" + ); +} diff --git a/engine/crates/layerfs-persistence/tests/postgresql_commit_round_trips.rs b/engine/crates/layerfs-persistence/tests/postgresql_commit_round_trips.rs index 9515ce1e28..646a22c8dc 100644 --- a/engine/crates/layerfs-persistence/tests/postgresql_commit_round_trips.rs +++ b/engine/crates/layerfs-persistence/tests/postgresql_commit_round_trips.rs @@ -364,10 +364,13 @@ fn commit_store_calls_are_counted_on_both_engines() { // The lane: its BEGIN, the head read, commit_branch's BEGIN, the Branch // probe, the post-fence re-read, Commit insert, parent line, lineage // insert, the position read, advance and COMMIT, the T6.5 epoch READ and - // its FOR SHARE re-check, and the lane's ROLLBACK. The second Branch read - // is the spec §5 fence window: the probe learns the project, the fence - // opens, and the re-read sees a removal that committed in between. - assert_eq!(pg("lane + head + commit_branch").round_trips, 14); + // its FOR SHARE re-check, the lane check on the lane connection before + // commit_branch's COMMIT (finding #10), and the lane's ROLLBACK. The + // second Branch read is the spec §5 fence window: the probe learns the + // project, the fence opens, and the re-read sees a removal that committed + // in between. The lane barrier rides in the lane's BEGIN and the nested + // write's BEGIN, so it adds no round trip. + assert_eq!(pg("lane + head + commit_branch").round_trips, 15); // #70: descriptors and bodies in one statement, found or missing. assert_eq!(pg("read_packs 2").round_trips, 1); assert_eq!(pg("read_packs missing").round_trips, 1); diff --git a/engine/crates/layerfs-persistence/tests/postgresql_lane_liveness.rs b/engine/crates/layerfs-persistence/tests/postgresql_lane_liveness.rs new file mode 100644 index 0000000000..3f737f8025 --- /dev/null +++ b/engine/crates/layerfs-persistence/tests/postgresql_lane_liveness.rs @@ -0,0 +1,184 @@ +//! PostgreSQL lane liveness after an uncertain outcome or a lost lane +//! connection. +//! +//! * Finding #3: a session quarantined by an uncertain write closes its +//! connection. Before the fix its backend stayed connected, idle in its +//! aborted transaction, until the process exited: a transaction the server +//! aborted with an error has already released its row locks, but the +//! backend keeps its session advisory keys (mount and compaction presence), +//! and an uncertain outcome that leaves the transaction live keeps every +//! row lock, `store_lane` included. +//! * Finding #10: a write nested in a held lane commits on the session +//! connection while the row lock lives on the lane connection. When the lane +//! connection dies, the nested write now fails definitely and writes +//! nothing; before the fix it committed without the lock. +//! +//! The only injected conditions are a test-only trigger that raises an +//! unlisted SQLSTATE (classed as an unknown outcome) and an administrator's +//! `pg_terminate_backend` of the lane connection. +//! +//! Needs `LAYERFS_TEST_POSTGRES_URL`; NOT_RUN without it. +mod support; + +use layerfs_history::HistoryCatalog; +use layerfs_persistence::PostgresHandles; +use layerfs_storage::{ + port::{PackPersistence, PersistenceError, Reserve}, + StoragePolicy, +}; +use std::time::{Duration, Instant}; +use support::pg::{catalog, url, Schema}; + +const BINDING: &[u8] = b"postgresql-lane-liveness"; +const CURSOR: [u8; 32] = [91; 32]; +/// The lane wait of the second session: a row still held after the first +/// session's failure shows up as `Busy` within it. +const LOCK_TIMEOUT_MS: u32 = 3_000; + +fn reserve() -> Reserve { + Reserve { + packs: 1, + ordinals: 0, + } +} + +fn handles(schema: &Schema) -> (PostgresHandles, PostgresHandles) { + let mut selection = schema.selection(); + selection.lock_timeout_ms = LOCK_TIMEOUT_MS; + let first = PostgresHandles::create( + &selection, + StoragePolicy::frozen_default(), + &catalog(BINDING, CURSOR, 3), + ) + .expect("PostgreSQL Store creation"); + let second = PostgresHandles::open_writable(&selection, BINDING, CURSOR) + .expect("second PostgreSQL session"); + (first, second) +} + +fn next_pack(schema: &Schema) -> i64 { + schema + .admin() + .query_one("SELECT next_pack_id FROM store_policy WHERE id=1", &[]) + .unwrap() + .get(0) +} + +/// Backends idle in an aborted transaction whose last statement was the +/// Store's allocation `UPDATE`: the quarantined session's, before the fix. +fn aborted_allocations(admin: &mut postgres::Client) -> i64 { + admin + .query_one( + "SELECT count(*) FROM pg_stat_activity WHERE datname = current_database() \ + AND pid <> pg_backend_pid() AND state = 'idle in transaction (aborted)' \ + AND query LIKE 'UPDATE store_policy SET next_pack_id=next_pack_id+%'", + &[], + ) + .unwrap() + .get(0) +} + +#[test] +fn a_quarantined_session_closes_its_connection_and_frees_the_lane_row() { + let Some(url) = url() else { return }; + let schema = Schema::new(url, "quarantine_lane"); + let (first, second) = handles(&schema); + first.storage.reserve(reserve()).unwrap(); + let mut admin = schema.admin(); + admin + .batch_execute( + "CREATE FUNCTION quarantine_probe() RETURNS trigger LANGUAGE plpgsql AS \ + $$ BEGIN RAISE EXCEPTION 'probe' USING ERRCODE = 'XX000'; END $$; \ + CREATE TRIGGER quarantine_probe BEFORE UPDATE ON store_policy \ + FOR EACH ROW EXECUTE FUNCTION quarantine_probe()", + ) + .unwrap(); + let before = next_pack(&schema); + // The write takes the lane row in its BEGIN, then meets the trigger's + // internal error: an unknown outcome, so the session is quarantined. + assert!(matches!( + first.storage.reserve(reserve()), + Err(PersistenceError::Uncertain) + )); + // The quarantined session's backend is gone; the server ends it as soon + // as it reads the closed connection (bounded wait). + let until = Instant::now() + Duration::from_secs(10); + while aborted_allocations(&mut admin) != 0 { + assert!( + Instant::now() < until, + "the quarantined session's backend is still connected" + ); + std::thread::sleep(Duration::from_millis(20)); + } + // Removing the trigger needs the table lock the failed UPDATE took; no + // transaction of the quarantined session holds it. + admin + .batch_execute( + "SET lock_timeout TO 3000; DROP TRIGGER quarantine_probe ON store_policy; \ + DROP FUNCTION quarantine_probe()", + ) + .expect("the quarantined session left no transaction holding store_policy"); + let started = Instant::now(); + let reserved = second + .storage + .reserve(reserve()) + .expect("the second session takes the lane row"); + assert!(started.elapsed() < Duration::from_millis(LOCK_TIMEOUT_MS as u64)); + assert_eq!(reserved.first_pack_id, before); + // The first session stays quarantined. + assert!(matches!( + first.storage.reserve(reserve()), + Err(PersistenceError::Uncertain) + )); +} + +#[test] +fn a_nested_write_after_the_lane_connection_died_fails_and_writes_nothing() { + let Some(url) = url() else { return }; + let schema = Schema::new(url, "lost_lane"); + let (first, second) = handles(&schema); + first.storage.reserve(reserve()).unwrap(); + let before = next_pack(&schema); + let lane = first.history.publish_lane().expect("publication lane"); + // The lane connection is the backend of this schema's Store sitting idle + // in a transaction that holds a row lock on store_lane. + let mut admin = schema.admin(); + let terminated: i64 = admin + .query_one( + "SELECT count(*) FILTER (WHERE pg_terminate_backend(a.pid)) FROM pg_stat_activity a \ + WHERE a.state = 'idle in transaction' AND a.pid <> pg_backend_pid() \ + AND EXISTS (SELECT 1 FROM pg_locks l \ + WHERE l.pid = a.pid AND l.locktype = 'relation' \ + AND l.relation = 'store_lane'::regclass)", + &[], + ) + .unwrap() + .get(0); + assert_eq!(terminated, 1, "exactly the lane connection is terminated"); + // Wait, bounded, for the server to end it. + let until = Instant::now() + Duration::from_secs(10); + while admin + .query_one( + "SELECT count(*) FROM pg_locks l WHERE l.locktype = 'relation' \ + AND l.relation = 'store_lane'::regclass AND l.pid <> pg_backend_pid()", + &[], + ) + .unwrap() + .get::<_, i64>(0) + != 0 + { + assert!(Instant::now() < until, "the lane backend ends"); + std::thread::sleep(Duration::from_millis(20)); + } + // The nested write runs in the still-held turn and must not commit. + let nested = first.storage.reserve(reserve()); + assert!( + matches!(&nested, Err(PersistenceError::Refused { status }) if status == "Closed"), + "{nested:?}" + ); + assert_eq!(next_pack(&schema), before, "the nested write wrote nothing"); + drop(lane); + // Another session takes the lane and writes at once. + let reserved = second.storage.reserve(reserve()).unwrap(); + assert_eq!(reserved.first_pack_id, before); +} diff --git a/engine/crates/layerfs-persistence/tests/postgresql_sqlstate.rs b/engine/crates/layerfs-persistence/tests/postgresql_sqlstate.rs index f93e55761b..34a8c3be9e 100644 --- a/engine/crates/layerfs-persistence/tests/postgresql_sqlstate.rs +++ b/engine/crates/layerfs-persistence/tests/postgresql_sqlstate.rs @@ -31,3 +31,18 @@ fn the_neighbouring_classes_keep_their_verdicts() { assert_eq!(sqlstate("42501"), BackendError::Integrity); assert_eq!(sqlstate("08006"), BackendError::Unknown); } + +/// A statement the server refused with a reply is a definite failure, not an +/// unknown outcome: `P0001` comes from the `pack_immutable` trigger's RAISE +/// EXCEPTION, class P0 from any PL/pgSQL error and class 21 from a +/// cardinality violation (finding #3). Server I/O and internal errors stay +/// unknown. +#[test] +fn refused_statements_are_definite_and_server_failures_stay_unknown() { + for code in ["P0001", "P0002", "P0003", "P0004", "21000"] { + assert_eq!(sqlstate(code), BackendError::Integrity, "SQLSTATE {code}"); + } + for code in ["58030", "XX000", "XX001"] { + assert_eq!(sqlstate(code), BackendError::Unknown, "SQLSTATE {code}"); + } +} diff --git a/engine/crates/layerfs-persistence/tests/sqlite_publication.rs b/engine/crates/layerfs-persistence/tests/sqlite_publication.rs index 317b9dd2bb..cda8c0d8e2 100644 --- a/engine/crates/layerfs-persistence/tests/sqlite_publication.rs +++ b/engine/crates/layerfs-persistence/tests/sqlite_publication.rs @@ -528,6 +528,10 @@ fn explicit_profiles_keep_atomic_publication_and_matching_reopen_contracts() { assert_eq!(profile.synchronous, if selected == Durable { 2 } else { 1 }); assert_eq!(profile.fullfsync, i64::from(selected == Durable)); assert_eq!((profile.checkpoint_fullfsync, profile.temp_store), (1, 2)); + // Routine checkpoint-thread passes sync with plain fsync; the idle + // and last-close checkpoints run on the session's connection above + // (finding #11, narrowed by the owner 2026-11-23). + assert_eq!(profile.checkpoint_thread_checkpoint_fullfsync, Some(0)); assert_eq!( (profile.page_size, profile.cache_size, profile.mmap_size), (4096, -2048, 0) diff --git a/engine/crates/layerfs-persistence/tests/sqlite_quarantine_release.rs b/engine/crates/layerfs-persistence/tests/sqlite_quarantine_release.rs new file mode 100644 index 0000000000..d277c8388f --- /dev/null +++ b/engine/crates/layerfs-persistence/tests/sqlite_quarantine_release.rs @@ -0,0 +1,169 @@ +//! A Session quarantined by an uncertain write outcome lets the Store's +//! writer lane go (finding #2). Before the fix the quarantined Session kept +//! the directory `flock`, and with it its open SQLite write transaction, until +//! the Session dropped, so every other Session and process waited forever. +//! +//! The uncertain outcome comes from ordinary public behaviour: an +//! uncoordinated raw SQLite connection adds a trigger that calls an unknown +//! function, so the Store's own `UPDATE store_policy` fails with a generic +//! `SQLITE_ERROR` inside its write transaction, which the Store classes as an +//! unknown outcome and which leaves SQLite's transaction open. +#![cfg(any(target_os = "linux", target_os = "macos"))] +mod support; +use layerfs_history::{HistoryCatalog, HistoryCatalogConfig}; +use layerfs_persistence::{PersistenceConfig, SqliteHandles, SqlitePersistenceProfile}; +use layerfs_storage::{port::*, StoragePolicy}; +use std::{ + path::Path, + process::{Command, Stdio}, + sync::mpsc, + time::{Duration, Instant}, +}; + +/// How long the second Session may wait for the lane once the first one is +/// quarantined; the fixed path takes it at once. +const BOUND: Duration = Duration::from_secs(10); + +fn authority() -> HistoryCatalogConfig { + HistoryCatalogConfig { + binding_key: b"sqlite-quarantine-release".to_vec(), + cursor_key: [83; 32], + incarnation: 1, + } +} +fn config(path: &Path) -> PersistenceConfig { + PersistenceConfig::sqlite(path).with_sqlite_profile(SqlitePersistenceProfile::Normal) +} +fn reserve() -> Reserve { + Reserve { + packs: 1, + ordinals: 0, + } +} + +/// One bounded raw SQLite statement from another process, with a 3 s busy +/// wait of its own. `Ok(())` when it ran, `Err(message)` when SQLite refused +/// it (for example `database is locked` while a write transaction is open). +fn raw(path: &Path, sql: &str) -> Result<(), String> { + let script = "import sqlite3,sys\ntry:\n c=sqlite3.connect(sys.argv[1],timeout=3,isolation_level=None)\n c.execute(sys.argv[2])\n c.close()\n print('ok')\nexcept Exception as e:\n print('refused',e)\n"; + let mut child = Command::new("python3") + .args(["-I", "-c", script]) + .arg(path) + .arg(sql) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + let until = Instant::now() + Duration::from_secs(10); + while child.try_wait().unwrap().is_none() { + if Instant::now() >= until { + let _ = child.kill(); + let _ = child.wait(); + panic!("bounded raw SQLite statement"); + } + std::thread::sleep(Duration::from_millis(10)); + } + let output = child.wait_with_output().unwrap(); + assert!(output.status.success()); + let text = String::from_utf8(output.stdout).unwrap(); + if text == "ok\n" { + Ok(()) + } else { + Err(text) + } +} + +const ADD_TRIGGER: &str = "CREATE TRIGGER quarantine_probe BEFORE UPDATE ON store_policy \ + BEGIN SELECT layerfs_no_such_function(); END"; +const DROP_TRIGGER: &str = "DROP TRIGGER quarantine_probe"; + +/// The second Session's reservation, run on its own thread and waited for +/// within [`BOUND`]. A reservation still waiting at the bound is the bug. +fn reserve_within_bound(second: &SqliteHandles) -> Reserved { + // A detached thread, so a reservation stuck in the kernel wait cannot + // hold the test past its bound; process exit ends it. + let storage = second.storage.clone(); + let (done, finished) = mpsc::channel(); + std::thread::spawn(move || { + let _ = done.send(storage.reserve(reserve())); + }); + finished + .recv_timeout(BOUND) + .unwrap_or_else(|_| { + panic!("the second Session still waits for the writer lane after {BOUND:?}") + }) + .expect("the second Session reserves") +} + +struct Stores { + _temp: support::Temp, + path: std::path::PathBuf, + first: SqliteHandles, + second: SqliteHandles, + /// The pack id the next successful reservation gets. + next_pack: i64, +} + +fn stores(name: &str) -> Stores { + let temp = support::Temp::new(name); + let path = temp.join("store.sqlite"); + let first = SqliteHandles::create(config(&path), StoragePolicy::frozen_default(), &authority()) + .unwrap(); + let second = SqliteHandles::open_writable( + config(&path), + &authority().binding_key, + authority().cursor_key, + ) + .unwrap(); + first.storage.reserve(reserve()).unwrap(); + let last = second.storage.reserve(reserve()).unwrap().first_pack_id; + raw(&path, ADD_TRIGGER).expect("the probe trigger is added while no writer is active"); + Stores { + _temp: temp, + path, + first, + second, + next_pack: last + 1, + } +} + +/// After the first Session's uncertain write: SQLite's transaction is gone +/// (a raw writer can drop the trigger), the second Session takes the lane +/// within the bound and gets the next pack id, and the first Session stays +/// quarantined. +fn check_released(stores: Stores) { + raw(&stores.path, DROP_TRIGGER) + .expect("the quarantined Session left no SQLite write transaction open"); + let reserved = reserve_within_bound(&stores.second); + assert_eq!(reserved.first_pack_id, stores.next_pack); + assert!(matches!( + stores.first.storage.reserve(reserve()), + Err(PersistenceError::Uncertain) + )); +} + +#[test] +fn a_quarantined_write_releases_the_lane_to_another_session() { + let stores = stores("sqlite-quarantine-release-run"); + assert!(matches!( + stores.first.storage.reserve(reserve()), + Err(PersistenceError::Uncertain) + )); + check_released(stores); +} + +#[test] +fn a_quarantined_write_inside_a_held_lane_closes_before_the_lane_is_released() { + let stores = stores("sqlite-quarantine-release-lane"); + let lane = stores + .first + .history + .publish_lane() + .expect("publication lane"); + assert!(matches!( + stores.first.storage.reserve(reserve()), + Err(PersistenceError::Uncertain) + )); + drop(lane); + check_released(stores); +} diff --git a/tools/ci_tests.py b/tools/ci_tests.py index 45e0c0b511..b0187f37dd 100755 --- a/tools/ci_tests.py +++ b/tools/ci_tests.py @@ -60,6 +60,8 @@ ("layerfs-control", "observed_application"): 6.30, # Linux functional run at the relocated tree, 2026-10-27. ("layerfs-persistence", "writer_admission"): 9.74, + # Two cases each hold a lane 3 s (finding #20), macOS host, 2026-11-23. + ("layerfs-persistence", "diagnostics_during_lane"): 6.06, ("layerfs-store-service", "scale_lineage_cap"): 24.3, ("layerfs-store-service", "sdk_merge_scale"): 23.8, ("layerfs-daemon", "complete_installed_roots"): 9.0,