From 2ae3f3f281c215dc73504c3cff859416f177457c Mon Sep 17 00:00:00 2001 From: Ashish Bagri Date: Sat, 14 Nov 2026 11:31:23 +0100 Subject: [PATCH 1/2] Lore: review follow-ups from TR-1189/TR-1191 (TR-1313) - prune index_runs: keep the newest 50 runs per source, never a running one - admin overview and pushes use the database's clock for now - timeouts on the lock connection's ping, unlock and close, and a bounded release - a refused push restores the lore-indexed ref and the checkout to the indexed commit Co-Authored-By: Claude Sonnet 5.5 --- docs/usage.md | 6 +-- src/http/admin.rs | 14 +++-- src/repo/lock.rs | 86 +++++++++++++++++++++++------ src/repo/mod.rs | 21 ++++++++ src/repo/progress.rs | 42 +++++++++++++++ tests/admin.rs | 48 +++++++++++++++++ tests/cli_index.rs | 126 +++++++++++++++++++++++++++++++++++++++++++ tests/index_runs.rs | 83 +++++++++++++++++++++++++++- 8 files changed, 404 insertions(+), 22 deletions(-) diff --git a/docs/usage.md b/docs/usage.md index ee8812a..f105bdf 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -45,7 +45,7 @@ curl -X PUT "localhost:8080/v1/repos//bundle?ref=$(git rev-parse HEAD)&full= `GET /v1/repos/{id}/progress` needs a `read` key and answers with the latest index run of that repo, whichever process ran it (while a run is queued behind another, the queued run is the latest, so the one indexing is not shown until the queued one starts): `{"id", "stage", "commit", "full", "files_done", "files_total", "chunks", "chunks_embedded", "embed_ms", "started_at", "updated_at", "finished_at", "error", "stale"}`. `stage` is `queued` (waiting for another run on the same repo), `cloning` (fetching the commit), `indexing`, `done` or `failed`, and `error` says why a run failed. `files_total` is null until the files to index are known. A run that has not ended and has not been updated for 90 seconds is shown with `"stale": true`: its process most likely died. The stage is left as it was, and the run stays that way until the next run starts. A repo that has no run yet answers 404 `no_index_run`; a repo of another tenant answers the usual 404. -Progress is kept in the Postgres table `index_runs`, one row per run (source, tenant, stage, files done and total, chunks, start and finish times, error), so it survives a restart and a process other than the server can report through it. An indexer writes its counts at most once a second, writes a change of stage or the end of a run at once, and refreshes `updated_at` every 5 seconds while it is alive. If a write fails, the failure is logged and the index carries on. The rows go with their source or tenant when it is deleted. +Progress is kept in the Postgres table `index_runs`, one row per run (source, tenant, stage, files done and total, chunks, start and finish times, error), so it survives a restart and a process other than the server can report through it. An indexer writes its counts at most once a second, writes a change of stage or the end of a run at once, and refreshes `updated_at` every 5 seconds while it is alive. If a write fails, the failure is logged and the index carries on. The rows go with their source or tenant when it is deleted. Each source keeps its newest 50 runs: when a run starts, the runs of that source beyond the newest 50 are deleted, except runs that are going (a run that is not ended and not stale), so the table does not grow with every push. Repo indexing publishes atomically. While a push runs, search sees the previous complete index (or no repo chunks on its first push). Changed, new and deleted files and `indexed_commit` @@ -171,7 +171,7 @@ The repo must belong to the tenant: a source of another tenant, a source that do The run shows in `index_runs` like any index run, so `GET /v1/repos/{id}/progress` and the admin page show its stage and counts while it works and `done` or `failed` after. A process that is killed leaves a run that goes stale, as for the server. -One `lore index` per repo at a time: it holds a Postgres advisory lock on the repo for the whole run, on a connection of its own. A second one for the same repo does not wait; it exits at once with code 3 (`another index of source is running`). The lock is released when the process ends, however it ends. Other repos are not affected, and the server's own pushes and syncs of that repo still serialise with it on the row lock the index takes while it writes. A server incremental push or sync that waited on that row lock behind an index that moved the indexed commit is answered with the full-index path (409 `need_full_bundle` for a push, a full index for a sync) instead of applying a stale diff. The lock connection is pinged every 30 seconds so an idle-connection timeout of a NAT or load balancer does not drop it; point `LORE_DATABASE_URL` at Postgres or a session-mode pooler, not a transaction-mode one (PgBouncer `pool_mode=transaction`), which cannot hold a session lock. +One `lore index` per repo at a time: it holds a Postgres advisory lock on the repo for the whole run, on a connection of its own. A second one for the same repo does not wait; it exits at once with code 3 (`another index of source is running`). The lock is released when the process ends, however it ends. Other repos are not affected, and the server's own pushes and syncs of that repo still serialise with it on the row lock the index takes while it writes. A server incremental push or sync that waited on that row lock behind an index that moved the indexed commit is answered with the full-index path (409 `need_full_bundle` for a push, a full index for a sync) instead of applying a stale diff, and the repo's `lore-indexed` ref and checkout are put back at the indexed commit the database holds, so they never run ahead of it after a refused push. The lock connection is pinged every 30 seconds so an idle-connection timeout of a NAT or load balancer does not drop it. A ping, the unlock and the close each wait 10 seconds at most, so a connection that went half-open (open, but never answering) cannot keep `lore index` from exiting; a ping that gets no answer is logged as an error and ends the pinging, since the session lock is then lost with the connection; point `LORE_DATABASE_URL` at Postgres or a session-mode pooler, not a transaction-mode one (PgBouncer `pool_mode=transaction`), which cannot hold a session lock. | Exit code | Meaning | |---|---| @@ -317,7 +317,7 @@ curl -H "Authorization: Bearer $LORE_ADMIN_TOKEN" localhost:8080/v1/admin/overvi curl -H "Authorization: Bearer $LORE_ADMIN_TOKEN" localhost:8080/v1/admin/pushes # running and recent pushes ``` -`GET /v1/admin/overview` answers `{"now", "server", "storage", "tenants"}`. `server` has `version`, `llm`, `embedder`, `modes`, `models` (`fast` and `deep`, each with `model` and `effort`), `memory` (`rss_bytes` and `peak_rss_bytes`, null outside Linux), and the totals `tenants`, `sources`, `documents` and `chunks`. `storage` has `database_bytes`, `repos_bytes`, `tables` (`name`, `rows_estimate`, `data_bytes`, `index_bytes`, `total_bytes`, largest first) and `indexes` (`name`, `table`, `method`, `bytes`). Each tenant has `id`, `name`, `created_at`, `sources` (`id`, `name`, `kind`, `indexed_commit`, `remote_url`, `last_sync_at`, `last_sync_commit`, `last_sync_error`, `documents`, `chunks`, `last_indexed_at`, `disk_bytes`) and `keys` (`id`, `prefix`, `scopes`, `created_at`, `revoked_at`). `last_indexed_at` is the later of a repo's last push and the source's newest document write, and null until something is indexed; `disk_bytes` is null for sources that are not repos. `last_sync_at` is when the last sync ended, `last_sync_commit` the remote's head at the last sync that worked, and `last_sync_error` why the last one failed (null when it worked). The database reads share one snapshot, so the totals add up; the repo directories are walked on each call, which takes longer the more files the checkouts hold. +`GET /v1/admin/overview` answers `{"now", "server", "storage", "tenants"}`; `now` here and in `GET /v1/admin/pushes` is the database's clock (the one that stamps `updated_at` and decides `stale`), not the server process's, so the ages on the page agree even when the hosts' clocks differ. `server` has `version`, `llm`, `embedder`, `modes`, `models` (`fast` and `deep`, each with `model` and `effort`), `memory` (`rss_bytes` and `peak_rss_bytes`, null outside Linux), and the totals `tenants`, `sources`, `documents` and `chunks`. `storage` has `database_bytes`, `repos_bytes`, `tables` (`name`, `rows_estimate`, `data_bytes`, `index_bytes`, `total_bytes`, largest first) and `indexes` (`name`, `table`, `method`, `bytes`). Each tenant has `id`, `name`, `created_at`, `sources` (`id`, `name`, `kind`, `indexed_commit`, `remote_url`, `last_sync_at`, `last_sync_commit`, `last_sync_error`, `documents`, `chunks`, `last_indexed_at`, `disk_bytes`) and `keys` (`id`, `prefix`, `scopes`, `created_at`, `revoked_at`). `last_indexed_at` is the later of a repo's last push and the source's newest document write, and null until something is indexed; `disk_bytes` is null for sources that are not repos. `last_sync_at` is when the last sync ended, `last_sync_commit` the remote's head at the last sync that worked, and `last_sync_error` why the last one failed (null when it worked). The database reads share one snapshot, so the totals add up; the repo directories are walked on each call, which takes longer the more files the checkouts hold. `GET /v1/admin/pushes` answers `{"now", "running", "recent"}`, newest first, from the `index_runs` table. A push has `id`, `tenant`, `tenant_id`, `source`, `source_id`, `commit`, `full`, `state`, `started_at`, `finished_at`, `updated_at`, `files_total` (null until the bundle is fetched), `files_done`, `chunks`, `chunks_embedded`, `embed_ms`, `error` and `stale` (see the progress route above). `state` is the run's stage. `embed_ms` is wall-clock time in the embedder, including waits while another push uses it. CPU and memory are not measured per push: pushes and searches share one process. diff --git a/src/http/admin.rs b/src/http/admin.rs index e6e1335..eca8d53 100644 --- a/src/http/admin.rs +++ b/src/http/admin.rs @@ -313,7 +313,8 @@ pub async fn delete_source( /// What the server runs and holds, for the admin page. #[derive(Serialize)] pub struct Overview { - /// The server's clock, so a client can show times relative to it. + /// The database's clock (`now()`), the one that sets `updated_at` and decides `stale`, so a + /// client can show times relative to it. now: DateTime, server: ServerFacts, storage: Storage, @@ -477,6 +478,9 @@ pub async fn overview( sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY") .execute(&mut *tx) .await?; + let now: DateTime = sqlx::query_scalar("SELECT now()") + .fetch_one(&mut *tx) + .await?; let tenants: Vec = sqlx::query_as(TENANTS_SQL).fetch_all(&mut *tx).await?; let mut sources: Vec = sqlx::query_as(SOURCES_SQL).fetch_all(&mut *tx).await?; let keys: Vec = sqlx::query_as( @@ -539,7 +543,7 @@ pub async fn overview( } } Ok(Json(Overview { - now: Utc::now(), + now, server, storage, tenants: out, @@ -626,6 +630,7 @@ impl From for PushItem { #[derive(Serialize)] pub struct PushList { + /// The database's clock, like `updated_at` and `stale`. now: DateTime, /// The runs going now, oldest first, whichever process runs them. running: Vec, @@ -639,8 +644,11 @@ pub async fn list_pushes( State(state): State, ) -> Result, AppError> { let (running, recent) = admin_runs(&state.pool, RECENT_RUNS).await?; + let now: DateTime = sqlx::query_scalar("SELECT now()") + .fetch_one(&state.pool) + .await?; Ok(Json(PushList { - now: Utc::now(), + now, running: running.into_iter().map(PushItem::from).collect(), recent: recent.into_iter().map(PushItem::from).collect(), })) diff --git a/src/repo/lock.rs b/src/repo/lock.rs index e32014a..ad438e0 100644 --- a/src/repo/lock.rs +++ b/src/repo/lock.rs @@ -19,6 +19,14 @@ //! keepalive option, so a background task owns the connection and runs `SELECT 1` on it every //! [`PING_INTERVAL`] until the lock is released or dropped. //! +//! A half-open connection (the same NAT case) does not fail a query, it just never answers, and +//! the kernel's TCP retransmit timeout can take a quarter of an hour to give up. Every query on +//! the lock connection, the ping, the unlock and the close, is therefore bound by +//! [`QUERY_TIMEOUT`], and [`SourceAdvisoryLock::release`] waits for the task for a bounded time +//! too, so `lore index` can always exit. A ping that fails or times out ends the keepalive: the +//! connection is gone, so is the session lock, and there is nothing left to keep alive. The index +//! goes on (the row lock and the lock check at commit stay in force) and an error is logged. +//! //! This needs a session-level connection to Postgres itself: through a transaction-mode pooler //! (PgBouncer in `transaction` pool mode) the session advisory lock would belong to whichever //! server connection the pooler handed out for that statement, and it would be lost or leak. @@ -36,6 +44,10 @@ use uuid::Uuid; /// How often the idle lock connection is used, so that a NAT or load balancer does not drop it. pub const PING_INTERVAL: Duration = Duration::from_secs(30); +/// The longest a query on the lock connection may take (the ping, the unlock, the close). Longer +/// means the connection is half-open: it never answers. +pub const QUERY_TIMEOUT: Duration = Duration::from_secs(10); + /// The advisory lock key of a source: the first 8 bytes of its (random, version 4) id. pub fn advisory_key(source_id: Uuid) -> i64 { let bytes = source_id.as_bytes(); @@ -51,6 +63,7 @@ pub struct SourceAdvisoryLock { /// Tells the task owning the connection to unlock and close it; dropping it stops the task. release: Option>, task: Option>, + query_timeout: Duration, } impl SourceAdvisoryLock { @@ -65,6 +78,17 @@ impl SourceAdvisoryLock { database_url: &str, source_id: Uuid, ping_every: Duration, + ) -> Result> { + Self::try_acquire_timed(database_url, source_id, ping_every, QUERY_TIMEOUT).await + } + + /// [`Self::try_acquire_pinging`] with the time one query on the connection may take (a test + /// makes it short). + pub async fn try_acquire_timed( + database_url: &str, + source_id: Uuid, + ping_every: Duration, + query_timeout: Duration, ) -> Result> { let mut conn = PgConnection::connect(database_url) .await @@ -77,56 +101,88 @@ impl SourceAdvisoryLock { .context("taking the source lock")? .get(0); if !got { - let _ = conn.close().await; + let _ = tokio::time::timeout(query_timeout, conn.close()).await; return Ok(None); } let (release, released) = oneshot::channel(); - let task = tokio::spawn(hold(conn, key, ping_every, released)); + let task = tokio::spawn(hold(conn, key, ping_every, query_timeout, released)); Ok(Some(Self { release: Some(release), task: Some(task), + query_timeout, })) } /// Unlocks and closes the connection. A failure is not an error: closing the connection - /// releases the lock anyway. + /// releases the lock anyway. It waits for the task for a bounded time (the unlock and the + /// close each have the query timeout), so it returns even when the connection is half-open. pub async fn release(mut self) { if let Some(release) = self.release.take() { let _ = release.send(()); } if let Some(task) = self.task.take() { - let _ = task.await; + let abort = task.abort_handle(); + if tokio::time::timeout(self.query_timeout * 3, task) + .await + .is_err() + { + // Aborting drops the connection, which ends the session, and the lock with it. + abort.abort(); + tracing::warn!("the source lock connection did not answer; dropped it"); + } } } } /// Owns the lock connection: pings it every `ping_every`, and on a release request unlocks and -/// closes it. When the sender is dropped without a request, the connection is just closed. +/// closes it. When the sender is dropped without a request, the connection is just closed. Every +/// query has `query_timeout`; a ping that fails or times out ends the task, which drops the +/// connection. async fn hold( mut conn: PgConnection, key: i64, ping_every: Duration, + query_timeout: Duration, mut released: oneshot::Receiver<()>, ) { let mut next = tokio::time::Instant::now() + ping_every; loop { tokio::select! { requested = &mut released => { - if requested.is_ok() - && let Err(e) = sqlx::query("SELECT pg_advisory_unlock($1)") - .bind(key) - .execute(&mut conn) - .await - { - tracing::warn!(error = %e, "could not unlock the source"); + if requested.is_ok() { + let unlock = tokio::time::timeout( + query_timeout, + sqlx::query("SELECT pg_advisory_unlock($1)") + .bind(key) + .execute(&mut conn), + ) + .await; + match unlock { + Ok(Ok(_)) => {} + Ok(Err(e)) => tracing::warn!(error = %e, "could not unlock the source"), + Err(_) => tracing::warn!("the source unlock got no answer in time"), + } } - let _ = conn.close().await; + let _ = tokio::time::timeout(query_timeout, conn.close()).await; return; } _ = tokio::time::sleep_until(next) => { next = tokio::time::Instant::now() + ping_every; - if let Err(e) = sqlx::query("SELECT 1").execute(&mut conn).await { - tracing::warn!(error = %e, "the source lock connection failed its keepalive"); + let ping = tokio::time::timeout( + query_timeout, + sqlx::query("SELECT 1").execute(&mut conn), + ) + .await; + match ping { + Ok(Ok(_)) => {} + Ok(Err(e)) => { + tracing::error!(error = %e, "the source lock connection failed its keepalive; the lock may be lost"); + return; + } + Err(_) => { + tracing::error!("the source lock connection did not answer its keepalive; the lock may be lost"); + return; + } } } } diff --git a/src/repo/mod.rs b/src/repo/mod.rs index f65ea2d..3a7b4f5 100644 --- a/src/repo/mod.rs +++ b/src/repo/mod.rs @@ -464,6 +464,10 @@ async fn index_commit( // files only that commit had, so ask for a full index instead; nothing is written yet. if !full_mode && locked_commit != source.indexed_commit { tx.rollback().await?; + // The mirror's indexed ref and the checkout already moved to `commit`, ahead of the + // database. Put them back to what this run started from, so deep mode keeps reading + // what search serves until the full index that follows. + restore_indexed(paths, source.indexed_commit.as_deref()).await; return Err(IngestError::NeedFull); } let mut job = Job { @@ -505,6 +509,23 @@ async fn index_commit( Ok(job.report) } +/// Puts the mirror's indexed ref and the checkout back at `previous` (the commit an index run +/// started from), after the run moved them and then did not index. A failure is only logged: the +/// full index that follows moves both again. +async fn restore_indexed(paths: &RepoPaths, previous: Option<&str>) { + let Some(previous) = previous else { return }; + let result = async { + paths + .mirror_git(&["update-ref", "refs/heads/lore-indexed", previous]) + .await?; + refresh_checkout(paths, previous).await + } + .await; + if let Err(e) = result { + tracing::warn!(error = %e, commit = previous, "could not put the checkout back after a refused index"); + } +} + /// The longest header line accepted: a ref line is a sha and a ref name. const MAX_HEADER_LINE: u64 = 4096; diff --git a/src/repo/progress.rs b/src/repo/progress.rs index 1c44046..cf57c1e 100644 --- a/src/repo/progress.rs +++ b/src/repo/progress.rs @@ -41,6 +41,14 @@ const FINISH_WAIT: Duration = Duration::from_secs(10); const FINAL_TRIES: u32 = 3; /// The run has not ended (`r` is the alias of `index_runs`). +/// How many runs of one source are kept. A run that is going is never removed; of the others, +/// the newest ones stay, so the admin page's recent list and a source's latest run are always +/// there, and the table does not grow with every push forever. +pub const KEEP_RUNS_PER_SOURCE: i64 = 50; + +/// The longest the prune of a source's old runs may take. +const PRUNE_TIMEOUT: Duration = Duration::from_secs(5); + const NOT_ENDED: &str = "r.stage NOT IN ('done','failed')"; /// The run was written in the last 90 seconds. Older and not ended means stale: the process /// that ran it is gone. @@ -270,6 +278,20 @@ async fn write_run( return; } }; + // Old rows go now, after the new one exists and the push has stopped waiting for it. A + // failure only leaves them for the next run. + match tokio::time::timeout( + PRUNE_TIMEOUT, + prune_runs(&writer.pool, new.source_id, KEEP_RUNS_PER_SOURCE), + ) + .await + { + Ok(Ok(_)) => {} + Ok(Err(e)) => { + tracing::warn!(error = %e, source = %new.source_id, "could not prune old index runs"); + } + Err(_) => tracing::warn!(source = %new.source_id, "pruning old index runs took too long"), + } let mut written = Snapshot::queued(&new.commit, new.full); let mut last_write = Instant::now(); let mut last_failed = false; @@ -355,6 +377,26 @@ async fn insert_run(pool: &PgPool, new: &NewRun) -> sqlx::Result { Ok(id) } +/// Deletes the source's runs beyond the newest `keep`, except runs that are going (not ended and +/// not stale). A stale run, whose process is gone, counts as old like an ended one. Returns how +/// many rows went. +pub async fn prune_runs(pool: &PgPool, source_id: Uuid, keep: i64) -> sqlx::Result { + let done = sqlx::query(&format!( + "DELETE FROM index_runs r + WHERE r.source_id = $1 + AND NOT ({NOT_ENDED} AND {FRESH}) + AND r.id < COALESCE( + (SELECT min(k.id) FROM (SELECT id FROM index_runs + WHERE source_id = $1 ORDER BY id DESC LIMIT $2) k), + 0)" + )) + .bind(source_id) + .bind(keep) + .execute(pool) + .await?; + Ok(done.rows_affected()) +} + fn db_int(n: usize) -> i32 { i32::try_from(n).unwrap_or(i32::MAX) } diff --git a/tests/admin.rs b/tests/admin.rs index d06cfbd..d985dc0 100644 --- a/tests/admin.rs +++ b/tests/admin.rs @@ -507,3 +507,51 @@ async fn the_runs_of_a_deleted_tenant_go_with_it(pool: PgPool) { assert_eq!(overview["tenants"], json!([])); assert_eq!(overview["server"]["documents"], 0); } + +/// The admin page shows how old a run is with the `now` of the response, and `updated_at` and +/// `stale` come from the database's clock. So `now` is the database's too, not this process's: +/// two hosts whose clocks differ would otherwise show every age wrong. Here the database's +/// `now()` runs an hour ahead of this process, and both endpoints must report that hour. +#[sqlx::test(migrations = "./migrations")] +async fn the_admin_answers_carry_the_databases_clock(pool: PgPool) { + sqlx::query( + "CREATE FUNCTION public.now() RETURNS timestamptz LANGUAGE sql STABLE + AS $$ SELECT pg_catalog.now() + interval '1 hour' $$", + ) + .execute(&pool) + .await + .unwrap(); + let database = pool.connect_options().get_database().unwrap().to_string(); + sqlx::query(&format!( + "ALTER DATABASE \"{database}\" SET search_path = public, pg_catalog" + )) + .execute(&pool) + .await + .unwrap(); + // Connections opened from here on see the other clock. + let skewed = sqlx::postgres::PgPoolOptions::new() + .max_connections(3) + .connect_with((*pool.connect_options()).clone()) + .await + .unwrap(); + let database_secs: f64 = sqlx::query_scalar("SELECT extract(epoch FROM now())::float8") + .fetch_one(&skewed) + .await + .unwrap(); + let database_ahead = database_secs - chrono::Utc::now().timestamp() as f64; + assert!( + (database_ahead - 3600.0).abs() < 60.0, + "the test database clock is not an hour ahead: {database_ahead} s" + ); + + let env = env(skewed); + for path in ["/v1/admin/pushes", "/v1/admin/overview"] { + let body = admin_get(&env.router, path).await; + let now = chrono::DateTime::parse_from_rfc3339(body["now"].as_str().unwrap()).unwrap(); + let ahead_by = now.timestamp() - chrono::Utc::now().timestamp(); + assert!( + (ahead_by - 3600).abs() < 60, + "{path} answered the process clock, not the database's: {now} is {ahead_by} s ahead" + ); + } +} diff --git a/tests/cli_index.rs b/tests/cli_index.rs index f86e173..eb259d5 100644 --- a/tests/cli_index.rs +++ b/tests/cli_index.rs @@ -7,6 +7,8 @@ mod common; use std::os::unix::fs::PermissionsExt; use std::path::Path; use std::process::Command; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use axum::Router; use common::{ @@ -751,6 +753,24 @@ async fn a_push_that_queued_behind_an_index_does_not_apply_its_stale_diff(pool: assert!(docs.contains(&"ghost.md".to_string()), "{docs:?}"); assert!(!docs.contains(&"c.md".to_string()), "{docs:?}"); + // The refused push had already moved the server's indexed ref and checkout to C. They are + // put back to A, where this push started, and are not left ahead of the database. + let server_repo = env + ._server_data + .path() + .join("repos") + .join(source.to_string()); + let mirror = server_repo.join("mirror.git"); + assert_eq!( + git(&mirror, &["rev-parse", "refs/heads/lore-indexed"]).trim(), + a + ); + assert!( + !server_repo.join("checkout/c.md").exists(), + "the checkout is still at the refused commit" + ); + assert!(server_repo.join("checkout/README.md").exists()); + // The client's answer to the 409, a full push of C, lands cleanly and drops ghost.md. let (status, body) = put_bundle( &env.router, @@ -825,3 +845,109 @@ async fn the_lock_connection_is_kept_alive_while_held_and_freed_on_release(pool: } assert!(freed, "a dropped lock is freed"); } + +/// A TCP forwarder to the test database whose traffic can be frozen: the connection stays open +/// and nothing moves on it, like a half-open connection behind a NAT that lost its state. +struct Proxy { + /// The DSN of the database through the proxy. + dsn: String, + frozen: Arc, +} + +async fn pump( + mut from: impl tokio::io::AsyncRead + Unpin, + mut to: impl tokio::io::AsyncWrite + Unpin, + frozen: Arc, +) { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let mut buf = [0u8; 8192]; + loop { + let n = match from.read(&mut buf).await { + Ok(0) | Err(_) => return, + Ok(n) => n, + }; + while frozen.load(Ordering::SeqCst) { + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + if to.write_all(&buf[..n]).await.is_err() { + return; + } + } +} + +async fn proxy(pool: &PgPool) -> Proxy { + use tokio::net::{TcpListener, TcpStream}; + let direct = reqwest::Url::parse(&dsn(pool)).unwrap(); + let upstream = format!( + "{}:{}", + direct.host_str().unwrap(), + direct.port().unwrap_or(5432) + ); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let frozen = Arc::new(AtomicBool::new(false)); + let flag = frozen.clone(); + tokio::spawn(async move { + while let Ok((client, _)) = listener.accept().await { + let Ok(server) = TcpStream::connect(&upstream).await else { + continue; + }; + let (client_read, client_write) = client.into_split(); + let (server_read, server_write) = server.into_split(); + tokio::spawn(pump(client_read, server_write, flag.clone())); + tokio::spawn(pump(server_read, client_write, flag.clone())); + } + }); + let mut via = direct; + via.set_host(Some("127.0.0.1")).unwrap(); + via.set_port(Some(port)).unwrap(); + Proxy { + dsn: via.to_string(), + frozen, + } +} + +/// On a half-open connection a query never gets an answer. Releasing the lock, which sends an +/// unlock, must not hang: each step has a timeout. +#[sqlx::test(migrations = "./migrations")] +async fn releasing_a_lock_on_a_dead_connection_returns(pool: PgPool) { + let proxy = proxy(&pool).await; + let source = Uuid::new_v4(); + let held = SourceAdvisoryLock::try_acquire_timed( + &proxy.dsn, + source, + std::time::Duration::from_secs(3600), + std::time::Duration::from_millis(300), + ) + .await + .unwrap() + .expect("the lock is free"); + + proxy.frozen.store(true, Ordering::SeqCst); + tokio::time::timeout(std::time::Duration::from_secs(5), held.release()) + .await + .expect("release returned although the connection never answers"); +} + +/// The same for the keepalive: a ping that gets no answer must not keep `release` waiting. +#[sqlx::test(migrations = "./migrations")] +async fn a_keepalive_on_a_dead_connection_does_not_block_the_release(pool: PgPool) { + let proxy = proxy(&pool).await; + let source = Uuid::new_v4(); + let held = SourceAdvisoryLock::try_acquire_timed( + &proxy.dsn, + source, + std::time::Duration::from_millis(50), + std::time::Duration::from_millis(300), + ) + .await + .unwrap() + .expect("the lock is free"); + + proxy.frozen.store(true, Ordering::SeqCst); + // A ping is now on the wire and unanswered. + tokio::time::sleep(std::time::Duration::from_millis(150)).await; + tokio::time::timeout(std::time::Duration::from_secs(5), held.release()) + .await + .expect("release returned although a ping is unanswered"); +} diff --git a/tests/index_runs.rs b/tests/index_runs.rs index 8616d5c..befcef2 100644 --- a/tests/index_runs.rs +++ b/tests/index_runs.rs @@ -16,7 +16,7 @@ use common::{ use lore::embed::{Embedder, HashEmbedder}; use lore::http::AppState; use lore::repo::IndexReport; -use lore::repo::progress::RunWriter; +use lore::repo::progress::{KEEP_RUNS_PER_SOURCE, RunWriter}; use lore::store::IndexStats; use serde_json::{Value, json}; use sqlx::PgPool; @@ -757,3 +757,84 @@ async fn the_runs_of_a_deleted_source_go_with_it(pool: PgPool) { assert_eq!(status, 204, "{body}"); assert!(rows(&pool, source).await.is_empty()); } + +/// Every push adds a row, so the table is cut back: the newest runs of each source stay, and a +/// run that is going stays however old it is. Another source's runs are not touched. +#[sqlx::test(migrations = "./migrations")] +async fn only_the_newest_runs_of_a_source_are_kept(pool: PgPool) { + let a = app(pool.clone()); + let (tenant, key, source) = tenant_with_repo(&a, "acme").await; + let (status, other) = create_repo(&a.router, &key, "other").await; + assert_eq!(status, 200, "{other}"); + let other: Uuid = other["id"].as_str().unwrap().parse().unwrap(); + let writer = RunWriter::new(pool.clone()); + + // The oldest run is still going; the second one's process died. + let going = writer.start(source, tenant, &"1".repeat(40), false).await; + going.cloning(); + let lost = writer.start(source, tenant, &"2".repeat(40), false).await; + lost.cloning(); + wait_for_row(&pool, source, |r| r.stage == "cloning").await; + sqlx::query("UPDATE index_runs SET updated_at = now() - interval '1 hour' WHERE commit = $1") + .bind("2".repeat(40)) + .execute(&pool) + .await + .unwrap(); + for _ in 0..3 { + writer + .start(other, tenant, &"9".repeat(40), false) + .await + .done(&report(1)) + .await; + } + + let keep = usize::try_from(KEEP_RUNS_PER_SOURCE).unwrap(); + for i in 0..keep + 5 { + let commit = format!("{i:040}"); + writer + .start(source, tenant, &commit, false) + .await + .done(&report(1)) + .await; + } + + // The pruning runs behind each start; wait until it has caught up: the newest `keep` runs, + // plus the one that is going. + let start = Instant::now(); + let left = loop { + let left = rows(&pool, source).await; + if left.len() == keep + 1 || start.elapsed() > Duration::from_secs(10) { + break left; + } + tokio::time::sleep(Duration::from_millis(50)).await; + }; + assert_eq!(left.len(), keep + 1, "{left:?}"); + let commits: Vec = + sqlx::query_scalar("SELECT commit FROM index_runs WHERE source_id = $1") + .bind(source) + .fetch_all(&pool) + .await + .unwrap(); + assert!( + commits.contains(&"1".repeat(40)), + "the running run was pruned" + ); + assert!( + !commits.contains(&"2".repeat(40)), + "a run nobody writes any more is old like an ended one" + ); + assert!( + !commits.contains(&format!("{:040}", 0)), + "the oldest ended run is still there" + ); + assert!( + commits.contains(&format!("{:040}", keep + 4)), + "the newest run is gone" + ); + assert_eq!( + rows(&pool, other).await.len(), + 3, + "another source was pruned" + ); + drop((going, lost)); +} From e82f6d257a316388ed4d6161e6de9939ff62b067 Mon Sep 17 00:00:00 2001 From: Ashish Bagri Date: Sat, 14 Nov 2026 12:03:13 +0100 Subject: [PATCH 2/2] Lore: a refused push restores the commit the database holds (TR-1313 review F1, F5, F6) A push refused behind a `lore index` put the indexed ref and the checkout back at the commit the push started from, which is behind what the database holds. It now restores to the commit the database holds when this server's mirror has it, and to the start commit otherwise. Moves the NOT_ENDED doc comment back to NOT_ENDED, and tests that a stale run inside the newest window is kept. Co-Authored-By: Claude Sonnet 5.5 --- docs/usage.md | 2 +- src/repo/mod.rs | 40 +++++++++++++++++++++++++++----------- src/repo/progress.rs | 2 +- tests/cli_index.rs | 46 +++++++++++++++++++++++++++++++++++++------- tests/index_runs.rs | 33 ++++++++++++++++++++++++++++++- 5 files changed, 102 insertions(+), 21 deletions(-) diff --git a/docs/usage.md b/docs/usage.md index f105bdf..7f6cf01 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -171,7 +171,7 @@ The repo must belong to the tenant: a source of another tenant, a source that do The run shows in `index_runs` like any index run, so `GET /v1/repos/{id}/progress` and the admin page show its stage and counts while it works and `done` or `failed` after. A process that is killed leaves a run that goes stale, as for the server. -One `lore index` per repo at a time: it holds a Postgres advisory lock on the repo for the whole run, on a connection of its own. A second one for the same repo does not wait; it exits at once with code 3 (`another index of source is running`). The lock is released when the process ends, however it ends. Other repos are not affected, and the server's own pushes and syncs of that repo still serialise with it on the row lock the index takes while it writes. A server incremental push or sync that waited on that row lock behind an index that moved the indexed commit is answered with the full-index path (409 `need_full_bundle` for a push, a full index for a sync) instead of applying a stale diff, and the repo's `lore-indexed` ref and checkout are put back at the indexed commit the database holds, so they never run ahead of it after a refused push. The lock connection is pinged every 30 seconds so an idle-connection timeout of a NAT or load balancer does not drop it. A ping, the unlock and the close each wait 10 seconds at most, so a connection that went half-open (open, but never answering) cannot keep `lore index` from exiting; a ping that gets no answer is logged as an error and ends the pinging, since the session lock is then lost with the connection; point `LORE_DATABASE_URL` at Postgres or a session-mode pooler, not a transaction-mode one (PgBouncer `pool_mode=transaction`), which cannot hold a session lock. +One `lore index` per repo at a time: it holds a Postgres advisory lock on the repo for the whole run, on a connection of its own. A second one for the same repo does not wait; it exits at once with code 3 (`another index of source is running`). The lock is released when the process ends, however it ends. Other repos are not affected, and the server's own pushes and syncs of that repo still serialise with it on the row lock the index takes while it writes. A server incremental push or sync that waited on that row lock behind an index that moved the indexed commit is answered with the full-index path (409 `need_full_bundle` for a push, a full index for a sync) instead of applying a stale diff, and the repo's `lore-indexed` ref and checkout are put back, so they never run ahead of the database after a refused push: at the indexed commit the database holds when this server's mirror has that commit, otherwise at the commit the push started from. The lock connection is pinged every 30 seconds so an idle-connection timeout of a NAT or load balancer does not drop it. A ping, the unlock and the close each wait 10 seconds at most, so a connection that went half-open (open, but never answering) cannot keep `lore index` from exiting; a ping that gets no answer is logged as an error and ends the pinging, since the session lock is then lost with the connection; point `LORE_DATABASE_URL` at Postgres or a session-mode pooler, not a transaction-mode one (PgBouncer `pool_mode=transaction`), which cannot hold a session lock. | Exit code | Meaning | |---|---| diff --git a/src/repo/mod.rs b/src/repo/mod.rs index 3a7b4f5..332c03e 100644 --- a/src/repo/mod.rs +++ b/src/repo/mod.rs @@ -465,9 +465,16 @@ async fn index_commit( if !full_mode && locked_commit != source.indexed_commit { tx.rollback().await?; // The mirror's indexed ref and the checkout already moved to `commit`, ahead of the - // database. Put them back to what this run started from, so deep mode keeps reading - // what search serves until the full index that follows. - restore_indexed(paths, source.indexed_commit.as_deref()).await; + // database. Put them back to what the database holds now (the other process's commit), + // so deep mode keeps reading what search serves until the full index that follows. That + // commit may not be in this mirror (the other process has its own data); then the + // commit this run started from is the nearest one this mirror has. + restore_indexed( + paths, + locked_commit.as_deref(), + source.indexed_commit.as_deref(), + ) + .await; return Err(IngestError::NeedFull); } let mut job = Job { @@ -509,20 +516,31 @@ async fn index_commit( Ok(job.report) } -/// Puts the mirror's indexed ref and the checkout back at `previous` (the commit an index run -/// started from), after the run moved them and then did not index. A failure is only logged: the -/// full index that follows moves both again. -async fn restore_indexed(paths: &RepoPaths, previous: Option<&str>) { - let Some(previous) = previous else { return }; +/// Puts the mirror's indexed ref and the checkout back after an index run moved them and then +/// did not index. The target is `database` (the commit the database holds) when the mirror has +/// it, else `started_from` (the commit the run started from). A failure is only logged: the full +/// index that follows moves both again. +async fn restore_indexed(paths: &RepoPaths, database: Option<&str>, started_from: Option<&str>) { + let mut target = started_from; + if let Some(commit) = database { + let present = paths + .mirror_git(&["cat-file", "-e", &format!("{commit}^{{commit}}")]) + .await + .is_ok(); + if present { + target = Some(commit); + } + } + let Some(target) = target else { return }; let result = async { paths - .mirror_git(&["update-ref", "refs/heads/lore-indexed", previous]) + .mirror_git(&["update-ref", "refs/heads/lore-indexed", target]) .await?; - refresh_checkout(paths, previous).await + refresh_checkout(paths, target).await } .await; if let Err(e) = result { - tracing::warn!(error = %e, commit = previous, "could not put the checkout back after a refused index"); + tracing::warn!(error = %e, commit = target, "could not put the checkout back after a refused index"); } } diff --git a/src/repo/progress.rs b/src/repo/progress.rs index cf57c1e..daa55d8 100644 --- a/src/repo/progress.rs +++ b/src/repo/progress.rs @@ -40,7 +40,6 @@ const FINISH_WAIT: Duration = Duration::from_secs(10); /// How often the write of a run's end is tried. const FINAL_TRIES: u32 = 3; -/// The run has not ended (`r` is the alias of `index_runs`). /// How many runs of one source are kept. A run that is going is never removed; of the others, /// the newest ones stay, so the admin page's recent list and a source's latest run are always /// there, and the table does not grow with every push forever. @@ -49,6 +48,7 @@ pub const KEEP_RUNS_PER_SOURCE: i64 = 50; /// The longest the prune of a source's old runs may take. const PRUNE_TIMEOUT: Duration = Duration::from_secs(5); +/// The run has not ended (`r` is the alias of `index_runs`). const NOT_ENDED: &str = "r.stage NOT IN ('done','failed')"; /// The run was written in the last 90 seconds. Older and not ended means stale: the process /// that ran it is gone. diff --git a/tests/cli_index.rs b/tests/cli_index.rs index eb259d5..f6a9463 100644 --- a/tests/cli_index.rs +++ b/tests/cli_index.rs @@ -687,12 +687,25 @@ async fn indexed_paths(pool: &PgPool, source: Uuid) -> Vec { /// a full bundle, and leave the index as the job made it. #[sqlx::test(migrations = "./migrations")] async fn a_push_that_queued_behind_an_index_does_not_apply_its_stale_diff(pool: PgPool) { + a_push_refused_behind_an_index(pool, false).await; +} + +/// The same, when the server's mirror has the job's commit (a sync fetched it): the refused push +/// puts the ref and the checkout back at what the database holds, not at where the push started. +#[sqlx::test(migrations = "./migrations")] +async fn a_refused_push_restores_the_commit_the_database_holds_when_the_mirror_has_it( + pool: PgPool, +) { + a_push_refused_behind_an_index(pool, true).await; +} + +async fn a_push_refused_behind_an_index(pool: PgPool, mirror_has_b: bool) { let env = Env::new(pool.clone()); let (tenant, key, source) = env.tenant("jobs").await; let repo = fixture_repo(); - // A: the server's full push. B adds ghost.md, and the job's remote is a clone at B. C drops - // ghost.md again and adds a file. + // A: the server's full push. B adds ghost.md, and the job's remote is a clone at B. C is + // another commit on top of A (not of B), so the push of C does not carry B to the server. let a = head(&repo); let (status, body) = put_bundle( &env.router, @@ -712,9 +725,9 @@ async fn a_push_that_queued_behind_an_index_does_not_apply_its_stale_diff(pool: repo.path(), &["clone", "-q", ".", &job_remote.path().to_string_lossy()], ); - std::fs::remove_file(repo.path().join("ghost.md")).unwrap(); + git(repo.path(), &["reset", "-q", "--hard", &a]); std::fs::write(repo.path().join("c.md"), "# See\n\nOnly C has me.\n").unwrap(); - commit_all(&repo, "C drops ghost.md"); + commit_all(&repo, "C adds c.md"); let c = head(&repo); // Hold the source row, so both writers queue on it, the job first. @@ -739,6 +752,18 @@ async fn a_push_that_queued_behind_an_index_does_not_apply_its_stale_diff(pool: tokio::spawn(async move { put_bundle(&router, &key, source, bytes, &c, false).await }) }; wait_for_waiters(&pool, 2).await; + if mirror_has_b { + let server_mirror = env + ._server_data + .path() + .join("repos") + .join(source.to_string()) + .join("mirror.git"); + git( + &server_mirror, + &["fetch", "-q", &job_remote.path().to_string_lossy(), "HEAD"], + ); + } hold.rollback().await.unwrap(); let job_out = job.await.unwrap(); @@ -748,28 +773,35 @@ async fn a_push_that_queued_behind_an_index_does_not_apply_its_stale_diff(pool: assert_eq!(body["error"], "need_full_bundle", "{body}"); // Nothing of the refused push was applied: the index is B, ghost.md included, c.md absent. - assert_eq!(indexed_commit(&pool, source).await, Some(b)); + assert_eq!(indexed_commit(&pool, source).await, Some(b.clone())); let docs = indexed_paths(&pool, source).await; assert!(docs.contains(&"ghost.md".to_string()), "{docs:?}"); assert!(!docs.contains(&"c.md".to_string()), "{docs:?}"); // The refused push had already moved the server's indexed ref and checkout to C. They are - // put back to A, where this push started, and are not left ahead of the database. + // put back, and are not left ahead of the database: at B, which the database holds, when the + // mirror has B, else at A, where this push started. let server_repo = env ._server_data .path() .join("repos") .join(source.to_string()); let mirror = server_repo.join("mirror.git"); + let restored = if mirror_has_b { &b } else { &a }; assert_eq!( git(&mirror, &["rev-parse", "refs/heads/lore-indexed"]).trim(), - a + restored ); assert!( !server_repo.join("checkout/c.md").exists(), "the checkout is still at the refused commit" ); assert!(server_repo.join("checkout/README.md").exists()); + assert_eq!( + server_repo.join("checkout/ghost.md").exists(), + mirror_has_b, + "the checkout is at the wrong commit" + ); // The client's answer to the 409, a full push of C, lands cleanly and drops ghost.md. let (status, body) = put_bundle( diff --git a/tests/index_runs.rs b/tests/index_runs.rs index befcef2..49a52b5 100644 --- a/tests/index_runs.rs +++ b/tests/index_runs.rs @@ -16,7 +16,7 @@ use common::{ use lore::embed::{Embedder, HashEmbedder}; use lore::http::AppState; use lore::repo::IndexReport; -use lore::repo::progress::{KEEP_RUNS_PER_SOURCE, RunWriter}; +use lore::repo::progress::{KEEP_RUNS_PER_SOURCE, RunWriter, prune_runs}; use lore::store::IndexStats; use serde_json::{Value, json}; use sqlx::PgPool; @@ -838,3 +838,34 @@ async fn only_the_newest_runs_of_a_source_are_kept(pool: PgPool) { ); drop((going, lost)); } + +/// A stale run (its process is gone) is old like an ended one, but only by its position: one +/// among the newest runs stays, and one beyond them goes. +#[sqlx::test(migrations = "./migrations")] +async fn a_stale_run_among_the_newest_is_kept(pool: PgPool) { + let a = app(pool.clone()); + let (tenant, _key, source) = tenant_with_repo(&a, "acme").await; + let writer = RunWriter::new(pool.clone()); + + let lost = writer.start(source, tenant, &"1".repeat(40), false).await; + lost.cloning(); + wait_for_row(&pool, source, |r| r.stage == "cloning").await; + sqlx::query("UPDATE index_runs SET updated_at = now() - interval '1 hour' WHERE commit = $1") + .bind("1".repeat(40)) + .execute(&pool) + .await + .unwrap(); + writer + .start(source, tenant, &"2".repeat(40), false) + .await + .done(&report(1)) + .await; + + // Two runs, and room for two: nothing goes, the stale one included. + assert_eq!(prune_runs(&pool, source, 2).await.unwrap(), 0); + assert_eq!(rows(&pool, source).await.len(), 2); + // Room for one: the older run, the stale one, is beyond the newest and goes. + assert_eq!(prune_runs(&pool, source, 1).await.unwrap(), 1); + assert_eq!(rows(&pool, source).await.len(), 1); + drop(lost); +}