//! V24 schema guard: authoritative execution admission state (Story 4.1, FR-21/FR-24). //! //! Схема V24 либо полностью отсутствует (миграция ещё не применена), либо присутствует ровно в //! ожидаемой форме: controller-row с weighted round-robin cursor и bounded entries с закрытым //! словарём mode/policy_mode/state, уникальным owner token и индексами квот. use sqlx::{PgConnection, Row, query}; use super::authority::MigrationError; use super::schema_guard::relation_exists; const CONTROLLERS: &str = "execution_admission_controllers"; const ENTRIES: &str = "execution_admission_entries"; const OWNED_RELATIONS: &[&str] = &[CONTROLLERS, ENTRIES]; const CONTROLLER_COLUMNS: &[(&str, &str, bool)] = &[ ("workspace_id", "text", false), ("cursor_agent", "text", true), ("cursor_agent_credit", "integer", false), ("cursor_tool", "text", true), ("cursor_tool_credit", "integer", false), ("updated_at", "timestamp with time zone", false), ]; const ENTRY_COLUMNS: &[(&str, &str, bool)] = &[ ("ticket_id", "bigint", false), ("workspace_id", "text", false), ("agent_key", "text", false), ("operation_id", "text", false), ("operation_version", "integer", false), ("mode", "text", false), ("policy_mode", "text", false), ("state", "text", false), ("owner_token", "text", false), ("fingerprint", "text", false), ("created_at", "timestamp with time zone", false), ("expires_at", "timestamp with time zone", false), ("granted_at", "timestamp with time zone", true), ]; /// V25 adds the nullable Task dispatch-intent link to the same reserved row. At version 24 the /// column must not exist yet, so the guard validates the shape of the version it describes. fn entry_columns(current_version: i64) -> Vec<(&'static str, &'static str, bool)> { let mut columns = ENTRY_COLUMNS.to_vec(); if current_version >= 25 { columns.push(("task_id", "uuid", true)); } columns } fn constraint_count(table: &str, current_version: i64) -> Option { match table { CONTROLLERS => Some(4), ENTRIES if current_version >= 25 => Some(12), ENTRIES => Some(11), _ => None, } } const UNIQUE_INDEXES: &[&str] = &["execution_admission_entries_owner_uidx"]; fn v24_error(stage: &'static str) -> MigrationError { MigrationError::new( "partial_sequence", stage, Some(24), "restore_known_good_backup", ) } /// Схема V24 отсутствует целиком (для current_version < 24). pub(super) async fn validate_v24_absent( connection: &mut PgConnection, ) -> Result { for relation in OWNED_RELATIONS { if relation_exists(connection, relation).await? { return Ok(false); } } for index in UNIQUE_INDEXES { if index_exists(connection, index).await? { return Ok(false); } } Ok(true) } /// Схема V24 присутствует в ожидаемой форме (для current_version >= 24). pub(super) async fn validate_v24_execution_admission( connection: &mut PgConnection, current_version: i64, ) -> Result<(), MigrationError> { for relation in OWNED_RELATIONS { if !relation_exists(connection, relation).await? { return Err(v24_error("v24.relations")); } } let tables = [ (CONTROLLERS, CONTROLLER_COLUMNS.to_vec()), (ENTRIES, entry_columns(current_version)), ]; for (table, columns) in tables { validate_columns(connection, table, &columns).await?; } for table in [CONTROLLERS, ENTRIES] { let expected = constraint_count(table, current_version).unwrap_or_default(); let count: i64 = query( "select count(*)::bigint as count 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", ) .bind(table) .fetch_one(&mut *connection) .await .map_err(|_| MigrationError::storage("preflight.schema"))? .try_get("count") .map_err(|_| MigrationError::storage("preflight.schema"))?; if count != i64::try_from(expected).unwrap_or_default() { return Err(v24_error("v24.constraints")); } } for (table, constraint) in [ (CONTROLLERS, "execution_admission_controllers_pkey"), (ENTRIES, "execution_admission_entries_pkey"), (ENTRIES, "execution_admission_entries_state_check"), ] { if !constraint_exists(connection, table, constraint).await? { return Err(v24_error("v24.constraint_missing")); } } if !normalized_expression( connection, ENTRIES, "execution_admission_entries_state_check", ) .await? .is_some_and(|expression| { super::schema_guard::enum_constraint_matches( &expression, "state", &["waiting", "executing", "reserved"], ) }) { return Err(v24_error("v24.state_vocabulary")); } for index in UNIQUE_INDEXES { let unique = index_unique(connection, index).await?; if unique != Some(true) { return Err(v24_error("v24.indexes")); } } Ok(()) } async fn validate_columns( connection: &mut PgConnection, table: &str, columns: &[(&str, &str, bool)], ) -> Result<(), MigrationError> { let count: i64 = query( "select count(*)::bigint as count from information_schema.columns where table_schema = current_schema() and table_name = $1", ) .bind(table) .fetch_one(&mut *connection) .await .map_err(|_| MigrationError::storage("preflight.schema"))? .try_get("count") .map_err(|_| MigrationError::storage("preflight.schema"))?; if count != i64::try_from(columns.len()).unwrap_or_default() { return Err(v24_error("v24.columns")); } for (column, data_type, nullable) in columns { let row = query( "select data_type, is_nullable from information_schema.columns where table_schema = current_schema() and table_name = $1 and column_name = $2", ) .bind(table) .bind(column) .fetch_optional(&mut *connection) .await .map_err(|_| MigrationError::storage("preflight.schema"))?; let valid = row.is_some_and(|row| { row.try_get::("data_type").ok().as_deref() == Some(*data_type) && row.try_get::("is_nullable").ok().as_deref() == Some(if *nullable { "YES" } else { "NO" }) }); if !valid { return Err(v24_error("v24.columns")); } } Ok(()) } async fn constraint_exists( connection: &mut PgConnection, table: &str, constraint: &str, ) -> Result { 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")) } async fn normalized_expression( connection: &mut PgConnection, table: &str, constraint: &str, ) -> Result, MigrationError> { let row = 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(&mut *connection) .await .map_err(|_| MigrationError::storage("preflight.schema"))?; Ok(row.and_then(|row| row.try_get::("expression").ok())) } async fn index_exists(connection: &mut PgConnection, index: &str) -> Result { query( "select exists ( select 1 from pg_catalog.pg_class idx join pg_catalog.pg_namespace n on n.oid = idx.relnamespace where n.nspname = current_schema() and idx.relname = $1 ) as present", ) .bind(index) .fetch_one(&mut *connection) .await .map_err(|_| MigrationError::storage("preflight.schema"))? .try_get::("present") .map_err(|_| MigrationError::storage("preflight.schema")) } async fn index_unique( connection: &mut PgConnection, index: &str, ) -> Result, MigrationError> { let row = query( "select i.indisunique, i.indisvalid from pg_catalog.pg_index i join pg_catalog.pg_class idx on idx.oid = i.indexrelid join pg_catalog.pg_namespace n on n.oid = idx.relnamespace where n.nspname = current_schema() and idx.relname = $1", ) .bind(index) .fetch_optional(&mut *connection) .await .map_err(|_| MigrationError::storage("preflight.schema"))?; Ok(row.and_then(|row| { let unique = row.try_get::("indisunique").ok()?; let valid = row.try_get::("indisvalid").ok()?; Some(unique && valid) })) }