diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index cff8a268126..1bc8a1ff227 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -879,7 +879,7 @@ mod postgres_tests { let mut migrations: Vec<_> = MIGRATOR.iter().collect(); migrations.sort_by_key(|migration| migration.version); - assert_eq!(migrations.len(), 97); + assert_eq!(migrations.len(), 100); assert_eq!(migrations[89].version, 90); assert!(migrations[89] .sql @@ -924,6 +924,20 @@ mod postgres_tests { .sql .as_str() .contains("SET LOCAL lock_timeout = '5s'")); + // 0098-0100 undo 0097's community artifact expand without a table + // scan under ACCESS EXCLUSIVE. + assert_eq!(migrations[97].version, 98); + assert!(strip_sql_comments(migrations[97].sql.as_str()) + .contains("CHECK (channel_id IS NOT NULL) NOT VALID;")); + assert_eq!(migrations[98].version, 99); + assert!(strip_sql_comments(migrations[98].sql.as_str()) + .contains("VALIDATE CONSTRAINT artifact_heads_channel_id_not_null;")); + assert_eq!(migrations[99].version, 100); + let unexpand = strip_sql_comments(migrations[99].sql.as_str()); + assert!( + unexpand.contains("ALTER TABLE artifact_heads ALTER COLUMN channel_id SET NOT NULL;") + ); + assert!(unexpand.contains("ALTER TABLE communities DROP COLUMN artifact_type_policies;")); assert!(migrations[79] .sql .as_str() @@ -3530,6 +3544,7 @@ mod postgres_tests { .execute(&pool) .await .expect("insert community"); + let channel_id = uuid::Uuid::new_v4(); let artifact_id = uuid::Uuid::new_v4(); sqlx::query( "INSERT INTO artifact_revisions (community_id, event_id, artifact_id) \ @@ -3549,7 +3564,7 @@ mod postgres_tests { .bind(community_id) .bind(artifact_id) .bind(vec![1_u8; 32]) - .bind(uuid::Uuid::new_v4()) + .bind(channel_id) .execute(&pool) .await .expect("insert artifact head"); @@ -3630,6 +3645,29 @@ mod postgres_tests { .await .expect("populated small database auto-migrates"); assert_boots_through_every_migration(&pool).await; + // 0097 relaxed channel_id and 0098-0100 restore NOT NULL; the channel + // head and revision written before both must survive unchanged. + let head: (uuid::Uuid, Vec) = sqlx::query_as( + "SELECT channel_id, event_id FROM artifact_heads \ + WHERE community_id = $1 AND artifact_id = $2", + ) + .bind(community_id) + .bind(artifact_id) + .fetch_one(&pool) + .await + .expect("read surviving artifact head"); + assert_eq!(head, (channel_id, vec![1_u8; 32])); + let revisions: i64 = sqlx::query_scalar( + "SELECT count(*) FROM artifact_revisions \ + WHERE community_id = $1 AND event_id = $2 AND artifact_id = $3", + ) + .bind(community_id) + .bind(vec![1_u8; 32]) + .bind(artifact_id) + .fetch_one(&pool) + .await + .expect("read surviving artifact revision"); + assert_eq!(revisions, 1, "0097-0100 keep channel artifact revisions"); assert_eq!( valid_indexes( &pool, @@ -3646,6 +3684,93 @@ mod postgres_tests { ); } + /// 0099 validates the channel check while channel artifact writes + /// continue: an open writer on `artifact_heads` must not block it. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn artifact_unexpand_validates_while_channel_heads_are_written() { + let pool = connect_test_pool().await; + reset_public_schema(&pool).await; + run_migrations_through(&pool, 98) + .await + .expect("apply migrations 1-98"); + let community_id = uuid::Uuid::new_v4(); + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(community_id) + .bind(format!("unexpand-{}.example", community_id.simple())) + .execute(&pool) + .await + .expect("insert community"); + + let mut writer = pool.begin().await.expect("begin channel head writer"); + sqlx::query( + "INSERT INTO artifact_heads \ + (community_id, artifact_id, event_id, channel_id, artifact_type) \ + VALUES ($1, $2, $3, $4, 'doc')", + ) + .bind(community_id) + .bind(uuid::Uuid::new_v4()) + .bind(vec![2_u8; 32]) + .bind(uuid::Uuid::new_v4()) + .execute(&mut *writer) + .await + .expect("write a channel head"); + run_migrations_through(&pool, 99) + .await + .expect("0099 validates beside an open channel head writer"); + writer.commit().await.expect("commit channel head"); + + run_migrations(&pool) + .await + .expect("apply the remaining migrations"); + assert_boots_through_every_migration(&pool).await; + let heads: i64 = + sqlx::query_scalar("SELECT count(*) FROM artifact_heads WHERE community_id = $1") + .bind(community_id) + .fetch_one(&pool) + .await + .expect("count channel heads"); + assert_eq!(heads, 1); + } + + /// 0098 refuses a database whose artifact head key is the scoped key from + /// the removed operator contract, before any cleanup runs. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn artifact_unexpand_refuses_scoped_head_key() { + let pool = connect_test_pool().await; + reset_public_schema(&pool).await; + run_migrations_through(&pool, 97) + .await + .expect("apply migrations 1-97"); + sqlx::query( + "ALTER TABLE artifact_heads DROP CONSTRAINT artifact_heads_pkey, \ + ADD CONSTRAINT artifact_heads_pkey PRIMARY KEY USING INDEX artifact_heads_scoped_identity", + ) + .execute(&pool) + .await + .expect("attach the scoped key as the contract script did"); + + let refused = run_migrations(&pool) + .await + .expect_err("0098 must refuse the scoped key") + .to_string(); + assert!( + refused.contains("artifact_heads primary key is not (community_id, artifact_id)"), + "unexpected error: {refused}" + ); + assert_eq!(applied_versions(&pool).await.last().copied(), Some(97)); + let scope_columns: i64 = sqlx::query_scalar( + "SELECT count(*) FROM information_schema.columns \ + WHERE table_schema = 'public' AND table_name = 'artifact_heads' \ + AND column_name = 'scope'", + ) + .fetch_one(&pool) + .await + .expect("read artifact_heads columns"); + assert_eq!(scope_columns, 1, "cleanup must not run"); + } + /// Migration 0081 refuses a populated `nip_fi_profile_heads`. A relay that /// has published NIP-FI verified profiles must still boot through every /// migration. diff --git a/deploy/charts/buzz/README.md b/deploy/charts/buzz/README.md index cc165e2480f..eefbf96417b 100644 --- a/deploy/charts/buzz/README.md +++ b/deploy/charts/buzz/README.md @@ -635,6 +635,8 @@ Schema migrations are embedded in the relay binary via `sqlx::migrate!` and run **Required stop before migrations 0089–0091, 0095 and 0096.** These migrations drop database triggers whose work the relay now does in application code. Before you upgrade to a build that contains any of them, every relay pod, job and rollback target must run a stop build. An older relay that keeps serving after they run can write data the dropped triggers used to refuse, and some older builds refuse to start without the 0032 roster trigger or the community tombstone trigger. [`docs/trigger-retirement-deployment.md`](../../../docs/trigger-retirement-deployment.md) names the stop build and gives the procedure and rollback. +**Required stop before migration 0100.** Migrations 0098–0100 undo migration 0097, and 0100 drops the columns and indexes that 0097 added. No tagged relay release reads them. Only rolling images built from commit `eebf62b6` (#9650) up to, but not including, `a4061916` (#9689) do. Their channel artifact reads and writes fail once 0100 runs. If any relay pod, job or rollback target runs one of those images, move all of them to `sha-a406191` or later before you upgrade. To roll back after 0100 has run, set `migrate.autoMigrate=false` first, because an older binary with auto-migration on refuses a database that has migrations it does not know. Then roll back to `sha-a406191` or later, never to an image in that range. Migration 0098 refuses a database whose `artifact_heads` primary key is not `(community_id, artifact_id)`. Recover such a database as #9689 describes before upgrading. + Apply migrations before rolling the relay; for large installations, prefer a controlled `buzz-admin migrate` job with PostgreSQL lock monitoring before the code rollout. If you prefer decoupling migrations from serving, set `migrate.autoMigrate=false`. **In that mode the chart does not run migrations for you** — you own running `buzz-admin migrate` (separate Pod / one-shot Job) against the database before every `helm install` / `helm upgrade`. Readiness probes only verify DB connectivity, not schema freshness, so a pod will appear healthy against an unmigrated schema and fail under load. A pre-upgrade Helm Job for this is on the chart roadmap; the values knob `migrate.preUpgradeJob.enabled` is reserved. diff --git a/migrations/0098_community_artifact_unexpand_check.sql b/migrations/0098_community_artifact_unexpand_check.sql new file mode 100644 index 00000000000..07a81817d08 --- /dev/null +++ b/migrations/0098_community_artifact_unexpand_check.sql @@ -0,0 +1,34 @@ +-- Undo 0097 (community artifact expand), step 1 of 3. The community-scoped +-- artifact feature that needed 0097 was reverted (#9689), and no release after +-- the revert reads or writes the columns 0097 added. 0097 stays in place +-- because databases that auto-migrated have recorded its checksum. +-- +-- Required stop: every relay pod and job must run #9689 or a later release +-- before 0100 runs. Relays built from #9650 itself read artifact_heads.scope +-- and write with ON CONFLICT on artifact_heads_scoped_identity. +-- +-- This step fails closed on a database whose artifact head key is not the +-- channel key. Only a database that ran the removed operator contract script, +-- or was bootstrapped from #9650's declared schema, has the scoped key. Such a +-- database needs the separate recovery step in #9689 first. +-- +-- Then it starts restoring NOT NULL on artifact_heads.channel_id without a +-- table scan under ACCESS EXCLUSIVE: 0099 validates this check, and 0100 sets +-- NOT NULL from it. +SET LOCAL lock_timeout = '5s'; +SET LOCAL statement_timeout = '30s'; + +DO $$ +BEGIN + IF (SELECT array_agg(a.attname::text ORDER BY k.ordinality) + FROM pg_constraint c + CROSS JOIN LATERAL unnest(c.conkey) WITH ORDINALITY AS k(attnum, ordinality) + JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = k.attnum + WHERE c.conrelid = 'artifact_heads'::regclass AND c.contype = 'p') + IS DISTINCT FROM ARRAY['community_id', 'artifact_id'] THEN + RAISE EXCEPTION 'artifact_heads primary key is not (community_id, artifact_id); recover this database as described in #9689 before migrating'; + END IF; +END $$; + +ALTER TABLE artifact_heads + ADD CONSTRAINT artifact_heads_channel_id_not_null CHECK (channel_id IS NOT NULL) NOT VALID; diff --git a/migrations/0099_community_artifact_unexpand_validate.sql b/migrations/0099_community_artifact_unexpand_validate.sql new file mode 100644 index 00000000000..8b51e492631 --- /dev/null +++ b/migrations/0099_community_artifact_unexpand_validate.sql @@ -0,0 +1,7 @@ +-- Undo 0097, step 2 of 3. Validate separately from the write-blocking DDL: +-- VALIDATE CONSTRAINT scans artifact_heads under SHARE UPDATE EXCLUSIVE, so +-- channel artifact reads and writes continue while it runs. +SET LOCAL lock_timeout = '5s'; +SET LOCAL statement_timeout = '30s'; + +ALTER TABLE artifact_heads VALIDATE CONSTRAINT artifact_heads_channel_id_not_null; diff --git a/migrations/0100_community_artifact_unexpand.sql b/migrations/0100_community_artifact_unexpand.sql new file mode 100644 index 00000000000..61941866af3 --- /dev/null +++ b/migrations/0100_community_artifact_unexpand.sql @@ -0,0 +1,23 @@ +-- Undo 0097, step 3 of 3. Requires every relay pod and job to run #9689 or a +-- later release (see 0098). +-- +-- SET NOT NULL uses the check validated in 0099 and skips the table scan. The +-- drops are catalog-only. Each statement takes ACCESS EXCLUSIVE on its table; +-- fail the deployment rather than queue relay reads and writes behind a long +-- holder. +SET LOCAL lock_timeout = '5s'; +SET LOCAL statement_timeout = '30s'; + +ALTER TABLE artifact_heads ALTER COLUMN channel_id SET NOT NULL; +ALTER TABLE artifact_heads DROP CONSTRAINT artifact_heads_channel_id_not_null; + +DROP INDEX artifact_heads_live_type; +DROP INDEX artifact_heads_scoped_identity; +DROP INDEX artifact_revisions_scoped_identity; + +ALTER TABLE artifact_heads DROP COLUMN scope; +ALTER TABLE artifact_revisions + DROP COLUMN scope, + DROP COLUMN community_event, + DROP COLUMN redacted; +ALTER TABLE communities DROP COLUMN artifact_type_policies; diff --git a/schema/tables/public/artifact_heads.sql b/schema/tables/public/artifact_heads.sql index a442cb54b17..7e73557b9b6 100644 --- a/schema/tables/public/artifact_heads.sql +++ b/schema/tables/public/artifact_heads.sql @@ -2,17 +2,14 @@ CREATE TABLE artifact_heads ( community_id UUID NOT NULL REFERENCES communities(id), artifact_id UUID NOT NULL, - scope TEXT NOT NULL DEFAULT 'channel', event_id BYTEA NOT NULL CHECK (length(event_id) = 32), - channel_id UUID, + channel_id UUID NOT NULL, artifact_type TEXT NOT NULL, root BYTEA, deleted BOOLEAN NOT NULL DEFAULT false, modified_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), PRIMARY KEY (community_id, artifact_id) ); -CREATE UNIQUE INDEX artifact_heads_scoped_identity - ON artifact_heads (community_id, scope, artifact_id); CREATE INDEX artifact_heads_event ON artifact_heads (community_id, event_id); CREATE INDEX artifact_heads_modified ON artifact_heads (community_id, modified_at, artifact_id); CREATE INDEX artifact_heads_channel ON artifact_heads (community_id, channel_id, artifact_id); @@ -20,6 +17,3 @@ CREATE INDEX artifact_heads_channel ON artifact_heads (community_id, channel_id, -- The relay does not expire events. Any future row retention or partition -- retirement must skip payloads referenced by `artifact_heads.event_id` -- (NIP-AR: expiring earlier revisions MUST NOT remove the current revision). - -CREATE INDEX artifact_heads_live_type - ON artifact_heads (community_id, scope, artifact_type, artifact_id) WHERE NOT deleted; diff --git a/schema/tables/public/artifact_revisions.sql b/schema/tables/public/artifact_revisions.sql index 285d4cd9247..d3320c0bfff 100644 --- a/schema/tables/public/artifact_revisions.sql +++ b/schema/tables/public/artifact_revisions.sql @@ -4,9 +4,6 @@ CREATE TABLE artifact_revisions ( community_id UUID NOT NULL REFERENCES communities(id), event_id BYTEA NOT NULL CHECK (length(event_id) = 32), artifact_id UUID NOT NULL, - scope TEXT NOT NULL DEFAULT 'channel', - community_event JSONB, - redacted BOOLEAN NOT NULL DEFAULT false, source_channel_id UUID, modified_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), PRIMARY KEY (community_id, event_id) @@ -16,5 +13,3 @@ CREATE INDEX idx_artifact_revisions_artifact ON artifact_revisions (community_id, artifact_id); CREATE INDEX artifact_revisions_moves ON artifact_revisions (community_id, modified_at, event_id) WHERE source_channel_id IS NOT NULL; - -CREATE INDEX artifact_revisions_scoped_identity ON artifact_revisions (community_id, scope, artifact_id); diff --git a/schema/tables/public/communities.sql b/schema/tables/public/communities.sql index 42b220b189a..4c328109f69 100644 --- a/schema/tables/public/communities.sql +++ b/schema/tables/public/communities.sql @@ -26,7 +26,6 @@ CREATE TABLE communities ( deletion_state TEXT NOT NULL DEFAULT 'active' CHECK (deletion_state IN ('active', 'quiescing', 'fenced', 'tombstone')), deletion_fence_generation BIGINT NOT NULL DEFAULT 0 CHECK (deletion_fence_generation >= 0), deleted_at TIMESTAMPTZ, - artifact_type_policies JSONB NOT NULL DEFAULT '{}', artifact_policy_modified_at TIMESTAMPTZ NOT NULL DEFAULT 'epoch', CONSTRAINT chk_communities_id_not_nil CHECK (id <> '00000000-0000-0000-0000-000000000000'::uuid) );