feat: complete Epic 1 production foundation

This commit is contained in:
bsodfather committed 2026-08-25 01:24:11 +03:00
1 parent 767428436d
commit 182bde8ac0
298 files changed
+35711 -5291

No files matched your search

+174 -113
View File
@@ -1,17 +1,22 @@
use std::fmt;
use sha2::{Digest, Sha256};
use sqlx::{PgConnection, PgPool, Row, Transaction, query};
use super::admin_auth_lifecycle_v8;
use super::agent_catalog_lifecycle_v9;
use super::approval_side_effects_v10;
use super::execution_outcome_v5;
use super::master_key_identity_v7;
use super::onboarding_product_events_v11;
use super::owned_relations;
use super::platform_key_name_reuse_v6;
use super::schema_guard::{
OWNED_RELATIONS, relation_exists, validate_required_relations, validate_schema_fingerprint,
};
use super::{BASELINE_CHECKSUM, BASELINE_VERSION, apply_baseline};
use crate::ext::ExtensionMigration;
use sha2::{Digest, Sha256};
use sqlx::{PgConnection, PgPool, Row, Transaction, query};
use std::fmt;
const MIGRATION_LOCK_ID: i64 = 0x4352_414E_4B4D_4947;
const CURRENT_VERSION: i64 = 3;
const IMPLEMENTED_VERSIONS: &[i64] = &[1, 2, 3];
const CURRENT_VERSION: i64 = 11;
const IMPLEMENTED_VERSIONS: &[i64] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
const BASELINE_SOURCE_SHA256: &str =
"eb1656fc5b4b5be9ee390d237d1d58e4b2274ae5ba9b7ba06a2f3f860dfda675";
const CONSOLIDATION_SOURCE: &str = include_str!("consolidation_v2.sql");
@@ -20,41 +25,10 @@ const CONSOLIDATION_SOURCE_SHA256: &str =
const REQUEST_TRACE_IDENTITY_SOURCE: &str = include_str!("request_trace_identity_v3.sql");
const REQUEST_TRACE_IDENTITY_SOURCE_SHA256: &str =
"36487625503a8d4d8f18d5771c3c9b6705f845e267acbfcb7244c330f640cd94";
const BASELINE_RELATIONS: &[&str] = &[
"workspaces",
"users",
"memberships",
"user_sessions",
"invitation_tokens",
"platform_api_keys",
"operations",
"operation_versions",
"published_operations",
"operation_samples",
"descriptors",
"agents",
"agent_versions",
"published_agents",
"agent_operation_bindings",
"secrets",
"secret_versions",
"auth_profiles",
"workspace_upstreams",
"yaml_import_jobs",
"import_jobs",
"approval_requests",
"invocation_logs",
"usage_rollups",
];
const CONSOLIDATION_RELATIONS: &[&str] = &[
"__crank_migrations",
"__crank_migration_legacy_audit",
"__crank_mcp_migrations",
"mcp_transport_sessions",
"__crank_ext_migrations",
];
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,
@@ -70,7 +44,6 @@ pub struct MigrationDescriptor {
pub readable_schema_max: i64,
pub contract_evidence: Option<&'static str>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BackfillPolicy {
None,
@@ -80,14 +53,12 @@ pub enum BackfillPolicy {
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 {
@@ -113,19 +84,16 @@ impl BackfillBatch {
}
}
}
#[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,
@@ -133,7 +101,6 @@ pub struct MigrationError {
version: Option<i64>,
recovery: &'static str,
}
impl MigrationError {
pub(super) fn new(
code: &'static str,
@@ -148,28 +115,22 @@ impl MigrationError {
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!(
@@ -183,16 +144,33 @@ impl fmt::Display for MigrationError {
)
}
}
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 {
@@ -209,41 +187,66 @@ impl MigrationAuthority {
readable_schema_max: 1,
contract_evidence: None,
},
MigrationDescriptor {
version: 2,
name: "legacy-consolidation-v2",
checksum: CONSOLIDATION_SOURCE_SHA256.to_owned(),
source_digest: CONSOLIDATION_SOURCE_SHA256.to_owned(),
phase: "expand",
compatibility: "n-minus-one-readable",
owner: "crank-registry",
transactional: true,
backfill: BackfillPolicy::None,
readable_schema_min: 1,
readable_schema_max: 2,
contract_evidence: None,
},
MigrationDescriptor {
version: 3,
name: "request-trace-identity-v3",
checksum: REQUEST_TRACE_IDENTITY_SOURCE_SHA256.to_owned(),
source_digest: REQUEST_TRACE_IDENTITY_SOURCE_SHA256.to_owned(),
phase: "expand",
compatibility: "n-minus-one-readable",
owner: "crank-registry",
transactional: true,
backfill: BackfillPolicy::None,
readable_schema_min: 2,
readable_schema_max: 3,
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,
),
]
}
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
@@ -252,7 +255,6 @@ impl MigrationAuthority {
.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(()),
@@ -270,7 +272,6 @@ impl MigrationAuthority {
)),
}
}
pub async fn apply(pool: &PgPool) -> Result<MigrationApplyResult, MigrationError> {
Self::validate_sequence()?;
let mut transaction = pool
@@ -296,7 +297,6 @@ impl MigrationAuthority {
MigrationError::storage("apply.lock")
}
})?;
let before = inspect(&mut transaction).await?;
let from = match before {
MigrationPreflight::Current { version } => {
@@ -308,7 +308,6 @@ impl MigrationAuthority {
}
MigrationPreflight::MigrationRequired { current, .. } => current,
};
if from == 0 {
create_core_ledger(&mut transaction).await?;
apply_baseline(&mut transaction).await.map_err(|_| {
@@ -335,14 +334,36 @@ impl MigrationAuthority {
)
})?;
}
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?;
}
transaction
.commit()
.await
@@ -353,11 +374,9 @@ impl MigrationAuthority {
})
}
}
fn sha256_hex(bytes: &[u8]) -> String {
format!("{:x}", Sha256::digest(bytes))
}
#[cfg(test)]
fn baseline_source_digest() -> String {
let source = include_str!("baseline_v1.rs");
@@ -369,7 +388,6 @@ fn baseline_source_digest() -> String {
.expect("baseline end marker must exist");
sha256_hex(baseline.as_bytes())
}
fn validate_descriptors(descriptors: &[MigrationDescriptor]) -> Result<(), MigrationError> {
if descriptors.is_empty() || descriptors.len() > 1_024 {
return Err(MigrationError::new(
@@ -461,6 +479,19 @@ fn validate_descriptors(descriptors: &[MigrationDescriptor]) -> Result<(), Migra
|| sha256_hex(CONSOLIDATION_SOURCE.as_bytes()) != CONSOLIDATION_SOURCE_SHA256
|| sha256_hex(REQUEST_TRACE_IDENTITY_SOURCE.as_bytes())
!= REQUEST_TRACE_IDENTITY_SOURCE_SHA256
|| sha256_hex(OPERATION_LIFECYCLE_SOURCE.as_bytes()) != OPERATION_LIFECYCLE_SOURCE_SHA256
|| sha256_hex(execution_outcome_v5::SOURCE.as_bytes())
!= execution_outcome_v5::SOURCE_SHA256
|| sha256_hex(platform_key_name_reuse_v6::SOURCE.as_bytes())
!= platform_key_name_reuse_v6::SOURCE_SHA256
|| sha256_hex(master_key_identity_v7::SOURCE.as_bytes())
!= master_key_identity_v7::SOURCE_SHA256
|| sha256_hex(admin_auth_lifecycle_v8::SOURCE.as_bytes())
!= admin_auth_lifecycle_v8::SOURCE_SHA256
|| sha256_hex(agent_catalog_lifecycle_v9::SOURCE.as_bytes())
!= agent_catalog_lifecycle_v9::SOURCE_SHA256
|| sha256_hex(approval_side_effects_v10::SOURCE.as_bytes())
!= approval_side_effects_v10::SOURCE_SHA256
{
return Err(MigrationError::new(
"invalid_contract",
@@ -471,11 +502,9 @@ fn validate_descriptors(descriptors: &[MigrationDescriptor]) -> Result<(), Migra
}
Ok(())
}
async fn inspect(connection: &mut PgConnection) -> Result<MigrationPreflight, MigrationError> {
let core_exists = relation_exists(connection, "__crank_core_migrations").await?;
let canonical_exists = relation_exists(connection, "__crank_migrations").await?;
if !core_exists {
let mut owned_exists = canonical_exists;
for relation in OWNED_RELATIONS {
@@ -495,18 +524,15 @@ async fn inspect(connection: &mut PgConnection) -> Result<MigrationPreflight, Mi
target: CURRENT_VERSION,
});
}
validate_core_ledger(connection).await?;
validate_required_relations(connection, BASELINE_RELATIONS, 1).await?;
validate_required_relations(connection, owned_relations::BASELINE, 1).await?;
inspect_optional_legacy(connection).await?;
if !canonical_exists {
return Ok(MigrationPreflight::MigrationRequired {
current: 1,
target: CURRENT_VERSION,
});
}
let descriptors = MigrationAuthority::sequence();
let rows = query("select version, name, checksum, phase, compatibility from __crank_migrations order by version limit 1025")
.fetch_all(&mut *connection)
@@ -580,7 +606,6 @@ async fn inspect(connection: &mut PgConnection) -> Result<MigrationPreflight, Mi
));
}
}
let current = rows
.last()
.and_then(|row| row.try_get::<i64, _>("version").ok())
@@ -600,13 +625,19 @@ async fn inspect(connection: &mut PgConnection) -> Result<MigrationPreflight, Mi
target: CURRENT_VERSION,
})
} else {
validate_required_relations(connection, CONSOLIDATION_RELATIONS, CURRENT_VERSION).await?;
validate_required_relations(connection, owned_relations::CONSOLIDATION, CURRENT_VERSION)
.await?;
validate_required_relations(
connection,
owned_relations::ONBOARDING_PRODUCT_EVENTS,
CURRENT_VERSION,
)
.await?;
validate_schema_fingerprint(connection, CURRENT_VERSION).await?;
validate_legacy_audit(connection).await?;
Ok(MigrationPreflight::Current { version: current })
}
}
async fn validate_core_ledger(connection: &mut PgConnection) -> Result<(), MigrationError> {
let rows = query("select version, description, checksum from __crank_core_migrations order by version limit 2")
.fetch_all(connection)
@@ -642,7 +673,6 @@ async fn validate_core_ledger(connection: &mut PgConnection) -> Result<(), Migra
}
Ok(())
}
async fn inspect_optional_legacy(connection: &mut PgConnection) -> Result<(), MigrationError> {
let mcp_ledger = relation_exists(connection, "__crank_mcp_migrations").await?;
let mcp_sessions = relation_exists(connection, "mcp_transport_sessions").await?;
@@ -749,7 +779,6 @@ async fn inspect_optional_legacy(connection: &mut PgConnection) -> Result<(), Mi
}
Ok(())
}
async fn validate_legacy_audit(connection: &mut PgConnection) -> Result<(), MigrationError> {
let rows = query(
"select source, source_version, source_checksum
@@ -800,7 +829,6 @@ async fn validate_legacy_audit(connection: &mut PgConnection) -> Result<(), Migr
}
Ok(())
}
async fn create_core_ledger(
transaction: &mut Transaction<'_, sqlx::Postgres>,
) -> Result<(), MigrationError> {
@@ -824,7 +852,6 @@ async fn create_core_ledger(
})?;
Ok(())
}
async fn apply_consolidation(
transaction: &mut Transaction<'_, sqlx::Postgres>,
) -> Result<(), MigrationError> {
@@ -883,7 +910,6 @@ async fn apply_consolidation(
})?;
Ok(())
}
async fn apply_request_trace_identity(
transaction: &mut Transaction<'_, sqlx::Postgres>,
) -> Result<(), MigrationError> {
@@ -920,7 +946,42 @@ async fn apply_request_trace_identity(
})?;
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;