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

@@ -26,6 +26,8 @@ pub(super) const OWNED_RELATIONS: &[&str] = &[
"agent_operation_bindings",
"secrets",
"secret_versions",
"master_key_identities",
"master_key_rotations",
"auth_profiles",
"workspace_upstreams",
"yaml_import_jobs",
@@ -77,6 +79,37 @@ const REQUIRED_COLUMNS: &[(&str, &[&str])] = &[
"expires_at",
],
),
(
"master_key_identities",
&[
"epoch",
"fingerprint",
"cipher_contract",
"status",
"backup_ref",
"created_at",
"activated_at",
"retired_at",
],
),
(
"master_key_rotations",
&[
"id",
"source_epoch",
"target_epoch",
"target_fingerprint",
"state",
"backup_ref",
"checkpoint_secret_id",
"total_secret_versions",
"processed_secret_versions",
"verified_secret_versions",
"failure_code",
"created_at",
"updated_at",
],
),
];
const REQUIRED_COLUMN_TYPES: &[(&str, &str, &str, bool)] = &[
@@ -165,6 +198,67 @@ const REQUIRED_COLUMN_TYPES: &[(&str, &str, &str, bool)] = &[
"timestamp with time zone",
true,
),
("master_key_identities", "epoch", "bigint", false),
("master_key_identities", "fingerprint", "text", false),
("master_key_identities", "cipher_contract", "text", false),
("master_key_identities", "status", "text", false),
("master_key_identities", "backup_ref", "text", true),
(
"master_key_identities",
"created_at",
"timestamp with time zone",
false,
),
(
"master_key_identities",
"activated_at",
"timestamp with time zone",
true,
),
(
"master_key_identities",
"retired_at",
"timestamp with time zone",
true,
),
("master_key_rotations", "id", "text", false),
("master_key_rotations", "source_epoch", "bigint", false),
("master_key_rotations", "target_epoch", "bigint", false),
("master_key_rotations", "target_fingerprint", "text", false),
("master_key_rotations", "state", "text", false),
("master_key_rotations", "backup_ref", "text", true),
("master_key_rotations", "checkpoint_secret_id", "text", true),
(
"master_key_rotations",
"total_secret_versions",
"bigint",
false,
),
(
"master_key_rotations",
"processed_secret_versions",
"bigint",
false,
),
(
"master_key_rotations",
"verified_secret_versions",
"bigint",
false,
),
("master_key_rotations", "failure_code", "text", true),
(
"master_key_rotations",
"created_at",
"timestamp with time zone",
false,
),
(
"master_key_rotations",
"updated_at",
"timestamp with time zone",
false,
),
];
pub(super) async fn relation_exists(
@@ -363,9 +457,397 @@ pub(super) async fn validate_schema_fingerprint(
)
.await?;
}
let lifecycle_columns = [
"name",
"display_name",
"category",
"protocol",
"security_level",
"snapshot_provenance",
"snapshot_observed_at",
"published_at",
"published_by",
];
for column in lifecycle_columns {
let present = query(
"select exists (
select 1 from information_schema.columns
where table_schema = current_schema()
and table_name = 'operation_versions'
and column_name = $1
) as present",
)
.bind(column)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
if present != (current_version >= 4) {
return Err(schema_error(current_version));
}
}
if current_version >= 4 {
for (table, trigger) in [
("operation_versions", "operation_versions_immutable_guard"),
(
"published_operations",
"published_operations_monotonic_guard",
),
("operations", "operations_latest_pointer_monotonic_guard"),
] {
let trigger_present = query(
"select exists (
select 1 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 = $1
and tg.tgname = $2
and not tg.tgisinternal
) as present",
)
.bind(table)
.bind(trigger)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
if !trigger_present {
return Err(schema_error(current_version));
}
}
}
let outcome_columns = [
"operation_version",
"execution_stage",
"execution_error_code",
"retryability",
"outcome_certainty",
];
for column in outcome_columns {
let row = query(
"select data_type, is_nullable from information_schema.columns
where table_schema = current_schema()
and table_name = 'invocation_logs'
and column_name = $1",
)
.bind(column)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
if current_version < 5 {
if row.is_some() {
return Err(schema_error(current_version));
}
} else {
let expected_type = if column == "operation_version" {
"integer"
} else {
"text"
};
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("data_type").ok().as_deref() == Some(expected_type)
&& row.try_get::<String, _>("is_nullable").ok().as_deref() == Some("YES")
});
if !valid {
return Err(schema_error(current_version));
}
}
}
if current_version >= 5 {
validate_v5_execution_contract(connection).await?;
}
if current_version >= 6 {
validate_v6_platform_key_name_reuse(connection).await?;
}
if current_version < 7 {
let v7_relations_present = relation_exists(connection, "master_key_identities").await?
|| relation_exists(connection, "master_key_rotations").await?;
let mut v7_secret_columns_present = false;
for column in [
"master_key_epoch",
"target_ciphertext",
"target_key_version",
"target_master_key_epoch",
] {
v7_secret_columns_present |=
column_exists(connection, "secret_versions", column).await?;
}
if v7_relations_present || v7_secret_columns_present {
return Err(schema_error(current_version));
}
} else {
super::schema_guard_v7::validate_v7_master_key_identity(connection).await?;
}
if current_version < 8 {
let v8_relations_present = relation_exists(connection, "admin_bootstrap_contracts").await?
|| relation_exists(connection, "admin_login_backoff").await?
|| relation_exists(connection, "admin_security_audit_events").await?;
let v8_session_columns_present = column_exists(connection, "user_sessions", "csrf_hash")
.await?
|| column_exists(connection, "user_sessions", "revoked_at").await?;
if v8_relations_present || v8_session_columns_present {
return Err(schema_error(current_version));
}
} else {
super::schema_guard_v8::validate_v8_admin_auth_lifecycle(connection).await?;
}
if current_version < 9 {
if !super::schema_guard_v9::validate_v9_absent(connection).await? {
return Err(schema_error(current_version));
}
} else {
super::schema_guard_v9::validate_v9_agent_catalog_lifecycle(connection).await?;
}
if current_version < 10 {
if !super::schema_guard_v10::validate_v10_absent(connection).await? {
return Err(schema_error(current_version));
}
} else {
super::schema_guard_v10::validate_v10_approval_side_effects(connection).await?;
}
if current_version < 11 {
if !super::schema_guard_v11::validate_v11_absent(connection).await? {
return Err(schema_error(current_version));
}
} else {
super::schema_guard_v11::validate_v11_onboarding_product_events(connection).await?;
}
Ok(())
}
pub(super) async fn column_exists(
connection: &mut PgConnection,
table: &str,
column: &str,
) -> Result<bool, MigrationError> {
query(
"select exists (
select 1 from information_schema.columns
where table_schema = current_schema()
and table_name = $1
and column_name = $2
) as present",
)
.bind(table)
.bind(column)
.fetch_one(connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))
}
async fn validate_v5_execution_contract(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
let operation_version = constraint_expression(
connection,
"invocation_logs",
"invocation_logs_operation_version_check",
)
.await?;
if normalize_definition(&operation_version) != "operation_versionisnulloroperation_version>0" {
return Err(schema_error(5));
}
for (constraint, column, allowed) in [
(
"invocation_logs_execution_stage_check",
"execution_stage",
&[
"authorization",
"input_schema",
"input_mapping",
"request_preparation",
"admission",
"adapter",
"upstream",
"output_mapping",
"output_schema",
"mandatory_persistence",
"runtime",
][..],
),
(
"invocation_logs_execution_error_code_check",
"execution_error_code",
&[
"authorization_denied",
"auth_profile_not_found",
"secret_not_found",
"secret_invalid",
"input_schema_invalid",
"input_mapping_invalid",
"prepared_request_invalid",
"execution_overloaded",
"safety_store_unavailable",
"protocol_unsupported",
"execution_mode_unsupported",
"adapter_configuration_invalid",
"outbound_target_rejected",
"upstream_auth_error",
"upstream_not_found",
"upstream_rate_limited",
"upstream_server_error",
"upstream_status_error",
"upstream_timeout",
"upstream_transport_error",
"upstream_request_too_large",
"upstream_response_too_large",
"output_mapping_invalid",
"output_schema_invalid",
"persistence_unavailable",
"runtime_internal",
"confirmation_required",
"confirmation_invalid",
"idempotency_in_progress",
"idempotency_conflict",
"idempotency_outcome_unknown",
][..],
),
(
"invocation_logs_retryability_check",
"retryability",
&[
"never",
"safe",
"after_delay",
"manual_reconcile",
"requires_confirmation",
][..],
),
(
"invocation_logs_outcome_certainty_check",
"outcome_certainty",
&["certain", "outcome_unknown"][..],
),
] {
let expression = constraint_expression(connection, "invocation_logs", constraint).await?;
if !enum_constraint_matches(&expression, column, allowed) {
return Err(schema_error(5));
}
}
validate_v5_index(connection).await
}
pub(super) async fn constraint_expression(
connection: &mut PgConnection,
table: &str,
constraint: &str,
) -> Result<String, MigrationError> {
query(
"select pg_get_expr(c.conbin, c.conrelid) as expression
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 and c.contype = 'c'",
)
.bind(table)
.bind(constraint)
.fetch_optional(connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.and_then(|row| row.try_get::<String, _>("expression").ok())
.ok_or_else(|| schema_error(5))
}
pub(super) fn enum_constraint_matches(expression: &str, column: &str, allowed: &[&str]) -> bool {
let normalized = normalize_definition(expression);
if !normalized.contains(column) || normalized.contains("ortrue") {
return false;
}
let mut values = expression
.split('\'')
.enumerate()
.filter_map(|(index, value)| (index % 2 == 1).then_some(value))
.collect::<Vec<_>>();
values.sort_unstable();
values.dedup();
let mut expected = allowed.to_vec();
expected.sort_unstable();
values == expected
}
async fn validate_v5_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, pg_get_indexdef(i.indexrelid, 1, true) as first_column,
pg_get_indexdef(i.indexrelid, 2, true) as second_column,
pg_get_indexdef(i.indexrelid, 3, true) as third_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 = 'invocation_logs_workspace_operation_version_idx'",
)
.fetch_optional(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("invocation_logs")
&& 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::<String, _>("first_column").ok().as_deref() == Some("workspace_id")
&& row.try_get::<String, _>("second_column").ok().as_deref() == Some("operation_id")
&& row.try_get::<String, _>("third_column").ok().as_deref() == Some("operation_version")
&& row
.try_get::<String, _>("predicate")
.ok()
.is_some_and(|value| normalize_definition(&value) == "operation_versionisnotnull")
});
if valid { Ok(()) } else { Err(schema_error(5)) }
}
async fn validate_v6_platform_key_name_reuse(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
if relation_exists(connection, "platform_api_keys_workspace_name_idx").await? {
return Err(schema_error(6));
}
let row = query(
"select t.relname as table_name, am.amname as access_method, i.indisvalid, i.indisready,
i.indisunique, 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 = 'platform_api_keys_workspace_name_active_idx'",
)
.fetch_optional(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("platform_api_keys")
&& 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(true)
&& row.try_get::<String, _>("first_column").ok().as_deref() == Some("workspace_id")
&& row.try_get::<String, _>("second_column").ok().as_deref() == Some("name")
&& row
.try_get::<String, _>("predicate")
.ok()
.is_some_and(|value| {
matches!(
normalize_definition(&value).as_str(),
"status<>'deleted'::text" | "status!='deleted'::text"
)
})
});
if valid { Ok(()) } else { Err(schema_error(6)) }
}
async fn named_constraint_exists(
connection: &mut PgConnection,
table: &str,
@@ -433,7 +915,7 @@ async fn validate_index(
if valid { Ok(()) } else { Err(schema_error(3)) }
}
fn normalize_definition(value: &str) -> String {
pub(super) fn normalize_definition(value: &str) -> String {
value
.chars()
.filter(|character| !character.is_ascii_whitespace() && !matches!(character, '(' | ')'))
@@ -441,7 +923,7 @@ fn normalize_definition(value: &str) -> String {
.collect()
}
fn schema_error(version: i64) -> MigrationError {
pub(super) fn schema_error(version: i64) -> MigrationError {
MigrationError::new(
"partial_sequence",
"preflight.schema",