Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
d8d5dd1
fix(storage-postgres): check data relations against the catalog by id
LeeroyHannigan Oct 30, 2026
4556ffc
fix(app): compare data relations with the catalog through the storage…
LeeroyHannigan Oct 30, 2026
b1408eb
test(storage-postgres): cover catalog-check against the relations the…
LeeroyHannigan Oct 30, 2026
9b2dad8
docs: describe catalog-check and --fix for data relations without a c…
LeeroyHannigan Oct 30, 2026
ee5c814
fix(storage-postgres): wait only for index writers in catalog-check
LeeroyHannigan Oct 30, 2026
e666798
test(storage-postgres): cover catalog-check against changes in flight
LeeroyHannigan Oct 30, 2026
6d6383d
docs: state what catalog-check reports and drops while a server runs
LeeroyHannigan Oct 30, 2026
16c62f5
test(storage-postgres): bound the held-orphan drop in its test
LeeroyHannigan Oct 30, 2026
90d4294
fix(storage-postgres): lock indexes in catalog-check only for an unna…
LeeroyHannigan Oct 30, 2026
60171fb
test(storage-postgres): check the catalog-check lock wait holds nothi…
LeeroyHannigan Oct 30, 2026
4f5305c
test(storage-postgres): commit the GSI add while catalog-check waits
LeeroyHannigan Oct 30, 2026
286f6c3
docs: state that catalog-check waits for index writers only when needed
LeeroyHannigan Oct 30, 2026
fe791ce
docs: drop the count from the catalog-check wrong-report sentence
LeeroyHannigan Oct 30, 2026
c530d9f
Merge origin/main into fix/652-catalog-check-ids
LeeroyHannigan Nov 5, 2026
23e9df4
Merge origin/main into fix/652-catalog-check-ids
LeeroyHannigan Nov 18, 2026
c23efef
fix(app): open the encrypted connection string row in catalog-check
LeeroyHannigan Nov 18, 2026
d22577a
test(storage-postgres): set warm_throughput in the catalog_check GSI …
LeeroyHannigan Nov 18, 2026
7208d60
fix(app): set up the locked key store before catalog-check reads the KEK
LeeroyHannigan Nov 18, 2026
ceffc5e
test(storage-postgres): run the catalog-check relation check on a cat…
LeeroyHannigan Nov 18, 2026
62787ee
docs: state the DeleteTable order of main's #504 in the catalog-check…
LeeroyHannigan Nov 18, 2026
753c44e
test(storage-postgres): fail the catalog_check tests when a job needs…
LeeroyHannigan Nov 19, 2026
2ae1b19
test(storage-postgres): create pgvector in the catalog_check data dat…
LeeroyHannigan Nov 19, 2026
2d98016
test(storage-postgres): cover the end of the catalog-check index lock…
LeeroyHannigan Nov 19, 2026
1c2ffe3
fix(storage-postgres): give the catalog-check index lock text only fo…
LeeroyHannigan Nov 19, 2026
ee338c5
fix(storage-postgres): list the data relations that the search path r…
LeeroyHannigan Nov 19, 2026
bcdeb47
fix(storage-postgres): refuse a key ring row that the key does not op…
LeeroyHannigan Nov 19, 2026
e516b07
docs: state the catalog-check report stop after 30 seconds and the wa…
LeeroyHannigan Nov 19, 2026
4259312
test(app): run catalog-check as the binary against a PostgreSQL deplo…
LeeroyHannigan Nov 19, 2026
a9e49b8
fix(storage-postgres): turn off statement logging on the diagnostics …
LeeroyHannigan Nov 19, 2026
7f2b424
style: format the catalog-check tests with rustfmt
LeeroyHannigan Nov 19, 2026
9ee6fec
test(storage-postgres): check pgvector on the built catalog_check dep…
LeeroyHannigan Nov 19, 2026
5dd94fb
test(storage-postgres): run the drop in the catalog-check failure tes…
LeeroyHannigan Nov 19, 2026
c4e2aaa
docs: drop the catalog-check sentence on waits at each indexes write
LeeroyHannigan Nov 19, 2026
a8bca7e
test: one helper for the catalog-check sessions that hold a lock
LeeroyHannigan Nov 19, 2026
2610afd
refactor(storage-postgres): map the diagnostics store's connect error…
LeeroyHannigan Nov 19, 2026
c9551a9
ci: set the PostgreSQL test settings once for the storage test job
LeeroyHannigan Nov 19, 2026
ea1d0ec
refactor(storage-postgres): drop the unused Debug derive of CheckFailure
LeeroyHannigan Nov 19, 2026
4c18186
test(storage-postgres): use the hold helper in the open index write test
LeeroyHannigan Nov 19, 2026
7309bc7
Merge origin/main into fix/652-catalog-check-ids
LeeroyHannigan Nov 23, 2026
5e36eaa
test(storage-postgres): check an ACTIVE index of a settling table in …
LeeroyHannigan Nov 23, 2026
59b48d4
refactor(storage-postgres): classify undefined_table beside lock_not_…
LeeroyHannigan Nov 23, 2026
9754d3a
refactor(storage-postgres): share the data database read and connect …
LeeroyHannigan Nov 23, 2026
ea52779
test(storage-postgres): assert the full catalog-check messages
LeeroyHannigan Nov 23, 2026
b8dca1a
test(app): remove the catalog-check config directory when the test fails
LeeroyHannigan Nov 23, 2026
66b97c4
docs: say catalog-check waits for the index changes in flight
LeeroyHannigan Nov 23, 2026
75c9a06
style: put PostgreSQL and GetItem in backticks in the catalog-check docs
LeeroyHannigan Nov 23, 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
20 changes: 16 additions & 4 deletions .github/workflows/integration.yml
Original file line number Diff line number Diff line change
Expand Up @@ -729,6 +729,14 @@ jobs:
run-postgres-storage-tests:
runs-on: extenddb_ubuntu-2404_4-core
timeout-minutes: 40
# For both test steps below.
env:
EXTENDDB_TEST_PG_CONNECTION_STRING: postgresql://postgres:devpass@127.0.0.1:5432
# table_snapshot fails rather than skips without the string above.
EXTENDDB_TEST_PG_REQUIRED: "1"
# catalog_check fails when its data database has no pgvector, so
# its tests create and check a vector index relation on this image.
EXTENDDB_EXPECT_VECTORS: "1"
services:
postgres:
image: pgvector/pgvector:pg16
Expand Down Expand Up @@ -775,12 +783,16 @@ jobs:
# table_snapshot: the SnapshotEngine consistency check; it needs the
# shared page-size hook, compiled only into the crate's own test
# build, and scratch databases it creates and drops itself.
env:
EXTENDDB_TEST_PG_CONNECTION_STRING: postgresql://postgres:devpass@127.0.0.1:5432
# table_snapshot fails rather than skips without the string above.
EXTENDDB_TEST_PG_REQUIRED: "1"
# catalog_check: the data relations the engine creates compared with
# the catalog, on a deployment with a separate data database.
run: cargo test --release -p extenddb-storage-postgres --tests

# `extenddb catalog-check` run as the binary on the deployment the
# catalog_check tests above build: the lines it prints, its exit code,
# and its refusal of a catalog without the data database setting.
- name: Run the catalog-check command test
run: cargo test --release -p extenddb --test catalog_check

# The runtime-detection proof: the same binary, against a PostgreSQL with no
# pgvector, must refuse vector indexes over the wire. Today the job above runs
# on a plain image too, so this looks like a duplicate of it; it is not, because
Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

197 changes: 69 additions & 128 deletions crates/app/src/cmd_catalog_check.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
// Copyright 2026 ExtendDB contributors
// SPDX-License-Identifier: Apache-2.0

//! `extenddb catalog-check` — integrity check for catalog and data databases.
//! `extenddb catalog-check`: integrity check for the catalog and data databases.
//!
//! Detects orphaned data/GSI tables, missing data tables, and catalog
//! inconsistencies. Refuses to run while the server is up (PID file check).
//! Detects data relations no catalog row names, catalog rows whose data
//! relations are gone, and catalog inconsistencies. Refuses to run while the
//! server is up (PID file check).
//!
//! This command uses raw `sqlx` queries intentionally. It is a diagnostic
//! tool that runs outside the server process and needs direct database
//! access to cross-reference catalog metadata against physical `PostgreSQL`
//! tables. Routing through the storage abstraction would defeat the purpose
//! of an independent integrity check.

use std::collections::HashSet;
//! The data relations are named by the storage backend from catalog ids, so
//! checks 1 and 2 run through the backend's `DiagnosticsStore`, which
//! computes the expected names with the same functions the engine uses to
//! create them. Checks 3 and 4 read the catalog with raw `sqlx` queries, as
//! the command always has; they need direct access to cross-reference catalog
//! rows against each other.

use clap::Args;
use sqlx::postgres::PgPoolOptions;

use extenddb_config as config;
use extenddb_storage::diagnostics::{DiagError, OrphanDrop};

#[derive(Args)]
pub struct CatalogCheckArgs {
Expand All @@ -30,9 +31,9 @@ pub struct CatalogCheckArgs {
fix: bool,
}

// Linear sequence of 4 independent checks — splitting into helpers would scatter
// the logic without improving readability, and each helper would need the same
// pool/fix parameters threaded through.
// A linear sequence of 4 independent checks. Splitting it into helpers would
// scatter the logic without improving readability, and each helper would need
// the same pool and fix parameters threaded through.
#[allow(clippy::too_many_lines)]
pub async fn run(args: CatalogCheckArgs) -> anyhow::Result<()> {
if !std::path::Path::new(&args.config).exists() {
Expand Down Expand Up @@ -69,96 +70,81 @@ pub async fn run(args: CatalogCheckArgs) -> anyhow::Result<()> {
.map_err(|e| anyhow::anyhow!("Cannot connect to catalog: {e}"))?;
println!("Connected to catalog.");

// Connect to data database.
let data_conn: Option<(String,)> =
sqlx::query_as("SELECT value FROM settings WHERE key = 'data_database_connection_string'")
.fetch_optional(&catalog_pool)
.await?;
let Some((data_conn_str,)) = data_conn else {
anyhow::bail!("No data database connection string in settings. Run `extenddb init`.");
};
let data_conn_str = data_connection_text(&catalog_pool, &app_config, data_conn_str).await?;
let data_pool = PgPoolOptions::new()
.max_connections(2)
.connect(&data_conn_str)
// The key that opens the data database connection string row of a
// catalog with a key ring: the KEK of `[auth.encryption] key_file`, read
// after the locked key store is set up, as `verify` reads it (RFC-0000
// sections 7 and 12). Without `key_file`, the catalog key, which opens no
// such row.
let key_source = crate::util::status_key_source(&app_config)?;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This file has no test, and no workflow runs catalog-check against PostgreSQL. The store tests stop at PostgresCatalogStore, so status_key_source, the NotConfigured mapping, the outcome lines and the exit code are not covered. One test of run against the storage test deployment, with one orphan, one missing relation and the missing setting, would cover them.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 4259312. crates/bin/tests/catalog_check.rs runs the extenddb binary on the storage tests' Deployment, with one orphan and one missing GSI relation, then with the data database setting deleted. It asserts the whole stdout, the last stderr line and the exit status of --fix, of the report, and of the run without the setting. status_key_source runs in each. The storage test job runs it as a new step, in release. It fails when the NotConfigured arm gets the "Cannot compare data relations with the catalog" prefix, and when the final exit(1) becomes exit(0).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional. Replacing status_key_source with CatalogKey here leaves the binary test passing. The test deployment has no key ring and no key_file, so nothing it checks depends on that call. A run against a KEK catalog would hold it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right. The binary test runs a deployment with no key ring and no key_file, so the status_key_source call is not exercised there. A run against a catalog with a KEK would hold it. I'll add that run in a follow-up after this PR merges, so that your approval stands.


// The backend's own view of its data relations. It connects to the data
// database the catalog names, and refuses a catalog that names none, as
// this command always has.
let diag_store = extenddb_storage::diagnostics_store::create_diagnostics_store(
app_config.storage.connection_config(),
)
.await
.map_err(|e| anyhow::anyhow!("Cannot open the storage backend's diagnostics: {e}"))?;
let relations = diag_store
.check_storage_relations(&key_source)
.await
.map_err(|e| anyhow::anyhow!("Cannot connect to data database: {e}"))?;
println!("Connected to data database.");
.map_err(|e| match e {
DiagError::NotConfigured(msg) => anyhow::anyhow!("{msg}"),
e => anyhow::anyhow!("Cannot compare data relations with the catalog: {e}"),
})?;
println!("Compared data relations with the catalog.");
println!();

// Build expected set from catalog: base tables and GSI tables.
// Include CREATING tables — they have data tables even before transitioning
// to ACTIVE. Excluding them would flag their data tables as orphaned.
let catalog_tables: Vec<(String, String)> = sqlx::query_as(
"SELECT account_id, table_name FROM tables \
WHERE table_status IN ('ACTIVE', 'CREATING')",
)
.fetch_all(&catalog_pool)
.await?;

let catalog_indexes: Vec<(String, String, String)> = sqlx::query_as(
"SELECT t.account_id, t.table_name, i.index_name \
FROM indexes i JOIN tables t ON i.table_id = t.table_id \
WHERE t.table_status IN ('ACTIVE', 'CREATING')",
)
.fetch_all(&catalog_pool)
.await?;

let mut expected: HashSet<String> = HashSet::new();
for (acct, name) in &catalog_tables {
expected.insert(format!("_ddb_{acct}_{name}"));
}
for (acct, name, idx) in &catalog_indexes {
expected.insert(format!("_ddb_{acct}_{name}__gsi__{idx}"));
}

// Get actual tables in data database (only _ddb_ prefixed).
let actual_tables: Vec<(String,)> = sqlx::query_as(
"SELECT tablename FROM pg_tables \
WHERE schemaname = 'public' AND tablename LIKE '_ddb_%'",
)
.fetch_all(&data_pool)
.await?;

let actual: HashSet<String> = actual_tables.into_iter().map(|(n,)| n).collect();

// Check 1: Orphaned data tables (in data DB but not in catalog).
// Check 1: Orphaned data tables (in data DB but no catalog row names them).
println!("--- Checking for orphaned data tables...");
let orphaned: Vec<&String> = actual.difference(&expected).collect();
if orphaned.is_empty() {
if relations.orphaned.is_empty() {
println!(" OK: No orphaned tables.");
} else {
println!(" FOUND: {} orphaned table(s):", orphaned.len());
for name in &orphaned {
println!(" FOUND: {} orphaned table(s):", relations.orphaned.len());
for name in &relations.orphaned {
println!(" - {name}");
}
errors += u32::try_from(orphaned.len()).unwrap_or(u32::MAX);
errors += u32::try_from(relations.orphaned.len()).unwrap_or(u32::MAX);

if args.fix {
println!(" Cleaning up orphaned tables...");
for name in &orphaned {
// Table names are from pg_tables (trusted), but quote anyway.
let quoted = format!("\"{}\"", name.replace('"', "\"\""));
let ddl = format!("DROP TABLE IF EXISTS {quoted}");
match sqlx::query(&ddl).execute(&data_pool).await {
Ok(_) => println!(" Dropped: {name}"),
Err(e) => println!(" FAILED to drop {name}: {e}"),
// The backend waits for the index changes in flight, checks each
// relation against the catalog again, and drops each one that no
// row names with a short lock wait of its own.
match diag_store
.drop_orphaned_relations(&key_source, relations.orphaned.clone())
.await
{
Ok(outcomes) => {
for (name, outcome) in &outcomes {
match outcome {
OrphanDrop::Dropped => println!(" Dropped: {name}"),
OrphanDrop::AlreadyGone => println!(
" Already gone: {name} (another session dropped it first)"
),
OrphanDrop::Kept(reason) => println!(" Kept: {name} ({reason})"),
OrphanDrop::Failed(e) => println!(" FAILED to drop {name}: {e}"),
}
}
}
Err(e) => println!(" FAILED to clean up orphaned tables: {e}"),
}
}
}

// Check 2: Missing data tables (in catalog but not in data DB).
// Check 2: Missing data tables (a catalog row names them, data DB lacks them).
println!("--- Checking for missing data tables...");
let missing: Vec<&String> = expected.difference(&actual).collect();
if missing.is_empty() {
if relations.missing.is_empty() {
println!(" OK: All catalog tables have backing data tables.");
} else {
println!(" FOUND: {} missing data table(s):", missing.len());
for name in &missing {
println!(" - {name}");
println!(
" FOUND: {} missing data table(s):",
relations.missing.len()
);
for entry in &relations.missing {
println!(" - {} ({})", entry.relation, entry.owner);
}
errors += u32::try_from(missing.len()).unwrap_or(u32::MAX);
errors += u32::try_from(relations.missing.len()).unwrap_or(u32::MAX);
}

// Check 3: Indexes without parent table in catalog.
Expand Down Expand Up @@ -215,48 +201,3 @@ pub async fn run(args: CatalogCheckArgs) -> anyhow::Result<()> {

Ok(())
}

/// The data database connection string that the row `stored` holds: the
/// row as it is in a catalog without a key ring; with a ring, the row
/// decrypted under a DEK of the ring, which the KEK of `[auth.encryption]
/// key_file` opens (RFC-0000 section 12). A row that no DEK opens is
/// refused, plaintext included, as every reader but `switch` refuses it.
async fn data_connection_text(
catalog: &sqlx::PgPool,
app_config: &config::AppConfig,
stored: String,
) -> anyhow::Result<zeroize::Zeroizing<String>> {
use extenddb_storage::key_ring::{KEY_RING_SETTING, open_ring};
use extenddb_storage::secret_keys::CATALOG_ID_SETTING;
use extenddb_storage::server_components::KeySource;

let setting = async |key: &str| -> anyhow::Result<Option<String>> {
let row: Option<(String,)> = sqlx::query_as("SELECT value FROM settings WHERE key = $1")
.bind(key)
.fetch_optional(catalog)
.await?;
Ok(row.map(|(value,)| value))
};
let Some(ring) = setting(KEY_RING_SETTING).await? else {
return Ok(zeroize::Zeroizing::new(stored));
};
let KeySource::Kek(kek) = extenddb_server::key_file::key_source(&app_config.auth.encryption)
.map_err(anyhow::Error::msg)?
else {
anyhow::bail!(
"The catalog has a key ring, so its data database connection string is encrypted. \
Set [auth.encryption] key_file to the KEK file that the ring names"
);
};
let catalog_id = setting(CATALOG_ID_SETTING).await?;
let open = open_ring(&ring, catalog_id.as_deref(), &kek).map_err(|e| anyhow::anyhow!("{e}"))?;
open.deks
.iter()
.find_map(|dek| dek.decrypt_setting(&stored).ok())
.ok_or_else(|| {
anyhow::anyhow!(
"No DEK of the key ring opens the data_database_connection_string row. Run \
`extenddb encryption-key status`"
)
})
}
5 changes: 5 additions & 0 deletions crates/bin/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,8 @@ sqlx = { workspace = true }
tokio = { workspace = true }
uuid = { workspace = true }
extenddb-storage = { path = "../storage", features = ["test-util"] }
# The catalog-check test builds its deployment with the PostgreSQL storage
# tests' catalog_check support module, which names core types and the
# relation naming functions that `test-hooks` exports.
extenddb-core = { path = "../core" }
extenddb-storage-postgres = { path = "../storage-postgres", features = ["test-hooks"] }
Loading
Loading