feat(import): complete OpenAPI onboarding and verify delivery
CI / Rust Checks (pull_request) Failing after 1s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped

This commit is contained in:
bsodfather committed 2026-10-09 17:50:38 +03:00
1 parent bb3e376767
commit e93de7015a
244 files changed
+57020 -5139

No files matched your search

@@ -4,7 +4,9 @@ use super::approval_side_effects_v10;
use super::artifact_cleanup_indexes_v13;
use super::artifact_metadata_v12;
use super::execution_outcome_v5;
use super::import_plan_v14;
use super::master_key_identity_v7;
use super::onboarding_import_selection_v15;
use super::onboarding_product_events_v11;
use super::owned_relations;
use super::platform_key_name_reuse_v6;
@@ -25,8 +27,8 @@ mod contract;
use contract::baseline_source_digest;
use contract::validate_descriptors;
const MIGRATION_LOCK_ID: i64 = 0x4352_414E_4B4D_4947;
const CURRENT_VERSION: i64 = 13;
const IMPLEMENTED_VERSIONS: &[i64] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
const CURRENT_VERSION: i64 = 15;
const IMPLEMENTED_VERSIONS: &[i64] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const BASELINE_SOURCE_SHA256: &str =
"eb1656fc5b4b5be9ee390d237d1d58e4b2274ae5ba9b7ba06a2f3f860dfda675";
const CONSOLIDATION_SOURCE: &str = include_str!("consolidation_v2.sql");
@@ -264,6 +266,13 @@ impl MigrationAuthority {
artifact_cleanup_indexes_v13::SOURCE_SHA256,
12,
),
expand_descriptor(14, "import-plan-v14", import_plan_v14::SOURCE_SHA256, 13),
expand_descriptor(
15,
"onboarding-import-selection-v15",
onboarding_import_selection_v15::SOURCE_SHA256,
14,
),
]
}
pub fn validate_sequence() -> Result<(), MigrationError> {
@@ -392,6 +401,12 @@ impl MigrationAuthority {
if from < 13 {
artifact_cleanup_indexes_v13::apply(&mut transaction, &Self::sequence()[12]).await?;
}
if from < 14 {
import_plan_v14::apply(&mut transaction, &Self::sequence()[13]).await?;
}
if from < 15 {
onboarding_import_selection_v15::apply(&mut transaction, &Self::sequence()[14]).await?;
}
match inspect(&mut transaction).await? {
MigrationPreflight::Current {
version: CURRENT_VERSION,
@@ -558,6 +573,14 @@ async fn inspect(connection: &mut PgConnection) -> Result<MigrationPreflight, Mi
CURRENT_VERSION,
)
.await?;
validate_required_relations(connection, owned_relations::IMPORT_PLAN, CURRENT_VERSION)
.await?;
validate_required_relations(
connection,
owned_relations::ONBOARDING_IMPORT_SELECTION,
CURRENT_VERSION,
)
.await?;
validate_schema_fingerprint(connection, CURRENT_VERSION).await?;
validate_legacy_audit(connection).await?;
Ok(MigrationPreflight::Current { version: current })
@@ -580,6 +603,7 @@ async fn is_ledgerless_legacy_baseline(
"product_events",
"product_event_daily_rollups",
"onboarding_selections",
"onboarding_import_selections",
"artifact_blobs",
"artifact_sources",
] {
@@ -130,6 +130,9 @@ pub(super) fn validate_descriptors(
!= artifact_metadata_v12::SOURCE_SHA256
|| sha256_hex(artifact_cleanup_indexes_v13::SOURCE.as_bytes())
!= artifact_cleanup_indexes_v13::SOURCE_SHA256
|| sha256_hex(import_plan_v14::SOURCE.as_bytes()) != import_plan_v14::SOURCE_SHA256
|| sha256_hex(onboarding_import_selection_v15::SOURCE.as_bytes())
!= onboarding_import_selection_v15::SOURCE_SHA256
{
return Err(MigrationError::new(
"invalid_contract",
@@ -8,7 +8,7 @@ fn sequence_is_deterministic_and_append_only() {
MigrationAuthority::validate_sequence().unwrap();
assert_eq!(
first.iter().map(|item| item.version).collect::<Vec<_>>(),
vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
);
assert_eq!(first[0].checksum, "crank-community-baseline-v1");
assert_eq!(first[0].source_digest, BASELINE_SOURCE_SHA256);
@@ -0,0 +1,44 @@
use sqlx::{Postgres, Transaction, query};
use super::authority::{MigrationDescriptor, MigrationError};
pub(super) const SOURCE: &str = include_str!("import_plan_v14.sql");
pub(super) const SOURCE_SHA256: &str =
"176c5b3cd12ddaf78dd0d312626a0c387f9c240a765194b34e88f7e0d3b4ca2a";
pub(super) async fn apply(
transaction: &mut Transaction<'_, Postgres>,
descriptor: &MigrationDescriptor,
) -> Result<(), MigrationError> {
sqlx::raw_sql(SOURCE)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.import_plan",
Some(14),
"restore_known_good_backup",
)
})?;
query(
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
values ($1, $2, $3, $4, $5)",
)
.bind(descriptor.version)
.bind(descriptor.name)
.bind(&descriptor.checksum)
.bind(descriptor.phase)
.bind(descriptor.compatibility)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.canonical_ledger",
Some(14),
"restore_known_good_backup",
)
})?;
Ok(())
}
@@ -0,0 +1,68 @@
-- Import plan re-import: an immutable plan snapshot bound to the source import
-- job, plus immutable application evidence. Both are workspace-scoped and
-- append-only; UPDATE is rejected. Retention semantics: a plan never outlives
-- its job, so deleting the job cascades to the plan. Application rows
-- deliberately carry no FK to the plan: they keep
-- (workspace_id, idempotency_key, plan_digest) as replay evidence after the
-- job and plan have been cleaned up, and their `plan_id` is a history string.
-- No payload/report byte bounds here: the registry/service contract enforces
-- them.
alter table import_jobs
add constraint import_jobs_workspace_id_unique
unique (workspace_id, id);
create table import_plans (
workspace_id text not null references workspaces(id) on delete cascade,
id text not null,
job_id text not null,
digest text not null,
payload jsonb not null,
created_at timestamptz not null,
expires_at timestamptz not null,
constraint import_plans_digest_check check (digest ~ '^[0-9a-f]{64}$'),
constraint import_plans_payload_check check (jsonb_typeof(payload) = 'object'),
constraint import_plans_expires_check check (expires_at > created_at),
constraint import_plans_job_fk
foreign key (workspace_id, job_id)
references import_jobs(workspace_id, id)
on delete cascade,
primary key (workspace_id, id)
);
create table import_plan_applications (
workspace_id text not null references workspaces(id) on delete cascade,
idempotency_key text not null,
plan_id text not null,
plan_digest text not null,
report jsonb not null,
created_at timestamptz not null,
constraint import_plan_applications_plan_digest_check
check (plan_digest ~ '^[0-9a-f]{64}$'),
constraint import_plan_applications_report_check
check (jsonb_typeof(report) = 'object'),
primary key (workspace_id, idempotency_key)
);
create index import_plans_workspace_job_idx
on import_plans(workspace_id, job_id);
create index import_plan_applications_workspace_plan_idx
on import_plan_applications(workspace_id, plan_id);
create function crank_reject_import_plan_mutation()
returns trigger
language plpgsql
as $$
begin
raise exception 'import plan rows are immutable' using errcode = '23514';
end;
$$;
create trigger import_plans_immutable_guard
before update on import_plans
for each row execute function crank_reject_import_plan_mutation();
create trigger import_plan_applications_immutable_guard
before update on import_plan_applications
for each row execute function crank_reject_import_plan_mutation();
@@ -0,0 +1,44 @@
use sqlx::{Postgres, Transaction, query};
use super::authority::{MigrationDescriptor, MigrationError};
pub(super) const SOURCE: &str = include_str!("onboarding_import_selection_v15.sql");
pub(super) const SOURCE_SHA256: &str =
"0dbe85c649ca227f15ac141e7bf004948d3240c3495489b30e2197980ecd0c5e";
pub(super) async fn apply(
transaction: &mut Transaction<'_, Postgres>,
descriptor: &MigrationDescriptor,
) -> Result<(), MigrationError> {
sqlx::raw_sql(SOURCE)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.onboarding_import_selection",
Some(15),
"restore_known_good_backup",
)
})?;
query(
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
values ($1, $2, $3, $4, $5)",
)
.bind(descriptor.version)
.bind(descriptor.name)
.bind(&descriptor.checksum)
.bind(descriptor.phase)
.bind(descriptor.compatibility)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.canonical_ledger",
Some(15),
"restore_known_good_backup",
)
})?;
Ok(())
}
@@ -0,0 +1,81 @@
-- Guided onboarding OpenAPI import context.
--
-- A workspace has at most one durable import context. It stores only the
-- identity of an already committed immutable apply report
-- (`application_idempotency_key`, `plan_digest`) plus the explicitly selected
-- operation/version and timestamps. The immutable report itself is never
-- copied or mutated here; recovery re-reads it from
-- `import_plan_applications` by (workspace_id, idempotency_key) and verifies
-- the exact plan digest. This keeps the context alive after the import job and
-- plan are garbage collected.
--
-- Pending context has null selected operation/version and suppresses generic
-- automatic Operation selection until the administrator explicitly picks one
-- actionable Draft. Reset deletes the context without touching the terminal
-- `onboarding_selections` evidence boundary.
alter table operations
add constraint operations_workspace_id_unique unique (workspace_id, id);
create table onboarding_import_selections (
workspace_id text primary key references workspaces(id) on delete cascade,
application_idempotency_key text not null,
plan_digest text not null,
selected_operation_id text null,
selected_operation_version integer null,
registered_at timestamptz not null,
selected_at timestamptz null,
constraint onboarding_import_selections_application_key_check
check (octet_length(application_idempotency_key) between 1 and 256),
constraint onboarding_import_selections_plan_digest_check
check (plan_digest ~ '^[0-9a-f]{64}$'),
constraint onboarding_import_selections_version_check
check (selected_operation_version is null or selected_operation_version > 0),
constraint onboarding_import_selections_selection_shape_check check (
(
selected_operation_id is null
and selected_operation_version is null
and selected_at is null
) or (
selected_operation_id is not null
and selected_operation_version is not null
and selected_at is not null
)
),
-- The selected Operation is a durable report anchor. Hard-deleting it must
-- fail until the administrator explicitly resets/clears the import context;
-- normal archive keeps the row and surfaces drift. `no action` (checked at
-- statement end) still lets a single workspace deletion cascade-clean the
-- whole context together with its operations.
constraint onboarding_import_selections_operation_fk
foreign key (workspace_id, selected_operation_id)
references operations(workspace_id, id)
on delete no action,
constraint onboarding_import_selections_application_fk
foreign key (workspace_id, application_idempotency_key)
references import_plan_applications(workspace_id, idempotency_key)
on delete cascade
);
create index onboarding_import_selections_operation_idx
on onboarding_import_selections(workspace_id, selected_operation_id);
alter table product_events
drop constraint product_events_name_check;
alter table product_events
add constraint product_events_name_check check (event_name in (
'onboarding_eligible', 'onboarding_started', 'onboarding_resumed', 'onboarding_dismissed',
'onboarding_abandoned', 'onboarding_completed',
'onboarding_import_eligible', 'onboarding_import_published', 'onboarding_agent_activated'
));
alter table product_event_daily_rollups
drop constraint product_event_daily_rollups_name_check;
alter table product_event_daily_rollups
add constraint product_event_daily_rollups_name_check check (event_name in (
'onboarding_eligible', 'onboarding_started', 'onboarding_resumed', 'onboarding_dismissed',
'onboarding_abandoned', 'onboarding_completed',
'onboarding_import_eligible', 'onboarding_import_published', 'onboarding_agent_activated'
));
@@ -31,8 +31,12 @@ pub(super) const ONBOARDING_PRODUCT_EVENTS: &[&str] = &[
"onboarding_selections",
];
pub(super) const ONBOARDING_IMPORT_SELECTION: &[&str] = &["onboarding_import_selections"];
pub(super) const ARTIFACT_METADATA: &[&str] = &["artifact_blobs", "artifact_sources"];
pub(super) const IMPORT_PLAN: &[&str] = &["import_plans", "import_plan_applications"];
pub(super) const CONSOLIDATION: &[&str] = &[
"__crank_migrations",
"__crank_migration_legacy_audit",
@@ -37,6 +37,9 @@ pub(super) const OWNED_RELATIONS: &[&str] = &[
"usage_rollups",
"artifact_blobs",
"artifact_sources",
"import_plans",
"import_plan_applications",
"onboarding_import_selections",
];
const REQUIRED_COLUMNS: &[(&str, &[&str])] = &[
@@ -645,6 +648,20 @@ pub(super) async fn validate_schema_fingerprint(
} else {
super::schema_guard_v13::validate_v13_artifact_cleanup_indexes(connection).await?;
}
if current_version < 14 {
if !super::schema_guard_v14::validate_v14_absent(connection).await? {
return Err(schema_error(current_version));
}
} else {
super::schema_guard_v14::validate_v14_import_plan(connection).await?;
}
if current_version < 15 {
if !super::schema_guard_v15::validate_v15_absent(connection).await? {
return Err(schema_error(current_version));
}
} else {
super::schema_guard_v15::validate_v15_onboarding_import_selection(connection).await?;
}
Ok(())
}
@@ -0,0 +1,515 @@
use sqlx::{PgConnection, Row, query};
use super::authority::MigrationError;
use super::schema_guard::schema_error;
const PLAN_COLUMNS: &[(&str, &str, bool, Option<&str>)] = &[
("workspace_id", "text", false, None),
("id", "text", false, None),
("job_id", "text", false, None),
("digest", "text", false, None),
("payload", "jsonb", false, None),
("created_at", "timestamp with time zone", false, None),
("expires_at", "timestamp with time zone", false, None),
];
const APPLICATION_COLUMNS: &[(&str, &str, bool, Option<&str>)] = &[
("workspace_id", "text", false, None),
("idempotency_key", "text", false, None),
("plan_id", "text", false, None),
("plan_digest", "text", false, None),
("report", "jsonb", false, None),
("created_at", "timestamp with time zone", false, None),
];
const PLAN_CONSTRAINTS: &[(&str, &str, &str)] = &[
("import_plans_pkey", "p", "PRIMARY KEY (workspace_id, id)"),
(
"import_plans_job_fk",
"f",
"FOREIGN KEY (workspace_id, job_id) REFERENCES import_jobs (workspace_id, id) ON DELETE CASCADE",
),
(
"import_plans_workspace_id_fkey",
"f",
"FOREIGN KEY (workspace_id) REFERENCES workspaces (id) ON DELETE CASCADE",
),
(
"import_plans_digest_check",
"c",
"CHECK (digest ~ '^[0-9a-f]{64}$'::text)",
),
(
"import_plans_payload_check",
"c",
"CHECK (jsonb_typeof(payload) = 'object'::text)",
),
(
"import_plans_expires_check",
"c",
"CHECK (expires_at > created_at)",
),
];
const APPLICATION_CONSTRAINTS: &[(&str, &str, &str)] = &[
(
"import_plan_applications_pkey",
"p",
"PRIMARY KEY (workspace_id, idempotency_key)",
),
(
"import_plan_applications_workspace_id_fkey",
"f",
"FOREIGN KEY (workspace_id) REFERENCES workspaces (id) ON DELETE CASCADE",
),
(
"import_plan_applications_plan_digest_check",
"c",
"CHECK (plan_digest ~ '^[0-9a-f]{64}$'::text)",
),
(
"import_plan_applications_report_check",
"c",
"CHECK (jsonb_typeof(report) = 'object'::text)",
),
];
pub(super) async fn validate_v14_absent(
connection: &mut PgConnection,
) -> Result<bool, MigrationError> {
let mut absent = true;
for table in ["import_plans", "import_plan_applications"] {
if relation_exists(connection, table).await? {
absent = false;
}
}
if absent
&& query(
"select exists (
select 1 from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema()
and t.relname = 'import_jobs'
and c.conname = 'import_jobs_workspace_id_unique'
) as present",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))?
{
absent = false;
}
if absent && function_exists(connection, "crank_reject_import_plan_mutation").await? {
absent = false;
}
Ok(absent)
}
pub(super) async fn validate_v14_import_plan(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
validate_table_properties(connection).await?;
validate_columns(connection, "import_plans", PLAN_COLUMNS).await?;
validate_columns(connection, "import_plan_applications", APPLICATION_COLUMNS).await?;
validate_constraints(connection, "import_plans", PLAN_CONSTRAINTS).await?;
validate_constraints(
connection,
"import_plan_applications",
APPLICATION_CONSTRAINTS,
)
.await?;
validate_jobs_unique(connection).await?;
validate_deferred_flags(connection).await?;
validate_indexes(connection).await?;
validate_immutable_guards(connection).await
}
async fn validate_table_properties(connection: &mut PgConnection) -> Result<(), MigrationError> {
let rows = query(
"select c.relname, c.relpersistence::text as persistence,
c.relrowsecurity, c.relforcerowsecurity, c.reloptions
from pg_catalog.pg_class c
join pg_catalog.pg_namespace n on n.oid = c.relnamespace
where n.nspname = current_schema()
and c.relname in ('import_plans', 'import_plan_applications')
order by c.relname",
)
.fetch_all(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = rows.len() == 2
&& rows.iter().all(|row| {
row.try_get::<String, _>("persistence").ok().as_deref() == Some("p")
&& row.try_get::<bool, _>("relrowsecurity").ok() == Some(false)
&& row.try_get::<bool, _>("relforcerowsecurity").ok() == Some(false)
&& row
.try_get::<Option<Vec<String>>, _>("reloptions")
.ok()
.flatten()
.is_none()
});
if valid { Ok(()) } else { Err(schema_error(14)) }
}
async fn validate_columns(
connection: &mut PgConnection,
table: &str,
expected: &[(&str, &str, bool, Option<&str>)],
) -> Result<(), MigrationError> {
let rows = query(
"select column_name, data_type, is_nullable, column_default,
datetime_precision, collation_name
from information_schema.columns
where table_schema = current_schema() and table_name = $1
order by ordinal_position",
)
.bind(table)
.fetch_all(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
if rows.len() != expected.len() {
return Err(schema_error(14));
}
for (row, (name, data_type, nullable, default)) in rows.iter().zip(expected) {
let actual_default = row
.try_get::<Option<String>, _>("column_default")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let datetime_precision = row
.try_get::<Option<i32>, _>("datetime_precision")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let collation = row
.try_get::<Option<String>, _>("collation_name")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
if row.try_get::<String, _>("column_name").ok().as_deref() != Some(*name)
|| row.try_get::<String, _>("data_type").ok().as_deref() != Some(*data_type)
|| row.try_get::<String, _>("is_nullable").ok().as_deref()
!= Some(if *nullable { "YES" } else { "NO" })
|| actual_default.as_deref() != *default
|| (data_type == &"timestamp with time zone" && datetime_precision != Some(6))
|| collation.is_some()
{
return Err(schema_error(14));
}
}
Ok(())
}
async fn validate_constraints(
connection: &mut PgConnection,
table: &str,
expected: &[(&str, &str, &str)],
) -> Result<(), MigrationError> {
let rows = query(
"select c.conname, c.contype::text as contype, pg_get_constraintdef(c.oid, true) as definition
from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema() and t.relname = $1
order by c.conname",
)
.bind(table)
.fetch_all(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
if rows.len() != expected.len() {
return Err(schema_error(14));
}
for row in rows {
let name = row
.try_get::<String, _>("conname")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let kind = row
.try_get::<String, _>("contype")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let definition = row
.try_get::<String, _>("definition")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let Some((_, _, expected_definition)) =
expected.iter().find(|(expected_name, expected_kind, _)| {
name == *expected_name && kind == *expected_kind
})
else {
return Err(schema_error(14));
};
if canonical_definition(&definition) != canonical_definition(expected_definition) {
return Err(schema_error(14));
}
}
Ok(())
}
async fn validate_deferred_flags(connection: &mut PgConnection) -> Result<(), MigrationError> {
for (deferrable, deferred, constraint) in [
(false, false, "import_plans_job_fk"),
(false, false, "import_plans_workspace_id_fkey"),
(false, false, "import_plan_applications_workspace_id_fkey"),
] {
let row = query(
"select c.conname, c.condeferrable, c.condeferred
from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema() and c.conname = $1 and c.contype = 'f'",
)
.bind(constraint)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<bool, _>("condeferrable").ok() == Some(deferrable)
&& row.try_get::<bool, _>("condeferred").ok() == Some(deferred)
});
if !valid {
return Err(schema_error(14));
}
}
Ok(())
}
async fn validate_jobs_unique(connection: &mut PgConnection) -> Result<(), MigrationError> {
let row = query(
"select c.conname, pg_get_constraintdef(c.oid, true) as definition
from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema()
and t.relname = 'import_jobs'
and c.conname = 'import_jobs_workspace_id_unique'
and c.contype = 'u'",
)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("definition")
.ok()
.as_deref()
.is_some_and(|definition| {
canonical_definition(definition)
== canonical_definition("UNIQUE (workspace_id, id)")
})
});
if valid { Ok(()) } else { Err(schema_error(14)) }
}
async fn validate_indexes(connection: &mut PgConnection) -> Result<(), MigrationError> {
struct IndexContract {
name: &'static str,
table: &'static str,
unique: bool,
columns: &'static [&'static str],
}
const CONTRACTS: &[IndexContract] = &[
IndexContract {
name: "import_plans_workspace_job_idx",
table: "import_plans",
unique: false,
columns: &["workspace_id", "job_id"],
},
IndexContract {
name: "import_plan_applications_workspace_plan_idx",
table: "import_plan_applications",
unique: false,
columns: &["workspace_id", "plan_id"],
},
IndexContract {
name: "import_jobs_workspace_id_unique",
table: "import_jobs",
unique: true,
columns: &["workspace_id", "id"],
},
IndexContract {
name: "import_plans_pkey",
table: "import_plans",
unique: true,
columns: &["workspace_id", "id"],
},
IndexContract {
name: "import_plan_applications_pkey",
table: "import_plan_applications",
unique: true,
columns: &["workspace_id", "idempotency_key"],
},
];
for contract in CONTRACTS {
let row = query(
"select t.relname as table_name, am.amname as access_method,
i.indisvalid, i.indisready, i.indisunique,
i.indnkeyatts, i.indnatts,
pg_get_indexdef(i.indexrelid, 1, true) as first_column,
pg_get_indexdef(i.indexrelid, 2, true) as second_column,
pg_get_expr(i.indpred, i.indrelid) as predicate
from pg_catalog.pg_index i
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
join pg_catalog.pg_class t on t.oid = i.indrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
join pg_catalog.pg_am am on am.oid = idx.relam
where n.nspname = current_schema() and idx.relname = $1",
)
.bind(contract.name)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("table_name").ok().as_deref() == Some(contract.table)
&& row.try_get::<String, _>("access_method").ok().as_deref() == Some("btree")
&& row.try_get::<bool, _>("indisvalid").ok() == Some(true)
&& row.try_get::<bool, _>("indisready").ok() == Some(true)
&& row.try_get::<bool, _>("indisunique").ok() == Some(contract.unique)
&& row.try_get::<i16, _>("indnkeyatts").ok() == Some(2)
&& row.try_get::<i16, _>("indnatts").ok() == Some(2)
&& row.try_get::<String, _>("first_column").ok().as_deref()
== Some(contract.columns[0])
&& row.try_get::<String, _>("second_column").ok().as_deref()
== Some(contract.columns[1])
&& row
.try_get::<Option<String>, _>("predicate")
.ok()
.flatten()
.is_none()
});
if !valid {
return Err(schema_error(14));
}
}
Ok(())
}
async fn validate_immutable_guards(connection: &mut PgConnection) -> Result<(), MigrationError> {
let rows = query(
"select tg.tgname, t.relname as table_name, tg.tgtype::int as tgtype,
tg.tgenabled::text as tgenabled, tg.tgisinternal,
pg_get_triggerdef(tg.oid, true) as definition
from pg_catalog.pg_trigger tg
join pg_catalog.pg_class t on t.oid = tg.tgrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema()
and t.relname in ('import_plans', 'import_plan_applications')
and not tg.tgisinternal
order by tg.tgname",
)
.fetch_all(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let contracts = [
("import_plans_immutable_guard", "import_plans"),
(
"import_plan_applications_immutable_guard",
"import_plan_applications",
),
];
let mut seen = [false; 2];
for row in &rows {
let name = row
.try_get::<String, _>("tgname")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let table = row
.try_get::<String, _>("table_name")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let tgtype = row
.try_get::<i32, _>("tgtype")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let enabled = row
.try_get::<String, _>("tgenabled")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let internal = row
.try_get::<bool, _>("tgisinternal")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let definition = row
.try_get::<String, _>("definition")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let index = contracts
.iter()
.position(|(expected_name, expected_table)| {
name == *expected_name && table == *expected_table
})
.ok_or_else(|| schema_error(14))?;
let before_update_row = (tgtype & 1) != 0 && (tgtype & 2) != 0 && (tgtype & 16) != 0;
let calls_guard = definition
.to_lowercase()
.contains("execute function crank_reject_import_plan_mutation()");
if !(before_update_row && enabled == "O" && !internal && calls_guard) {
return Err(schema_error(14));
}
seen[index] = true;
}
if !seen.iter().all(|present| *present) {
return Err(schema_error(14));
}
if !function_exists(connection, "crank_reject_import_plan_mutation").await? {
return Err(schema_error(14));
}
let policy_count = sqlx::query_scalar::<_, i64>(
"select
(select count(*) from pg_catalog.pg_policy p
join pg_catalog.pg_class t on t.oid = p.polrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema()
and t.relname in ('import_plans', 'import_plan_applications'))",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
if policy_count != 0 {
return Err(schema_error(14));
}
Ok(())
}
fn canonical_definition(value: &str) -> String {
let mut quoted = false;
value
.chars()
.filter_map(|character| {
if character == '\'' {
quoted = !quoted;
return Some(character);
}
if character.is_ascii_whitespace() {
None
} else if quoted {
Some(character)
} else {
Some(character.to_ascii_lowercase())
}
})
.collect()
}
async fn relation_exists(
connection: &mut PgConnection,
relation: &str,
) -> Result<bool, MigrationError> {
query("select to_regclass(format('%I.%I', current_schema(), $1))::text is not null as present")
.bind(relation)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.inventory"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.inventory"))
}
async fn function_exists(
connection: &mut PgConnection,
function: &str,
) -> Result<bool, MigrationError> {
query(
"select exists (
select 1 from pg_catalog.pg_proc p
join pg_catalog.pg_namespace n on n.oid = p.pronamespace
where n.nspname = current_schema()
and p.proname = $1
and p.pronargs = 0
and p.prokind = 'f'
) as present",
)
.bind(function)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))
}
@@ -0,0 +1,334 @@
use sqlx::{PgConnection, Row, query};
use super::authority::MigrationError;
use super::schema_guard::{
constraint_expression, normalize_definition, relation_exists, schema_error,
};
const IMPORT_EVENT_NAMES: &[&str] = &[
"onboarding_import_eligible",
"onboarding_import_published",
"onboarding_agent_activated",
];
const CONTEXT_COLUMNS: &[(&str, &str, bool)] = &[
("workspace_id", "text", false),
("application_idempotency_key", "text", false),
("plan_digest", "text", false),
("selected_operation_id", "text", true),
("selected_operation_version", "integer", true),
("registered_at", "timestamp with time zone", false),
("selected_at", "timestamp with time zone", true),
];
pub(super) async fn validate_v15_absent(
connection: &mut PgConnection,
) -> Result<bool, MigrationError> {
if relation_exists(connection, "onboarding_import_selections").await? {
return Ok(false);
}
if named_constraint_exists(connection, "operations", "operations_workspace_id_unique").await? {
return Ok(false);
}
if !relation_exists(connection, "product_events").await? {
return Ok(true);
}
let name_check =
constraint_expression(connection, "product_events", "product_events_name_check").await?;
Ok(!normalize_definition(&name_check).contains("onboarding_import_eligible"))
}
pub(super) async fn validate_v15_onboarding_import_selection(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
validate_context_columns(connection).await?;
validate_context_constraints(connection).await?;
validate_context_index(connection).await?;
if !named_constraint_exists(connection, "operations", "operations_workspace_id_unique").await? {
return Err(schema_error(15));
}
for (table, constraint) in [
("product_events", "product_events_name_check"),
(
"product_event_daily_rollups",
"product_event_daily_rollups_name_check",
),
] {
let definition =
normalize_definition(&constraint_expression(connection, table, constraint).await?);
for event_name in IMPORT_EVENT_NAMES {
if !definition.contains(event_name) {
return Err(schema_error(15));
}
}
}
Ok(())
}
async fn validate_context_columns(connection: &mut PgConnection) -> Result<(), MigrationError> {
for (name, data_type, nullable) in CONTEXT_COLUMNS {
let row = query(
"select data_type, is_nullable, column_default, datetime_precision, collation_name
from information_schema.columns
where table_schema = current_schema()
and table_name = 'onboarding_import_selections'
and column_name = $1",
)
.bind(name)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let Some(row) = row else {
return Err(schema_error(15));
};
let actual_type = row
.try_get::<String, _>("data_type")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let actual_nullable = row
.try_get::<String, _>("is_nullable")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let default = row
.try_get::<Option<String>, _>("column_default")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let precision = row
.try_get::<Option<i32>, _>("datetime_precision")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let collation = row
.try_get::<Option<String>, _>("collation_name")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
if actual_type != *data_type
|| actual_nullable != if *nullable { "YES" } else { "NO" }
|| default.is_some()
|| (*data_type == "timestamp with time zone" && precision != Some(6))
|| collation.is_some()
{
return Err(schema_error(15));
}
}
Ok(())
}
async fn validate_context_constraints(connection: &mut PgConnection) -> Result<(), MigrationError> {
for (name, kind, required) in [
(
"onboarding_import_selections_pkey",
"p",
&["primarykeyworkspace_id"][..],
),
(
"onboarding_import_selections_workspace_id_fkey",
"f",
&[
"foreignkeyworkspace_id",
"referencesworkspacesid",
"ondeletecascade",
][..],
),
(
"onboarding_import_selections_operation_fk",
"f",
&[
"foreignkeyworkspace_id,selected_operation_id",
"referencesoperationsworkspace_id,id",
][..],
),
(
"onboarding_import_selections_application_fk",
"f",
&[
"foreignkeyworkspace_id,application_idempotency_key",
"referencesimport_plan_applicationsworkspace_id,idempotency_key",
"ondeletecascade",
][..],
),
] {
let definition = constraint_definition(connection, name).await?;
if !constraint_is_type(connection, name, kind).await? {
return Err(schema_error(15));
}
for snippet in required {
if !definition.contains(snippet) {
return Err(schema_error(15));
}
}
}
// `ON DELETE NO ACTION` is the FK default and Postgres omits it from
// `pg_get_constraintdef`; assert the raw delete action instead so a
// selected Operation hard-delete cannot silently cascade the report.
if constraint_delete_action(connection, "onboarding_import_selections_operation_fk")
.await?
.as_deref()
!= Some("a")
{
return Err(schema_error(15));
}
for (name, required) in [
(
"onboarding_import_selections_application_key_check",
&[
"octet_lengthapplication_idempotency_key>=1",
"octet_lengthapplication_idempotency_key<=256",
][..],
),
(
"onboarding_import_selections_plan_digest_check",
&["plan_digest~'^[0-9a-f]{64}$'"][..],
),
(
"onboarding_import_selections_version_check",
&[
"selected_operation_versionisnull",
"selected_operation_version>0",
][..],
),
(
"onboarding_import_selections_selection_shape_check",
&["selected_operation_idisnull", "selected_atisnull"][..],
),
] {
let definition = normalize_definition(
&constraint_expression(connection, "onboarding_import_selections", name).await?,
);
if required
.iter()
.any(|snippet| !definition.contains(&normalize_definition(snippet)))
{
return Err(schema_error(15));
}
}
Ok(())
}
async fn validate_context_index(connection: &mut PgConnection) -> Result<(), MigrationError> {
let row = query(
"select t.relname as table_name, am.amname as access_method,
i.indisvalid, i.indisready, i.indisunique, i.indnkeyatts,
pg_get_indexdef(i.indexrelid, 1, true) as first_column,
pg_get_indexdef(i.indexrelid, 2, true) as second_column,
pg_get_expr(i.indpred, i.indrelid) as predicate
from pg_catalog.pg_index i
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
join pg_catalog.pg_class t on t.oid = i.indrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
join pg_catalog.pg_am am on am.oid = idx.relam
where n.nspname = current_schema()
and idx.relname = 'onboarding_import_selections_operation_idx'",
)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("table_name").ok().as_deref()
== Some("onboarding_import_selections")
&& row.try_get::<String, _>("access_method").ok().as_deref() == Some("btree")
&& row.try_get::<bool, _>("indisvalid").ok() == Some(true)
&& row.try_get::<bool, _>("indisready").ok() == Some(true)
&& row.try_get::<bool, _>("indisunique").ok() == Some(false)
&& row.try_get::<i16, _>("indnkeyatts").ok() == Some(2)
&& row.try_get::<String, _>("first_column").ok().as_deref() == Some("workspace_id")
&& row.try_get::<String, _>("second_column").ok().as_deref()
== Some("selected_operation_id")
&& row
.try_get::<Option<String>, _>("predicate")
.ok()
.flatten()
.is_none()
});
if valid { Ok(()) } else { Err(schema_error(15)) }
}
async fn constraint_definition(
connection: &mut PgConnection,
constraint: &str,
) -> Result<String, MigrationError> {
query(
"select pg_get_constraintdef(c.oid, true) as definition
from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema()
and t.relname = 'onboarding_import_selections'
and c.conname = $1",
)
.bind(constraint)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.ok_or_else(|| schema_error(15))?
.try_get::<String, _>("definition")
.map(|definition| normalize_definition(&definition))
.map_err(|_| MigrationError::storage("preflight.schema"))
}
async fn constraint_delete_action(
connection: &mut PgConnection,
constraint: &str,
) -> Result<Option<String>, MigrationError> {
query(
"select c.confdeltype::text as action
from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema()
and t.relname = 'onboarding_import_selections'
and c.conname = $1",
)
.bind(constraint)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.map(|row| {
row.try_get::<String, _>("action")
.map_err(|_| MigrationError::storage("preflight.schema"))
})
.transpose()
}
async fn constraint_is_type(
connection: &mut PgConnection,
constraint: &str,
kind: &str,
) -> Result<bool, MigrationError> {
query(
"select exists (
select 1 from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema()
and t.relname = 'onboarding_import_selections'
and c.conname = $1
and c.contype = $2
) as present",
)
.bind(constraint)
.bind(kind)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get("present")
.map_err(|_| MigrationError::storage("preflight.schema"))
}
async fn named_constraint_exists(
connection: &mut PgConnection,
table: &str,
constraint: &str,
) -> Result<bool, MigrationError> {
query(
"select exists (
select 1 from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema()
and t.relname = $1
and c.conname = $2
) as present",
)
.bind(table)
.bind(constraint)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get("present")
.map_err(|_| MigrationError::storage("preflight.schema"))
}