Skip to main content

micromegas_ingestion/
sql_migration.rs

1use crate::sql_telemetry_db::create_tables;
2use anyhow::{Context, Result};
3use micromegas_tracing::prelude::*;
4use sqlx::Executor;
5use sqlx::Row;
6
7/// The latest schema version for the data lake.
8pub const LATEST_DATA_LAKE_SCHEMA_VERSION: i32 = 14;
9
10/// Reads the current schema version from the database.
11pub async fn read_data_lake_schema_version(tr: &mut sqlx::Transaction<'_, sqlx::Postgres>) -> i32 {
12    match sqlx::query(
13        "SELECT version
14         FROM migration;",
15    )
16    .fetch_one(&mut **tr)
17    .await
18    {
19        Ok(row) => row.get("version"),
20        Err(e) => {
21            info!(
22                "Error reading data lake schema version, assuming version 0: {}",
23                e
24            );
25            0
26        }
27    }
28}
29
30/// Warns when the connected database is behind [`LATEST_DATA_LAKE_SCHEMA_VERSION`].
31///
32/// `execute_migration` only runs from `telemetry-ingestion-srv`/`micromegas-monolith`; a
33/// `flight-sql-srv`/`analytics-web-srv` process reads the same database without ever migrating
34/// it. On a schema that already has the `audience_grants` table (v7+) but predates the v9 seed
35/// rows, `AudienceReadPolicy` resolves every audience to an empty grant set rather than erroring,
36/// so queries silently return zero rows -- this is the only signal an operator gets otherwise.
37pub async fn warn_if_data_lake_schema_stale(pool: &sqlx::Pool<sqlx::Postgres>) {
38    let version = match pool.begin().await {
39        Ok(mut tr) => read_data_lake_schema_version(&mut tr).await,
40        Err(e) => {
41            warn!("could not check data lake schema version: {e}");
42            return;
43        }
44    };
45    if version < 9 {
46        warn!(
47            "data lake schema is v{version}, behind the latest v{LATEST_DATA_LAKE_SCHEMA_VERSION}; \
48             the seeded 'public' audience_grants rows have not migrated in yet, so every query \
49             will resolve to an empty read scope and return zero rows until the schema is upgraded"
50        );
51    }
52    if version < 10 {
53        warn!(
54            "data lake schema is v{version}: the `groups`/`group_members` tables do not exist yet, \
55             so every request fails with a retryable 503 until the migration runs, because the \
56             group store cannot load"
57        );
58    }
59    if version < 12 {
60        warn!(
61            "data lake schema is v{version}: the `settings` table does not exist yet, so the \
62             settings store cannot load"
63        );
64    }
65}
66
67/// Upgrades the data lake schema to version 2.
68pub async fn upgrade_data_lake_schema_v2(
69    tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
70) -> Result<()> {
71    tr.execute("ALTER TABLE blocks ADD insert_time TIMESTAMPTZ;")
72        .await
73        .with_context(|| "adding column insert_time to blocks table")?;
74    tr.execute("UPDATE blocks SET insert_time=end_time WHERE insert_time is NULL;")
75        .await
76        .with_context(|| "use end_time as insert_time to backfill missing data")?;
77    tr.execute("CREATE INDEX block_begin_time on blocks(begin_time);")
78        .await
79        .with_context(|| "adding index block_begin_time")?;
80    tr.execute("CREATE INDEX block_end_time on blocks(end_time);")
81        .await
82        .with_context(|| "adding index block_end_time")?;
83    tr.execute("CREATE INDEX block_insert_time on blocks(insert_time);")
84        .await
85        .with_context(|| "adding index block_insert_time")?;
86    tr.execute("CREATE INDEX process_insert_time on processes(insert_time);")
87        .await
88        .with_context(|| "adding index process_insert_time")?;
89    tr.execute("UPDATE migration SET version=2;")
90        .await
91        .with_context(|| "Updating data lake schema version to 2")?;
92    Ok(())
93}
94
95/// Upgrades the data lake schema to version 3.
96/// Drops old non-unique indexes (superseded by the unique indexes created before this transaction).
97pub async fn upgrade_data_lake_schema_v3(
98    tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
99) -> Result<()> {
100    tr.execute("DROP INDEX IF EXISTS process_id;")
101        .await
102        .with_context(|| "dropping old non-unique index process_id")?;
103    tr.execute("DROP INDEX IF EXISTS stream_id;")
104        .await
105        .with_context(|| "dropping old non-unique index stream_id")?;
106    tr.execute("DROP INDEX IF EXISTS block_id;")
107        .await
108        .with_context(|| "dropping old non-unique index block_id")?;
109    tr.execute("UPDATE migration SET version=3;")
110        .await
111        .with_context(|| "updating data lake schema version to 3")?;
112    Ok(())
113}
114
115/// Upgrades the data lake schema to version 4.
116/// Adds the `format` column to `streams` so OTLP and native blocks can be distinguished.
117pub async fn upgrade_data_lake_schema_v4(
118    tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
119) -> Result<()> {
120    tr.execute("ALTER TABLE streams ADD COLUMN format TEXT NOT NULL DEFAULT 'micromegas-transit';")
121        .await
122        .with_context(|| "adding column format to streams table")?;
123    tr.execute("UPDATE migration SET version=4;")
124        .await
125        .with_context(|| "updating data lake schema version to 4")?;
126    Ok(())
127}
128
129/// Upgrades the data lake schema to version 5.
130/// Adds `ingestion_api_keys` and `analytics_api_keys`, the DB-backed API key store:
131/// a `key_id` UUID primary key (a non-secret handle for `DELETE`/`GET`,
132/// distinct from the `key_hash` lookup value), a SHA-256 `key_hash` with a unique
133/// index for O(1) validation lookups, and a `created_at`/`created_by`/`last_used_at`/
134/// `revoked_at`/`revoked_by` audit trail. The two tables are identical in shape but
135/// deliberately separate (never a shared `scopes` column) so an ingestion (write)
136/// key can never double as an analytics (read) credential.
137pub async fn upgrade_data_lake_schema_v5(
138    tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
139) -> Result<()> {
140    tr.execute(
141        "CREATE TABLE ingestion_api_keys (
142           key_id       UUID PRIMARY KEY,
143           key_hash     BYTEA NOT NULL,
144           name         VARCHAR(255) NOT NULL,
145           created_at   TIMESTAMPTZ NOT NULL,
146           created_by   VARCHAR(255) NOT NULL,
147           last_used_at TIMESTAMPTZ,
148           revoked_at   TIMESTAMPTZ,
149           revoked_by   VARCHAR(255)
150         );",
151    )
152    .await
153    .with_context(|| "creating table ingestion_api_keys")?;
154    tr.execute("CREATE UNIQUE INDEX ingestion_api_keys_key_hash ON ingestion_api_keys(key_hash);")
155        .await
156        .with_context(|| "creating unique index ingestion_api_keys_key_hash")?;
157    tr.execute(
158        "CREATE TABLE analytics_api_keys (
159           key_id       UUID PRIMARY KEY,
160           key_hash     BYTEA NOT NULL,
161           name         VARCHAR(255) NOT NULL,
162           created_at   TIMESTAMPTZ NOT NULL,
163           created_by   VARCHAR(255) NOT NULL,
164           last_used_at TIMESTAMPTZ,
165           revoked_at   TIMESTAMPTZ,
166           revoked_by   VARCHAR(255)
167         );",
168    )
169    .await
170    .with_context(|| "creating table analytics_api_keys")?;
171    tr.execute("CREATE UNIQUE INDEX analytics_api_keys_key_hash ON analytics_api_keys(key_hash);")
172        .await
173        .with_context(|| "creating unique index analytics_api_keys_key_hash")?;
174    tr.execute("UPDATE migration SET version=5;")
175        .await
176        .with_context(|| "updating data lake schema version to 5")?;
177    Ok(())
178}
179
180/// Upgrades the data lake schema to version 6.
181/// Adds the `audience` column to `ingestion_api_keys`: the write audience a key is
182/// immutably bound to. Backfilled to `'public'` before `SET NOT NULL` -- every pre-existing
183/// row predates audience stamping, and `public` is the accurate description of its current,
184/// unstamped-and-visible-to-everyone state, not a new grant. No `DEFAULT` on the column:
185/// that would let a not-yet-upgraded `analytics-web-srv` keep inserting rows that silently
186/// take `public`, defeating the column's fail-closed property. `analytics_api_keys` is
187/// untouched -- its read-side mirror is `read_audiences`, a set-valued grant in the opposite
188/// direction.
189pub async fn upgrade_data_lake_schema_v6(
190    tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
191) -> Result<()> {
192    tr.execute("ALTER TABLE ingestion_api_keys ADD COLUMN audience VARCHAR(255);")
193        .await
194        .with_context(|| "adding column audience to ingestion_api_keys table")?;
195    tr.execute("UPDATE ingestion_api_keys SET audience = 'public' WHERE audience IS NULL;")
196        .await
197        .with_context(|| "backfilling audience to 'public' on ingestion_api_keys")?;
198    tr.execute("ALTER TABLE ingestion_api_keys ALTER COLUMN audience SET NOT NULL;")
199        .await
200        .with_context(|| "setting audience NOT NULL on ingestion_api_keys")?;
201    tr.execute(
202        "ALTER TABLE ingestion_api_keys ADD CONSTRAINT ingestion_api_keys_audience_name \
203         CHECK (audience ~ '^[A-Za-z0-9_-]+$');",
204    )
205    .await
206    .with_context(|| "adding audience-name CHECK constraint on ingestion_api_keys")?;
207    tr.execute("UPDATE migration SET version=6;")
208        .await
209        .with_context(|| "updating data lake schema version to 6")?;
210    Ok(())
211}
212
213/// Upgrades the data lake schema to version 7.
214/// Adds `audience_grants`: the DB-backed audience grant store, a 1:1
215/// stand-in for the long-term model's `group_read_grants`/`group_mint_grants` tables. One table
216/// with an `axis` column (`'read'`/`'mint'`) rather than two, mirroring today's single env-var
217/// grant map (`{prefix}_AUDIENCE_GRANTS`); `(audience, axis, selector)` is the row's own natural
218/// key, so there is no surrogate `grant_id` the way `ingestion_api_keys.key_id` has one (a grant
219/// carries no secret to keep unlinkable from its own identity). No `revoked_at`/`revoked_by`
220/// either -- grants are hard-`DELETE`d, since a removed grant has no ongoing artifact whose
221/// provenance a caller might later need. The shape `CHECK` constraints declared here (audience
222/// name and axis) were dropped in v14: `AudienceGrants::from_rows` (`rust/auth/src/policy.rs`)
223/// validates in Rust and skips a malformed row, so a row inserted by any means other than the
224/// admin API (a manual `psql` fix, a future migration) is inert rather than a hazard.
225pub async fn upgrade_data_lake_schema_v7(
226    tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
227) -> Result<()> {
228    tr.execute(
229        "CREATE TABLE audience_grants (
230           audience   VARCHAR(255) NOT NULL,
231           axis       VARCHAR(4) NOT NULL CHECK (axis IN ('read', 'mint')),
232           selector   VARCHAR(255) NOT NULL,
233           created_at TIMESTAMPTZ NOT NULL,
234           created_by VARCHAR(255) NOT NULL,
235           PRIMARY KEY (audience, axis, selector),
236           CONSTRAINT audience_grants_audience_name CHECK (audience ~ '^[A-Za-z0-9_-]+$'),
237           CONSTRAINT audience_grants_selector_shape
238               CHECK (selector = '*' OR selector ~ '^(user|group):.+$')
239         );",
240    )
241    .await
242    .with_context(|| "creating table audience_grants")?;
243    tr.execute("UPDATE migration SET version=7;")
244        .await
245        .with_context(|| "updating data lake schema version to 7")?;
246    Ok(())
247}
248
249/// Upgrades the data lake schema to version 8.
250///
251/// Adds a nullable `audience` column to `processes`, `streams`, and `blocks`: the write audience
252/// the row was stamped with at insert time. No `DEFAULT` and no backfill -- a NULL column means
253/// the row predates this stage and resolves to the deployment's `MICROMEGAS_DEFAULT_AUDIENCE` at
254/// read time, exactly as an unstamped row does today.
255///
256/// The `CHECK` constraints are added `NOT VALID` so `ALTER TABLE` does not scan and lock every
257/// existing row on `blocks`, the largest table in the lake; the constraint only applies to rows
258/// written from this point on (`WriteAudience::new` already validates the charset in Rust).
259///
260/// No index: nothing queries Postgres by audience, so one would be pure write cost.
261///
262/// `sql_telemetry_db.rs`'s `create_tables` (the v1 shape) is not touched -- a fresh database
263/// walks every upgrade in turn, so adding the column there too would double-apply it.
264pub async fn upgrade_data_lake_schema_v8(
265    tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
266) -> Result<()> {
267    tr.execute("ALTER TABLE processes ADD COLUMN audience VARCHAR(255);")
268        .await
269        .with_context(|| "adding column audience to processes table")?;
270    tr.execute("ALTER TABLE streams ADD COLUMN audience VARCHAR(255);")
271        .await
272        .with_context(|| "adding column audience to streams table")?;
273    tr.execute("ALTER TABLE blocks ADD COLUMN audience VARCHAR(255);")
274        .await
275        .with_context(|| "adding column audience to blocks table")?;
276    tr.execute(
277        "ALTER TABLE processes ADD CONSTRAINT processes_audience_name \
278         CHECK (audience ~ '^[A-Za-z0-9_-]+$') NOT VALID;",
279    )
280    .await
281    .with_context(|| "adding audience-name CHECK constraint on processes")?;
282    tr.execute(
283        "ALTER TABLE streams ADD CONSTRAINT streams_audience_name \
284         CHECK (audience ~ '^[A-Za-z0-9_-]+$') NOT VALID;",
285    )
286    .await
287    .with_context(|| "adding audience-name CHECK constraint on streams")?;
288    tr.execute(
289        "ALTER TABLE blocks ADD CONSTRAINT blocks_audience_name \
290         CHECK (audience ~ '^[A-Za-z0-9_-]+$') NOT VALID;",
291    )
292    .await
293    .with_context(|| "adding audience-name CHECK constraint on blocks")?;
294    tr.execute("UPDATE migration SET version=8;")
295        .await
296        .with_context(|| "updating data lake schema version to 8")?;
297    Ok(())
298}
299
300/// Upgrades the data lake schema to version 9.
301///
302/// Seeds `('public', 'read', '*')` and `('public', 'mint', '*')` into `audience_grants`. The
303/// read row replaces the built-in `PUBLIC_AUDIENCE` arm removed from `AudienceReadPolicy::resolve`;
304/// the mint row is what lets a non-admin mint a key bound to `public` without an operator having
305/// to discover and create the row by hand. `ON CONFLICT DO NOTHING` because an operator may
306/// already have created either row before upgrading -- this must not fail the migration.
307pub async fn upgrade_data_lake_schema_v9(
308    tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
309) -> Result<()> {
310    tr.execute(
311        "INSERT INTO audience_grants (audience, axis, selector, created_at, created_by)
312         VALUES ('public', 'read', '*', now(), 'default'),
313                ('public', 'mint', '*', now(), 'default')
314         ON CONFLICT DO NOTHING;",
315    )
316    .await
317    .with_context(|| "seeding public read/mint grants")?;
318    tr.execute("UPDATE migration SET version=9;")
319        .await
320        .with_context(|| "updating data lake schema version to 9")?;
321    Ok(())
322}
323
324/// `true` if `name` matches the `groups.name`/`group_members.group_name` charset:
325/// `[A-Za-z0-9_-]{1,255}`. A local copy rather than a dependency on `micromegas-auth` (which this
326/// crate does not otherwise depend on).
327fn is_valid_group_name(name: &str) -> bool {
328    !name.is_empty()
329        && name.len() <= 255
330        && name
331            .bytes()
332            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
333}
334
335/// Upgrades the data lake schema to version 10.
336///
337/// Adds `groups` and `group_members`, the local-group-membership store: a `group_members.member`
338/// row is a selector in exactly the vocabulary `audience_grants.selector` uses (`*`,
339/// `user:<email>`, `group:<name>`), so nesting is the `group:` arm of the same predicate rather
340/// than a special case. Seeds the reserved `admins` group with a single wildcard member
341/// (`('admins', '*')`) on every upgrade, fresh install or not; the operator is expected to add
342/// `user:<their email>` to `admins` and then remove the wildcard row afterward, via the Groups
343/// page or `micromegas-groups`. Also backfills an empty group for every distinct `group:X`
344/// selector already present in `audience_grants` so a legacy claim-derived grant is not left
345/// dangling at an unknown name.
346pub async fn upgrade_data_lake_schema_v10(
347    tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
348) -> Result<()> {
349    tr.execute(
350        "CREATE TABLE groups (
351           name        VARCHAR(255) PRIMARY KEY,
352           description TEXT,
353           created_at  TIMESTAMPTZ NOT NULL,
354           created_by  VARCHAR(255) NOT NULL,
355           CONSTRAINT groups_name CHECK (name ~ '^[A-Za-z0-9_-]+$')
356         );",
357    )
358    .await
359    .with_context(|| "creating table groups")?;
360    tr.execute(
361        "CREATE TABLE group_members (
362           group_name  VARCHAR(255) NOT NULL REFERENCES groups(name) ON DELETE CASCADE,
363           member      VARCHAR(255) NOT NULL,
364           created_at  TIMESTAMPTZ NOT NULL,
365           created_by  VARCHAR(255) NOT NULL,
366           PRIMARY KEY (group_name, member),
367           CONSTRAINT group_members_selector_shape CHECK (member = '*' OR member ~ '^(user|group):.+$')
368         );",
369    )
370    .await
371    .with_context(|| "creating table group_members")?;
372
373    tr.execute(
374        "INSERT INTO groups (name, description, created_at, created_by)
375         VALUES ('admins', 'Deployment administrators', now(), 'default')
376         ON CONFLICT (name) DO NOTHING;",
377    )
378    .await
379    .with_context(|| "seeding the admins group")?;
380
381    tr.execute(
382        "INSERT INTO group_members (group_name, member, created_at, created_by)
383         VALUES ('admins', '*', now(), 'default')
384         ON CONFLICT (group_name, member) DO NOTHING;",
385    )
386    .await
387    .with_context(|| "seeding the admins group with the wildcard member")?;
388
389    let rows =
390        sqlx::query("SELECT DISTINCT selector FROM audience_grants WHERE selector LIKE 'group:%';")
391            .fetch_all(&mut **tr)
392            .await
393            .with_context(|| "querying distinct group: selectors from audience_grants")?;
394    for row in rows {
395        let selector: String = row.try_get("selector").context("reading selector")?;
396        let name = selector
397            .strip_prefix("group:")
398            .expect("selector matched the LIKE 'group:%' filter");
399        if !is_valid_group_name(name) {
400            warn!(
401                "legacy audience_grants selector group:{name:?} does not match the group name \
402                 charset [A-Za-z0-9_-]{{1,255}}; left as an inert grant row, not backfilled into \
403                 a group"
404            );
405            continue;
406        }
407        sqlx::query(
408            "INSERT INTO groups (name, description, created_at, created_by)
409             VALUES ($1, NULL, now(), 'migration')
410             ON CONFLICT (name) DO NOTHING;",
411        )
412        .bind(name)
413        .execute(&mut **tr)
414        .await
415        .with_context(|| format!("backfilling empty group {name:?} from a legacy grant"))?;
416        info!("backfilled empty group {name:?} from a legacy audience_grants selector");
417    }
418
419    tr.execute("UPDATE migration SET version=10;")
420        .await
421        .with_context(|| "updating data lake schema version to 10")?;
422    Ok(())
423}
424
425/// Upgrades the data lake schema to version 11.
426/// Adds a nullable `allowed_cidrs TEXT[]` column to both `ingestion_api_keys` and
427/// `analytics_api_keys`: the CIDR ranges/bare IPs a key may be presented from. No backfill
428/// needed (unlike `audience`, which had to become `NOT NULL`): `NULL`/absent means "no
429/// restriction", which is exactly the correct value for every pre-existing row.
430pub async fn upgrade_data_lake_schema_v11(
431    tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
432) -> Result<()> {
433    tr.execute("ALTER TABLE ingestion_api_keys ADD COLUMN allowed_cidrs TEXT[];")
434        .await
435        .with_context(|| "adding column allowed_cidrs to ingestion_api_keys table")?;
436    tr.execute("ALTER TABLE analytics_api_keys ADD COLUMN allowed_cidrs TEXT[];")
437        .await
438        .with_context(|| "adding column allowed_cidrs to analytics_api_keys table")?;
439    tr.execute("UPDATE migration SET version=11;")
440        .await
441        .with_context(|| "updating data lake schema version to 11")?;
442    Ok(())
443}
444
445/// Upgrades the data lake schema to version 12.
446/// Adds `settings`, a generic key/value table of deployment-wide settings that each service
447/// caches; a key with no row means "unset" and falls back to the env var or built-in default.
448pub async fn upgrade_data_lake_schema_v12(
449    tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
450) -> Result<()> {
451    tr.execute(
452        "CREATE TABLE settings (
453            key        VARCHAR(255) PRIMARY KEY,
454            value      JSONB        NOT NULL,
455            updated_at TIMESTAMPTZ  NOT NULL,
456            updated_by VARCHAR(255) NOT NULL
457        );",
458    )
459    .await
460    .with_context(|| "creating settings table")?;
461    tr.execute("UPDATE migration SET version=12;")
462        .await
463        .with_context(|| "updating data lake schema version to 12")?;
464    Ok(())
465}
466
467/// Upgrades the data lake schema to version 13.
468/// Drops the selector-shape CHECKs on `audience_grants` and `group_members`: the selector
469/// vocabulary (`valid_selector`) now grows without a migration each time, and shape is validated
470/// in code only.
471pub async fn upgrade_data_lake_schema_v13(
472    tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
473) -> Result<()> {
474    tr.execute(
475        "ALTER TABLE audience_grants DROP CONSTRAINT IF EXISTS audience_grants_selector_shape;",
476    )
477    .await
478    .with_context(|| "dropping audience_grants_selector_shape")?;
479    tr.execute("ALTER TABLE group_members DROP CONSTRAINT IF EXISTS group_members_selector_shape;")
480        .await
481        .with_context(|| "dropping group_members_selector_shape")?;
482    tr.execute("UPDATE migration SET version=13;")
483        .await
484        .with_context(|| "updating data lake schema version to 13")?;
485    Ok(())
486}
487
488/// Upgrades the data lake schema to version 14.
489/// Drops the last grant/group shape CHECKs: `audience_grants_audience_name` (a grant audience may
490/// now be `*`), the `audience_grants` axis CHECK (declared inline in v7, so Postgres auto-named
491/// it `audience_grants_axis_check`), and `groups_name`. Grant and group vocabulary is validated in
492/// code only; a malformed row written by direct SQL is skipped by the snapshot loaders.
493pub async fn upgrade_data_lake_schema_v14(
494    tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
495) -> Result<()> {
496    tr.execute(
497        "ALTER TABLE audience_grants DROP CONSTRAINT IF EXISTS audience_grants_audience_name;",
498    )
499    .await
500    .with_context(|| "dropping audience_grants_audience_name")?;
501    tr.execute("ALTER TABLE audience_grants DROP CONSTRAINT IF EXISTS audience_grants_axis_check;")
502        .await
503        .with_context(|| "dropping audience_grants_axis_check")?;
504    tr.execute("ALTER TABLE groups DROP CONSTRAINT IF EXISTS groups_name;")
505        .await
506        .with_context(|| "dropping groups_name")?;
507    tr.execute("UPDATE migration SET version=14;")
508        .await
509        .with_context(|| "updating data lake schema version to 14")?;
510    Ok(())
511}
512
513/// Checks whether a specific index is valid in `pg_index`.
514/// If the index is invalid, drops it and returns `Ok(false)`.
515/// If valid, returns `Ok(true)`.
516/// Returns an error if the index does not exist.
517async fn check_index_is_valid(pool: &sqlx::Pool<sqlx::Postgres>, index_name: &str) -> Result<bool> {
518    let row = sqlx::query(
519        "SELECT i.indisvalid
520         FROM pg_class c
521         JOIN pg_index i ON i.indexrelid = c.oid
522         WHERE c.relname = $1;",
523    )
524    .bind(index_name)
525    .fetch_optional(pool)
526    .await
527    .with_context(|| format!("querying pg_index for {index_name}"))?;
528
529    let row = row.with_context(|| format!("index {index_name} not found in pg_class"))?;
530    let is_valid: bool = row.get("indisvalid");
531
532    if !is_valid {
533        info!("index {index_name} is INVALID, dropping it");
534        sqlx::query(&format!("DROP INDEX IF EXISTS {index_name}"))
535            .execute(pool)
536            .await
537            .with_context(|| format!("dropping invalid index {index_name}"))?;
538        return Ok(false);
539    }
540
541    Ok(true)
542}
543
544/// Validates that all three unique indexes created during the v2→v3 migration are valid.
545/// Drops any invalid indexes and returns an error so the migration can be retried.
546async fn validate_unique_indexes(pool: &sqlx::Pool<sqlx::Postgres>) -> Result<()> {
547    let index_names = [
548        "processes_process_id_unique",
549        "streams_stream_id_unique",
550        "blocks_block_id_unique",
551    ];
552
553    let mut invalid_indexes = Vec::new();
554    for name in &index_names {
555        if !check_index_is_valid(pool, name).await? {
556            invalid_indexes.push(*name);
557        }
558    }
559
560    if !invalid_indexes.is_empty() {
561        anyhow::bail!(
562            "invalid indexes detected and dropped: {}. The migration will be retried on next startup.",
563            invalid_indexes.join(", ")
564        );
565    }
566
567    Ok(())
568}
569
570/// Executes the database migration.
571pub async fn execute_migration(pool: sqlx::Pool<sqlx::Postgres>) -> Result<()> {
572    let mut current_version = read_data_lake_schema_version(&mut pool.begin().await?).await;
573    if 0 == current_version {
574        info!("creating v1 data_lake_schema");
575        let mut tr = pool.begin().await?;
576        create_tables(&mut tr).await?;
577        current_version = read_data_lake_schema_version(&mut tr).await;
578        tr.commit().await?;
579    }
580    if 1 == current_version {
581        info!("upgrading data_lake_schema to v2");
582        let mut tr = pool.begin().await?;
583        upgrade_data_lake_schema_v2(&mut tr).await?;
584        current_version = read_data_lake_schema_version(&mut tr).await;
585        tr.commit().await?;
586    }
587    if 2 == current_version {
588        info!("upgrading data_lake_schema to v3");
589        // CREATE UNIQUE INDEX CONCURRENTLY cannot run inside a transaction.
590        // Run these outside any transaction, then do the rest in a transaction.
591        // IF NOT EXISTS makes this idempotent and safe for retries.
592        sqlx::query("CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS processes_process_id_unique ON processes(process_id);")
593            .execute(&pool)
594            .await
595            .with_context(|| "creating unique index on processes(process_id)")?;
596        sqlx::query("CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS streams_stream_id_unique ON streams(stream_id);")
597            .execute(&pool)
598            .await
599            .with_context(|| "creating unique index on streams(stream_id)")?;
600        sqlx::query("CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS blocks_block_id_unique ON blocks(block_id);")
601            .execute(&pool)
602            .await
603            .with_context(|| "creating unique index on blocks(block_id)")?;
604
605        validate_unique_indexes(&pool).await?;
606
607        let mut tr = pool.begin().await?;
608        upgrade_data_lake_schema_v3(&mut tr).await?;
609        current_version = read_data_lake_schema_version(&mut tr).await;
610        tr.commit().await?;
611    }
612    if 3 == current_version {
613        info!("upgrading data_lake_schema to v4");
614        let mut tr = pool.begin().await?;
615        upgrade_data_lake_schema_v4(&mut tr).await?;
616        current_version = read_data_lake_schema_version(&mut tr).await;
617        tr.commit().await?;
618    }
619    if 4 == current_version {
620        info!("upgrading data_lake_schema to v5");
621        let mut tr = pool.begin().await?;
622        upgrade_data_lake_schema_v5(&mut tr).await?;
623        current_version = read_data_lake_schema_version(&mut tr).await;
624        tr.commit().await?;
625    }
626    if 5 == current_version {
627        info!("upgrading data_lake_schema to v6");
628        let mut tr = pool.begin().await?;
629        upgrade_data_lake_schema_v6(&mut tr).await?;
630        current_version = read_data_lake_schema_version(&mut tr).await;
631        tr.commit().await?;
632    }
633    if 6 == current_version {
634        info!("upgrading data_lake_schema to v7");
635        let mut tr = pool.begin().await?;
636        upgrade_data_lake_schema_v7(&mut tr).await?;
637        current_version = read_data_lake_schema_version(&mut tr).await;
638        tr.commit().await?;
639    }
640    if 7 == current_version {
641        info!("upgrading data_lake_schema to v8");
642        let mut tr = pool.begin().await?;
643        upgrade_data_lake_schema_v8(&mut tr).await?;
644        current_version = read_data_lake_schema_version(&mut tr).await;
645        tr.commit().await?;
646    }
647    if 8 == current_version {
648        info!("upgrading data_lake_schema to v9");
649        let mut tr = pool.begin().await?;
650        upgrade_data_lake_schema_v9(&mut tr).await?;
651        current_version = read_data_lake_schema_version(&mut tr).await;
652        tr.commit().await?;
653    }
654    if 9 == current_version {
655        info!("upgrading data_lake_schema to v10");
656        let mut tr = pool.begin().await?;
657        upgrade_data_lake_schema_v10(&mut tr).await?;
658        current_version = read_data_lake_schema_version(&mut tr).await;
659        tr.commit().await?;
660    }
661    if 10 == current_version {
662        info!("upgrading data_lake_schema to v11");
663        let mut tr = pool.begin().await?;
664        upgrade_data_lake_schema_v11(&mut tr).await?;
665        current_version = read_data_lake_schema_version(&mut tr).await;
666        tr.commit().await?;
667    }
668    if 11 == current_version {
669        info!("upgrading data_lake_schema to v12");
670        let mut tr = pool.begin().await?;
671        upgrade_data_lake_schema_v12(&mut tr).await?;
672        current_version = read_data_lake_schema_version(&mut tr).await;
673        tr.commit().await?;
674    }
675    if 12 == current_version {
676        info!("upgrading data_lake_schema to v13");
677        let mut tr = pool.begin().await?;
678        upgrade_data_lake_schema_v13(&mut tr).await?;
679        current_version = read_data_lake_schema_version(&mut tr).await;
680        tr.commit().await?;
681    }
682    if 13 == current_version {
683        info!("upgrading data_lake_schema to v14");
684        let mut tr = pool.begin().await?;
685        upgrade_data_lake_schema_v14(&mut tr).await?;
686        current_version = read_data_lake_schema_version(&mut tr).await;
687        tr.commit().await?;
688    }
689    assert_eq!(current_version, LATEST_DATA_LAKE_SCHEMA_VERSION);
690    Ok(())
691}