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
6 changes: 3 additions & 3 deletions docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ curl -X PUT "localhost:8080/v1/repos/<id>/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`
Expand Down Expand Up @@ -173,7 +173,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 <id> 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 <id> 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 |
|---|---|
Expand Down Expand Up @@ -319,7 +319,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.

Expand Down
14 changes: 11 additions & 3 deletions src/http/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Utc>,
server: ServerFacts,
storage: Storage,
Expand Down Expand Up @@ -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<Utc> = sqlx::query_scalar("SELECT now()")
.fetch_one(&mut *tx)
.await?;
let tenants: Vec<TenantItem> = sqlx::query_as(TENANTS_SQL).fetch_all(&mut *tx).await?;
let mut sources: Vec<SourceOverview> = sqlx::query_as(SOURCES_SQL).fetch_all(&mut *tx).await?;
let keys: Vec<KeyRow> = sqlx::query_as(
Expand Down Expand Up @@ -539,7 +543,7 @@ pub async fn overview(
}
}
Ok(Json(Overview {
now: Utc::now(),
now,
server,
storage,
tenants: out,
Expand Down Expand Up @@ -626,6 +630,7 @@ impl From<NamedRun> for PushItem {

#[derive(Serialize)]
pub struct PushList {
/// The database's clock, like `updated_at` and `stale`.
now: DateTime<Utc>,
/// The runs going now, oldest first, whichever process runs them.
running: Vec<PushItem>,
Expand All @@ -639,8 +644,11 @@ pub async fn list_pushes(
State(state): State<AppState>,
) -> Result<Json<PushList>, AppError> {
let (running, recent) = admin_runs(&state.pool, RECENT_RUNS).await?;
let now: DateTime<Utc> = 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(),
}))
Expand Down
86 changes: 71 additions & 15 deletions src/repo/lock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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();
Expand All @@ -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<oneshot::Sender<()>>,
task: Option<JoinHandle<()>>,
query_timeout: Duration,
}

impl SourceAdvisoryLock {
Expand All @@ -65,6 +78,17 @@ impl SourceAdvisoryLock {
database_url: &str,
source_id: Uuid,
ping_every: Duration,
) -> Result<Option<Self>> {
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<Option<Self>> {
let mut conn = PgConnection::connect(database_url)
.await
Expand All @@ -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;
}
}
}
}
Expand Down
Loading
Loading