Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
dfb4908
Document configurable PostgreSQL storage design
mmpg-x86 Oct 14, 2026
953c8d2
Initialize pseudoterminals in display tests
mmpg-x86 Oct 15, 2026
ebb23b6
Parse opt-in PostgreSQL storage modes
mmpg-x86 Oct 15, 2026
8cc1137
Add PostgreSQL catalog migration foundation
mmpg-x86 Oct 15, 2026
282da5e
Support PostgreSQL for daemon storage
mmpg-x86 Oct 15, 2026
5ff2a61
Synchronize shared bug catalogs through PostgreSQL
mmpg-x86 Oct 15, 2026
0d7e948
Keep catalog merge bases until local changes are acknowledged
mmpg-x86 Oct 15, 2026
f0ab873
Keep imported discovery links scoped to their producer
mmpg-x86 Oct 15, 2026
1b9ef39
Honor the selected storage backend in database clients
mmpg-x86 Oct 15, 2026
dec5920
Provide OpenSSL dependencies for Linux Nix builds
mmpg-x86 Oct 15, 2026
9d63568
Run PostgreSQL integration coverage in CI
mmpg-x86 Oct 15, 2026
f74127a
Preserve ASCII subsystem scope matching on both backends
mmpg-x86 Oct 15, 2026
1256de8
Redact foreign duplicate history in scoped bug views
mmpg-x86 Oct 15, 2026
0a1ddeb
Bound pending catalog lookups to the requested bug views
mmpg-x86 Oct 15, 2026
67b4b3d
Preserve shared duplicate relationships during concurrent triage
mmpg-x86 Oct 15, 2026
b67bc94
Preserve analysis outcomes across shared catalog outages
mmpg-x86 Oct 15, 2026
44b0051
Recover ordinary PostgreSQL sessions after connection loss
mmpg-x86 Oct 15, 2026
ba8ef01
Keep the libSQL covering index for review statistics
mmpg-x86 Oct 15, 2026
3d64a2d
Exercise PostgreSQL adapter boundaries with deterministic fixtures
mmpg-x86 Oct 15, 2026
4447f1f
Describe PostgreSQL deployment and execution boundaries
mmpg-x86 Oct 15, 2026
56b079b
Keep shared publication scoped to the configured project
mmpg-x86 Oct 15, 2026
f5f686c
Scope PostgreSQL coordination locks to the configured schema
mmpg-x86 Oct 15, 2026
592d15d
Version shared mirror tracking and exclude local bookkeeping
mmpg-x86 Oct 15, 2026
44eb292
Reuse the shared catalog connection and TLS configuration
mmpg-x86 Oct 15, 2026
35b5c79
Discard PostgreSQL sessions after interrupted operations
mmpg-x86 Oct 15, 2026
672dbce
Classify transient catalog failures before refunding attempts
mmpg-x86 Oct 15, 2026
085e67a
Preserve legacy bug identifiers in project catalog namespaces
mmpg-x86 Oct 15, 2026
e875af3
Bound shared catalog synchronization with durable scheduling
mmpg-x86 Oct 15, 2026
490c9dc
Preserve original metadata when importing shared bug history
mmpg-x86 Oct 15, 2026
13fd37c
Match libSQL bug triage behavior on PostgreSQL
mmpg-x86 Oct 15, 2026
66e32d9
Verify the shared catalog readiness contract
mmpg-x86 Oct 15, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Discard PostgreSQL sessions after interrupted operations
Own each connection driver and stop it when an operation is canceled
or fails. Reconnect ordinary callers on their next operation while
keeping dedicated transactions and lock sessions invalid after loss.

Discard unfinished transaction sessions immediately instead of
spawning a rollback that can itself wait forever. Preserve the driver
alongside its client during reconnects and verify cancellation against
a live advisory-lock wait.

Signed-off-by: Maciej Grochowski <maciej.grochowski@protonmail.com>
  • Loading branch information
mmpg-x86 committed Oct 15, 2026
commit 35b5c79d5452c12f5ce25a843efd633e95b9ec5c
96 changes: 79 additions & 17 deletions src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ pub enum Error {
Postgres(#[from] tokio_postgres::Error),
#[error("could not reconnect PostgreSQL session: {0}")]
Reconnect(#[source] anyhow::Error),
#[error("PostgreSQL session was canceled")]
Canceled,
#[error("invalid database value: {0}")]
Value(String),
}
Expand All @@ -48,9 +50,41 @@ pub struct PgConfig {

struct PgConnection {
client: Mutex<tokio_postgres::Client>,
driver: std::sync::Mutex<PgDriver>,
config: PgConfig,
session: PgSession,
active: AtomicBool,
broken: AtomicBool,
}

struct PgDriver(tokio::task::JoinHandle<()>);

impl Drop for PgDriver {
fn drop(&mut self) {
self.0.abort();
}
}

struct PgCall<'a> {
connection: &'a PgConnection,
complete: bool,
}

impl<'a> PgCall<'a> {
fn new(connection: &'a PgConnection) -> Self {
Self {
connection,
complete: false,
}
}
}

impl Drop for PgCall<'_> {
fn drop(&mut self) {
if !self.complete {
self.connection.abort();
}
}
}

#[derive(Clone, Copy, PartialEq, Eq)]
Expand All @@ -61,14 +95,35 @@ enum PgSession {
}

impl PgConnection {
fn driver(&self) -> std::sync::MutexGuard<'_, PgDriver> {
self.driver
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}

fn abort(&self) {
self.broken.store(true, Ordering::Release);
self.active.store(false, Ordering::Release);
self.driver().0.abort();
}

async fn client(&self) -> Result<tokio::sync::MutexGuard<'_, tokio_postgres::Client>> {
let mut client = self.client.lock().await;
if self.session == PgSession::Regular && client.is_closed() {
let broken = self.broken.load(Ordering::Acquire);
if self.session != PgSession::Regular && broken {
return Err(Error::Canceled);
}
if self.session == PgSession::Regular && (broken || client.is_closed()) {
let replacement = Connection::connect_postgres(self.config.clone(), PgSession::Regular)
.await
.map_err(Error::Reconnect)?;
if let Backend::Postgres(replacement) = replacement.0 {
std::mem::swap(&mut *client, &mut *replacement.client.lock().await);
let mut replacement_client = replacement.client.lock().await;
let mut driver = self.driver();
let mut replacement_driver = replacement.driver();
std::mem::swap(&mut *client, &mut *replacement_client);
std::mem::swap(&mut *driver, &mut *replacement_driver);
self.broken.store(false, Ordering::Release);
}
}
Ok(client)
Expand Down Expand Up @@ -111,15 +166,15 @@ impl Connection {
};
let conn = Self::connect_postgres(connection.config.clone(), PgSession::DedupLock).await?;
if let Backend::Postgres(connection) = &conn.0 {
connection
.client
.lock()
.await
let client = connection.client.lock().await;
let mut call = PgCall::new(connection);
client
.query_one(
"SELECT pg_catalog.pg_advisory_lock(pg_catalog.hashtext($1),$2)",
&[&connection.config.schema, &(WRITE_LOCK + 1)],
)
.await?;
call.complete = true;
}
Ok(Some(conn))
}
Expand All @@ -145,11 +200,11 @@ impl Connection {
config.tls.clone(),
))
.await?;
tokio::spawn(async move {
let driver = PgDriver(tokio::spawn(async move {
if let Err(error) = driver.await {
tracing::warn!("PostgreSQL connection ended: {error}");
}
});
}));
let schema = format!("\"{}\"", config.schema);
if !transaction {
let tx = client.transaction().await?;
Expand All @@ -175,9 +230,11 @@ impl Connection {
}
Ok(Self(Backend::Postgres(Arc::new(PgConnection {
client: Mutex::new(client),
driver: std::sync::Mutex::new(driver),
config,
session,
active: AtomicBool::new(transaction),
broken: AtomicBool::new(false),
}))))
}

Expand All @@ -188,6 +245,7 @@ impl Connection {
let params = positional(params)?;
let sql = placeholders(sql)?;
let mut client = conn.client().await?;
let mut call = PgCall::new(conn);
let values = if conn.session == PgSession::Transaction {
pg_query(&*client, &sql, params).await?
} else {
Expand All @@ -197,6 +255,7 @@ impl Connection {
tx.commit().await?;
values
};
call.complete = true;
Ok(Rows::Postgres(values.into()))
}
}
Expand All @@ -209,6 +268,7 @@ impl Connection {
let params = positional(params)?;
let sql = placeholders(sql)?;
let mut client = conn.client().await?;
let mut call = PgCall::new(conn);
let control = matches!(
sql.trim()
.trim_end_matches(';')
Expand All @@ -219,17 +279,20 @@ impl Connection {
if control {
client.batch_execute(&sql).await?;
conn.active.store(false, Ordering::Release);
call.complete = true;
return Ok(0);
}
if conn.session == PgSession::Transaction {
let result = if conn.session == PgSession::Transaction {
pg_execute(&*client, &sql, params).await
} else {
let tx = client.transaction().await?;
pg_write_lock(&tx, &conn.config.schema).await?;
let count = pg_execute(&tx, &sql, params).await?;
tx.commit().await?;
Ok(count)
}
};
call.complete = result.is_ok();
result
}
}
}
Expand All @@ -241,6 +304,7 @@ impl Connection {
}
Backend::Postgres(conn) => {
let mut client = conn.client().await?;
let mut call = PgCall::new(conn);
if conn.session == PgSession::Transaction {
client.batch_execute(sql).await?;
} else {
Expand All @@ -249,6 +313,7 @@ impl Connection {
tx.batch_execute(sql).await?;
tx.commit().await?;
}
call.complete = true;
}
}
Ok(())
Expand Down Expand Up @@ -307,13 +372,10 @@ impl Drop for Transaction {
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(native))).is_err() {
tracing::warn!("Suppressed libSQL rollback panic while closing a transaction");
}
} else if !self.conn.is_autocommit() {
let conn = self.conn.clone();
if let Ok(runtime) = tokio::runtime::Handle::try_current() {
runtime.spawn(async move {
let _ = conn.execute("ROLLBACK", ()).await;
});
}
} else if !self.conn.is_autocommit()
&& let Backend::Postgres(connection) = &self.conn.0
{
connection.abort();
}
}
}
Expand Down
13 changes: 13 additions & 0 deletions tests/integration/postgres_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,19 @@ async fn backend_pid(conn: &sashiko::storage::Connection) -> Result<i32> {

async fn exercise_connection_recovery(db: &Database, settings: &StorageSettings) -> Result<()> {
let control = postgres_control(settings).await?;
let original = backend_pid(&db.conn).await?;
let tx = db.begin_transaction().await?;
assert!(
tokio::time::timeout(
std::time::Duration::from_millis(100),
db.conn.query("SELECT 1", ()),
)
.await
.is_err()
);
tx.rollback().await?;
// Canceling a regular operation must discard its uncertain protocol state.
assert_ne!(backend_pid(&db.conn).await?, original);
let prior = backend_pid(&db.conn).await?;
control
.query_one("SELECT pg_terminate_backend($1,5000)", &[&prior])
Expand Down