Files
crank/crates/crank-registry/src/migrations/authority.rs
T
bsodfather 54ce770682
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.

Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
  Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
  3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
  revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
  version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
  dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
  resources/list admission fix for bound template publications.

Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
  `just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
  a real MCP Inspector 2.12.0 client smoke.

Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
  runs only on main), story events run the changed packages, the full workspace suite
  stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
  release entry of the tag instead of dying with the runner workspace.

Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.

Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
2026-10-25 09:08:22 +00:00

671 lines
22 KiB
Rust

use super::admin_auth_lifecycle_v8;
use super::agent_catalog_lifecycle_v9;
use super::agent_resource_bindings_v18;
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;
use super::prompt_dependencies_v23;
use super::prompt_publications_v22;
use super::prompts_v21;
use super::resource_drafts_v16;
use super::resource_publications_v17;
use super::resource_security_revocations_v19;
use super::resource_template_sources_v20;
use super::schema_guard::{
OWNED_RELATIONS, relation_exists, validate_required_relations, validate_schema_fingerprint,
};
use super::schema_guard_legacy_v1::{
validate_ledgerless_baseline_fingerprint, validate_ledgerless_optional_fingerprints,
};
use super::{BASELINE_CHECKSUM, BASELINE_VERSION, apply_baseline};
use crate::ext::ExtensionMigration;
use sqlx::{PgConnection, PgPool, Row, Transaction, query};
use std::fmt;
mod contract;
mod preflight;
use preflight::*;
#[cfg(test)]
use contract::baseline_source_digest;
use contract::validate_descriptors;
const MIGRATION_LOCK_ID: i64 = 0x4352_414E_4B4D_4947;
const CURRENT_VERSION: i64 = 23;
const IMPLEMENTED_VERSIONS: &[i64] = &[
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
];
const BASELINE_SOURCE_SHA256: &str =
"eb1656fc5b4b5be9ee390d237d1d58e4b2274ae5ba9b7ba06a2f3f860dfda675";
const CONSOLIDATION_SOURCE: &str = include_str!("consolidation_v2.sql");
const CONSOLIDATION_SOURCE_SHA256: &str =
"1908b97ca7fe8a85d146b0eebf007d5018a9ff406cb099614270f3428ec1db48";
const REQUEST_TRACE_IDENTITY_SOURCE: &str = include_str!("request_trace_identity_v3.sql");
const REQUEST_TRACE_IDENTITY_SOURCE_SHA256: &str =
"36487625503a8d4d8f18d5771c3c9b6705f845e267acbfcb7244c330f640cd94";
const OPERATION_LIFECYCLE_SOURCE: &str = include_str!("operation_lifecycle_v4.sql");
const OPERATION_LIFECYCLE_SOURCE_SHA256: &str =
"45723712a1ea49cd8bbf59d77148c225f3ec376df7433983d982cc6f9d7fb39c";
const REGISTERED_EXTENSION_MIGRATIONS: &[(&str, ExtensionMigration)] = &[];
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MigrationDescriptor {
pub version: i64,
pub name: &'static str,
pub checksum: String,
pub source_digest: String,
pub phase: &'static str,
pub compatibility: &'static str,
pub owner: &'static str,
pub transactional: bool,
pub backfill: BackfillPolicy,
pub readable_schema_min: i64,
pub readable_schema_max: i64,
pub contract_evidence: Option<&'static str>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BackfillPolicy {
None,
Bounded {
max_batch_rows: u32,
max_batch_ms: u32,
resumable: bool,
},
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BackfillBatch {
pub cursor: Option<String>,
pub max_rows: u32,
pub max_ms: u32,
}
impl BackfillBatch {
pub fn validate(&self, policy: BackfillPolicy) -> Result<(), MigrationError> {
match policy {
BackfillPolicy::Bounded {
max_batch_rows,
max_batch_ms,
resumable: true,
} if (1..=max_batch_rows).contains(&self.max_rows)
&& (1..=max_batch_ms).contains(&self.max_ms)
&& self
.cursor
.as_ref()
.is_none_or(|cursor| cursor.len() <= 256) =>
{
Ok(())
}
_ => Err(MigrationError::new(
"invalid_contract",
"contract.backfill",
None,
"contact_operator",
)),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MigrationPreflight {
Current { version: i64 },
MigrationRequired { current: i64, target: i64 },
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MigrationApplyResult {
Applied { from: i64, to: i64 },
AlreadyCurrent { version: i64 },
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MigrationError {
code: &'static str,
stage: &'static str,
version: Option<i64>,
recovery: &'static str,
}
impl MigrationError {
pub(super) fn new(
code: &'static str,
stage: &'static str,
version: Option<i64>,
recovery: &'static str,
) -> Self {
Self {
code,
stage,
version,
recovery,
}
}
pub(super) fn storage(stage: &'static str) -> Self {
Self::new("storage_unavailable", stage, None, "contact_operator")
}
pub fn code(&self) -> &'static str {
self.code
}
pub fn stage(&self) -> &'static str {
self.stage
}
pub fn version(&self) -> Option<i64> {
self.version
}
pub fn recovery(&self) -> &'static str {
self.recovery
}
}
impl fmt::Display for MigrationError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
formatter,
"migration_error code={} stage={} version={} recovery={}",
self.code,
self.stage,
self.version
.map_or_else(|| "none".to_owned(), |value| value.to_string()),
self.recovery
)
}
}
impl std::error::Error for MigrationError {}
pub struct MigrationAuthority;
fn expand_descriptor(
version: i64,
name: &'static str,
checksum: &'static str,
readable_schema_min: i64,
) -> MigrationDescriptor {
MigrationDescriptor {
version,
name,
checksum: checksum.to_owned(),
source_digest: checksum.to_owned(),
phase: "expand",
compatibility: "n-minus-one-readable",
owner: "crank-registry",
transactional: true,
backfill: BackfillPolicy::None,
readable_schema_min,
readable_schema_max: version,
contract_evidence: None,
}
}
impl MigrationAuthority {
pub fn registered_extension_migrations() -> &'static [(&'static str, ExtensionMigration)] {
REGISTERED_EXTENSION_MIGRATIONS
}
pub fn sequence() -> Vec<MigrationDescriptor> {
vec![
MigrationDescriptor {
version: i64::from(BASELINE_VERSION),
name: "community-baseline-v1",
checksum: BASELINE_CHECKSUM.to_owned(),
source_digest: BASELINE_SOURCE_SHA256.to_owned(),
phase: "expand",
compatibility: "legacy-baseline",
owner: "crank-registry",
transactional: true,
backfill: BackfillPolicy::None,
readable_schema_min: 1,
readable_schema_max: 1,
contract_evidence: None,
},
expand_descriptor(2, "legacy-consolidation-v2", CONSOLIDATION_SOURCE_SHA256, 1),
expand_descriptor(
3,
"request-trace-identity-v3",
REQUEST_TRACE_IDENTITY_SOURCE_SHA256,
2,
),
expand_descriptor(
4,
"operation-lifecycle-v4",
OPERATION_LIFECYCLE_SOURCE_SHA256,
3,
),
expand_descriptor(
5,
"execution-outcome-v5",
execution_outcome_v5::SOURCE_SHA256,
4,
),
expand_descriptor(
6,
"platform-key-name-reuse-v6",
platform_key_name_reuse_v6::SOURCE_SHA256,
5,
),
expand_descriptor(
7,
"master-key-identity-v7",
master_key_identity_v7::SOURCE_SHA256,
6,
),
expand_descriptor(
8,
"admin-auth-lifecycle-v8",
admin_auth_lifecycle_v8::SOURCE_SHA256,
7,
),
expand_descriptor(
9,
"agent-catalog-lifecycle-v9",
agent_catalog_lifecycle_v9::SOURCE_SHA256,
8,
),
expand_descriptor(
10,
"approval-side-effects-v10",
approval_side_effects_v10::SOURCE_SHA256,
9,
),
expand_descriptor(
11,
"onboarding-product-events-v11",
onboarding_product_events_v11::SOURCE_SHA256,
10,
),
expand_descriptor(
12,
"artifact-metadata-v12",
artifact_metadata_v12::SOURCE_SHA256,
11,
),
expand_descriptor(
13,
"artifact-cleanup-indexes-v13",
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,
),
expand_descriptor(
16,
resource_drafts_v16::NAME,
resource_drafts_v16::SOURCE_SHA256,
15,
),
expand_descriptor(
17,
resource_publications_v17::NAME,
resource_publications_v17::SOURCE_SHA256,
16,
),
expand_descriptor(
18,
agent_resource_bindings_v18::NAME,
agent_resource_bindings_v18::SOURCE_SHA256,
17,
),
expand_descriptor(
19,
resource_security_revocations_v19::NAME,
resource_security_revocations_v19::SOURCE_SHA256,
18,
),
expand_descriptor(
20,
resource_template_sources_v20::NAME,
resource_template_sources_v20::SOURCE_SHA256,
19,
),
expand_descriptor(21, prompts_v21::NAME, prompts_v21::SOURCE_SHA256, 20),
expand_descriptor(
22,
prompt_publications_v22::NAME,
prompt_publications_v22::SOURCE_SHA256,
21,
),
expand_descriptor(
23,
prompt_dependencies_v23::NAME,
prompt_dependencies_v23::SOURCE_SHA256,
22,
),
]
}
pub fn validate_sequence() -> Result<(), MigrationError> {
validate_descriptors(&Self::sequence())
}
pub async fn preflight(pool: &PgPool) -> Result<MigrationPreflight, MigrationError> {
Self::validate_sequence()?;
let mut connection = pool
.acquire()
.await
.map_err(|_| MigrationError::storage("preflight.connect"))?;
inspect(&mut connection).await
}
pub async fn require_current(pool: &PgPool) -> Result<(), MigrationError> {
match Self::preflight(pool).await? {
MigrationPreflight::Current { .. } => Ok(()),
MigrationPreflight::MigrationRequired { current: 0, .. } => Err(MigrationError::new(
"schema_missing",
"preflight.compatibility",
Some(0),
"run_controlled_migration",
)),
MigrationPreflight::MigrationRequired { current, .. } => Err(MigrationError::new(
"migration_required",
"preflight.compatibility",
Some(current),
"run_controlled_migration",
)),
}
}
pub async fn apply(pool: &PgPool) -> Result<MigrationApplyResult, MigrationError> {
Self::validate_sequence()?;
let mut transaction = pool
.begin()
.await
.map_err(|_| MigrationError::storage("apply.begin"))?;
query("set local lock_timeout = '30s'")
.execute(&mut *transaction)
.await
.map_err(|_| MigrationError::storage("apply.lock_policy"))?;
query("select pg_advisory_xact_lock($1)")
.bind(MIGRATION_LOCK_ID)
.execute(&mut *transaction)
.await
.map_err(|error| {
if error
.as_database_error()
.and_then(|database| database.code())
.is_some_and(|code| matches!(code.as_ref(), "55P03" | "57014"))
{
MigrationError::new("lock_timeout", "apply.lock", None, "run_preflight")
} else {
MigrationError::storage("apply.lock")
}
})?;
let before = inspect(&mut transaction).await?;
let from = match before {
MigrationPreflight::Current { version } => {
transaction
.commit()
.await
.map_err(|_| MigrationError::storage("apply.commit"))?;
return Ok(MigrationApplyResult::AlreadyCurrent { version });
}
MigrationPreflight::MigrationRequired { current, .. } => current,
};
if from == 0 {
create_core_ledger(&mut transaction).await?;
apply_baseline(&mut transaction).await.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.baseline",
Some(1),
"restore_known_good_backup",
)
})?;
query(
"insert into __crank_core_migrations (version, description, checksum)
values (1, 'community baseline', $1)",
)
.bind(BASELINE_CHECKSUM)
.execute(&mut *transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.baseline_ledger",
Some(1),
"restore_known_good_backup",
)
})?;
}
if from < 2 {
apply_consolidation(&mut transaction).await?;
}
if from < 3 {
apply_request_trace_identity(&mut transaction).await?;
}
if from < 4 {
apply_operation_lifecycle(&mut transaction).await?;
}
if from < 5 {
execution_outcome_v5::apply(&mut transaction, &Self::sequence()[4]).await?;
}
if from < 6 {
platform_key_name_reuse_v6::apply(&mut transaction, &Self::sequence()[5]).await?;
}
if from < 7 {
master_key_identity_v7::apply(&mut transaction, &Self::sequence()[6]).await?;
}
if from < 8 {
admin_auth_lifecycle_v8::apply(&mut transaction, &Self::sequence()[7]).await?;
}
if from < 9 {
agent_catalog_lifecycle_v9::apply(&mut transaction, &Self::sequence()[8]).await?;
}
if from < 10 {
approval_side_effects_v10::apply(&mut transaction, &Self::sequence()[9]).await?;
}
if from < 11 {
onboarding_product_events_v11::apply(&mut transaction, &Self::sequence()[10]).await?;
}
if from < 12 {
artifact_metadata_v12::apply(&mut transaction, &Self::sequence()[11]).await?;
}
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?;
}
if from < 16 {
resource_drafts_v16::apply(&mut transaction, &Self::sequence()[15]).await?;
}
if from < 17 {
resource_publications_v17::apply(&mut transaction, &Self::sequence()[16]).await?;
}
if from < 18 {
agent_resource_bindings_v18::apply(&mut transaction, &Self::sequence()[17]).await?;
}
if from < 19 {
resource_security_revocations_v19::apply(&mut transaction, &Self::sequence()[18])
.await?;
}
if from < 20 {
resource_template_sources_v20::apply(&mut transaction, &Self::sequence()[19]).await?;
}
if from < 21 {
prompts_v21::apply(&mut transaction, &Self::sequence()[20]).await?;
}
if from < 22 {
prompt_publications_v22::apply(&mut transaction, &Self::sequence()[21]).await?;
}
if from < 23 {
prompt_dependencies_v23::apply(&mut transaction, &Self::sequence()[22]).await?;
}
match inspect(&mut transaction).await? {
MigrationPreflight::Current {
version: CURRENT_VERSION,
} => {}
_ => {
return Err(MigrationError::new(
"apply_failed",
"apply.postflight",
Some(CURRENT_VERSION),
"restore_known_good_backup",
));
}
}
transaction
.commit()
.await
.map_err(|_| MigrationError::storage("apply.commit"))?;
Ok(MigrationApplyResult::Applied {
from,
to: CURRENT_VERSION,
})
}
}
async fn create_core_ledger(
transaction: &mut Transaction<'_, sqlx::Postgres>,
) -> Result<(), MigrationError> {
query(
"create table __crank_core_migrations (
version integer primary key,
description text not null,
checksum text not null,
applied_at timestamptz not null default now()
)",
)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.core_ledger",
Some(1),
"restore_known_good_backup",
)
})?;
Ok(())
}
async fn apply_consolidation(
transaction: &mut Transaction<'_, sqlx::Postgres>,
) -> Result<(), MigrationError> {
sqlx::raw_sql(CONSOLIDATION_SOURCE)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.consolidation",
Some(2),
"restore_known_good_backup",
)
})?;
for (name, extension) in MigrationAuthority::registered_extension_migrations() {
query(
"insert into __crank_migration_legacy_audit
(source, source_version, source_checksum)
select 'extension:' || $1, $2, $3
from __crank_ext_migrations
where extension_name = $1 and version = $2 and checksum = $3",
)
.bind(name)
.bind(i64::from(extension.version))
.bind(extension.checksum)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.extension_audit",
Some(2),
"restore_known_good_backup",
)
})?;
}
let descriptor = &MigrationAuthority::sequence()[1];
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(2),
"restore_known_good_backup",
)
})?;
Ok(())
}
async fn apply_request_trace_identity(
transaction: &mut Transaction<'_, sqlx::Postgres>,
) -> Result<(), MigrationError> {
sqlx::raw_sql(REQUEST_TRACE_IDENTITY_SOURCE)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.request_trace_identity",
Some(3),
"restore_known_good_backup",
)
})?;
let descriptor = &MigrationAuthority::sequence()[2];
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(3),
"restore_known_good_backup",
)
})?;
Ok(())
}
async fn apply_operation_lifecycle(
transaction: &mut Transaction<'_, sqlx::Postgres>,
) -> Result<(), MigrationError> {
sqlx::raw_sql(OPERATION_LIFECYCLE_SOURCE)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.operation_lifecycle",
Some(4),
"restore_known_good_backup",
)
})?;
let descriptor = &MigrationAuthority::sequence()[3];
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(4),
"restore_known_good_backup",
)
})?;
Ok(())
}
#[cfg(test)]
#[path = "authority_tests.rs"]
mod tests;