Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,15 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
its partial match started (`gate_started_ms` in the run input); a refused
run retries under the same id. Correlated composites are unchanged.

- **Postgres: concurrent first opens of a new memory could deadlock** (`40P01`
on an open, or on a write made right after one). The bootstrap serialized
openers with an advisory lock but never re-checked the schema stamp once it
held it, so an opener that queued behind the winner re-ran the whole DDL and
seed; its `counters` upserts raced the winner's first writes, which lock the
same rows in a different order. The stamp is now re-read under the lock (a
current schema is left alone), and a migration locks `counters` in key
order first. No schema-version change.

## [1.14.5] — 2026-11-23

### Changed
Expand Down
39 changes: 39 additions & 0 deletions crates/areev-conformance/tests/pg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,45 @@ fn concurrent_first_open_bootstraps_once() {
drop(b.open_named("boot")); // register the schema for cleanup
}

/// Several openers racing a BRAND-NEW memory, each writing the moment it is
/// open, over many fresh schemas. The bootstrap is serialized by an advisory
/// lock, but an opener that queued behind the winner used to re-run the whole
/// DDL + seed anyway; its `counters` upserts (seq, op, hlc) then raced the
/// winner's first writes, which lock the same rows in key order (hlc, op,
/// seq) — a lock cycle Postgres broke with `40P01`. One opener pair per
/// schema hit it roughly once in a few hundred opens (a flaky
/// `concurrent_first_open_bootstraps_once` in CI); this shape makes it likely.
#[test]
fn first_openers_that_write_at_once_never_deadlock() {
let Some(b) = backend() else { return };
let url = pg_url().unwrap();
let mut failures = Vec::new();
for round in 0..40 {
let schema = b.schema_for(&format!("boot_w{round}"));
let openers: Vec<_> = (0..6)
.map(|w| {
let (url, schema) = (url.clone(), schema.clone());
std::thread::spawn(move || -> Result<(), String> {
let mut m = areev_store::Areev::open_postgres(&url, &schema)
.map_err(|e| format!("open: {e}"))?;
for i in 0..5 {
let g = areev_conformance::fact("ns", &format!("s{w}"), "seen", &format!("{i}"));
m.add(&g).map_err(|e| format!("write: {e}"))?;
}
Ok(())
})
})
.collect();
for t in openers {
if let Err(e) = t.join().unwrap() {
failures.push(format!("round {round}: {e}"));
}
}
drop(b.open_named(&format!("boot_w{round}"))); // register for cleanup
}
assert!(failures.is_empty(), "first-open + write must not fail: {failures:#?}");
}

/// Two instances racing to supersede the SAME head: exactly one winner and
/// one clean SupersessionConflict — the single-writer contract, kept under
/// concurrency by the in-transaction FOR UPDATE recheck.
Expand Down
13 changes: 13 additions & 0 deletions crates/areev-store/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -872,6 +872,19 @@ is what lets an embedded reader hold the SELECT-only role too.
needs, and that failure is silent — every recall returns empty, nothing
errors (the #160 shape). A unit test digests both arrays and fails if either
moves without a version bump; do not weaken it.
**The stamp is read TWICE** (double-checked locking): once before any
lock (the fast path), and again inside the bootstrap transaction right
after `pg_advisory_xact_lock`. An opener that queued behind the winner
arrives with a schema that is already current and must do nothing —
re-running the seed made its `counters` upserts (seq, op, hlc) race the
winner's first writes, which lock the same rows in KEY order (hlc, op, seq),
and Postgres broke the cycle with `40P01` on an open OR a write. A real
migration (a stamp bump) also takes `counters` `FOR UPDATE` in key order
before the seed, so it joins `reserve_write`'s one global order. Neither
moves `PG_SEED`, so neither bumps `PG_SCHEMA_VERSION`. Conformance:
`first_openers_that_write_at_once_never_deadlock` (Pg-only: 40 fresh
schemas × 6 openers, each writing at once; fails on every run without the
re-check).
Two more consequences: the bootstrap now runs inside one transaction under
`pg_advisory_xact_lock` (atomic, and the lock cannot leak on a failure
path), and `Db::seeds_state_at_open()` returns `false` here so `finish_open`
Expand Down
44 changes: 39 additions & 5 deletions crates/areev-store/src/pg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1183,7 +1183,7 @@ impl PgDb {
return Err(Self::not_provisioned(client, pool, layout, stamp));
}
match Self::bootstrap_once(pool, client, layout, bootstrap, stamp) {
Ok(()) => Ok(false),
Ok(already_current) => Ok(already_current),
// A concurrent opener won the race and created the schema first.
// The advisory lock makes this rare, not impossible: the pool
// shares one runtime, so two openers' `CREATE SCHEMA` can
Expand All @@ -1205,7 +1205,7 @@ impl PgDb {
if current {
Ok(true)
} else {
Self::bootstrap_once(pool, client, layout, bootstrap, stamp).map(|()| false)
Self::bootstrap_once(pool, client, layout, bootstrap, stamp)
}
}
Err(e) => Err(e),
Expand Down Expand Up @@ -1238,7 +1238,7 @@ impl PgDb {
layout: &PgLayout,
bootstrap: &[&str],
stamp: Option<PgStamp>,
) -> Result<()> {
) -> Result<bool> {
let schema = layout.schema();
pool.block_on(async {
// ONE transaction around the whole bootstrap. Postgres DDL
Expand All @@ -1256,6 +1256,21 @@ impl PgDb {
)
.await
.map_err(pg_err)?;
// Double-checked locking. `open_on` read the stamp BEFORE this
// lock; an opener that queued behind the winner arrives here
// with a schema that is already current. Re-running the DDL and
// seed then does no good — and harm: its `counters` upserts
// race the winner's first writes (`finish_open`), taking rows
// in the seed's order against `reserve_write`'s key order, and
// Postgres picks a loser with 40P01 (seen as a flaky
// `concurrent_first_open_bootstraps_once`).
if let Some(st) = stamp {
if Self::schema_stamp(client, layout, st).await?.as_deref()
== Some(st.version)
{
return Ok::<_, AreevError>(true);
}
}
for s in layout.schemas() {
client
.batch_execute(&format!("CREATE SCHEMA IF NOT EXISTS \"{s}\""))
Expand All @@ -1271,6 +1286,21 @@ impl PgDb {
))
.await
.map_err(pg_err)?;
// A migration (a stamp bump) runs against a live memory whose
// writers lock `counters` in KEY order (`reserve_write`). The
// seed upserts those rows in its own order, so take whatever
// exists in key order first: one global order, no cycle. A
// brand-new schema has no table yet and nobody to race.
let counters = layout.qualified("counters");
if Self::relation_present(client, &counters).await? {
client
.query(
&format!("SELECT name FROM {counters} ORDER BY name FOR UPDATE"),
&[],
)
.await
.map_err(pg_err)?;
}
for sql in bootstrap {
let routed = qualify_tables(sql, layout);
client.batch_execute(&routed).await.map_err(|e| {
Expand All @@ -1295,11 +1325,15 @@ impl PgDb {
.await
.map_err(pg_err)?;
}
Ok::<_, AreevError>(())
Ok::<_, AreevError>(false)
}
.await;
match boot {
Ok(()) => client.batch_execute("COMMIT").await.map_err(pg_err),
Ok(already_current) => client
.batch_execute("COMMIT")
.await
.map_err(pg_err)
.map(|()| already_current),
Err(e) => {
let _ = client.batch_execute("ROLLBACK").await;
Err(e)
Expand Down
Loading