feat(epic4): исполнять durable Task через PG lease/fence и восстанавливать после сбоев (Story 4.3)
CI / UI Checks (pull_request) Successful in 15s
CI / Rust Checks (pull_request) Failing after 4m58s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Failing after 1s
CI / Deploy (pull_request) Skipped
CI / UI Checks (pull_request) Successful in 15s
CI / Rust Checks (pull_request) Failing after 4m58s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Failing after 1s
CI / Deploy (pull_request) Skipped
mcp-server запускает сохранённые фоновые задачи: захват по PostgreSQL lease с fence-токеном, зашифрованный input и повторная проверка доступа до сетевого вызова, checkpoint с AttemptID до dispatch и восстановление только по PG. Устаревший worker не может зафиксировать результат. Добавлены миграции v26–v28 (V25 не меняется), guard их отсутствия в старой схеме, метрики/трассы попыток (attempt_trace) и остановка до отправки запроса: стоп в окне после checkpoint и до permit завершает задачу как failed(shutdown_before_dispatch) без сетевых вызовов, соседние queued-задачи остаются доступными. Retry-попытки получают отдельные дочерние spans с durable current_attempt_id. Shared admission/fairness из Story 4.1 сохранены. Проверки: durable_tasks 13/13, stages 11/11 (retry 5), runtime lib 47, bin shutdown 1, registry tasks 16, admission 11, migrations 58 (независимая QA и исходный runtime-прогон), точный exact-head CI остаётся обязательным.
This commit is contained in:
1 parent
6df6ffac4e
commit
f9f8c625d1
52 files changed
+5142
-232
No files matched your search
@@ -7,6 +7,9 @@ mod artifact_metadata_v12;
|
||||
mod authority;
|
||||
mod baseline_v1;
|
||||
mod durable_tasks_v25;
|
||||
mod durable_tasks_v26;
|
||||
mod durable_tasks_v27;
|
||||
mod durable_tasks_v28;
|
||||
mod execution_admission_v24;
|
||||
mod execution_outcome_v5;
|
||||
mod import_plan_v14;
|
||||
@@ -39,6 +42,9 @@ mod schema_guard_v22;
|
||||
mod schema_guard_v23;
|
||||
mod schema_guard_v24;
|
||||
mod schema_guard_v25;
|
||||
mod schema_guard_v26;
|
||||
mod schema_guard_v27;
|
||||
mod schema_guard_v28;
|
||||
mod schema_guard_v7;
|
||||
mod schema_guard_v8;
|
||||
mod schema_guard_v9;
|
||||
|
||||
@@ -5,6 +5,9 @@ use super::approval_side_effects_v10;
|
||||
use super::artifact_cleanup_indexes_v13;
|
||||
use super::artifact_metadata_v12;
|
||||
use super::durable_tasks_v25;
|
||||
use super::durable_tasks_v26;
|
||||
use super::durable_tasks_v27;
|
||||
use super::durable_tasks_v28;
|
||||
use super::execution_admission_v24;
|
||||
use super::execution_outcome_v5;
|
||||
use super::import_plan_v14;
|
||||
@@ -41,9 +44,10 @@ use preflight::*;
|
||||
use contract::baseline_source_digest;
|
||||
use contract::validate_descriptors;
|
||||
const MIGRATION_LOCK_ID: i64 = 0x4352_414E_4B4D_4947;
|
||||
const CURRENT_VERSION: i64 = 25;
|
||||
const CURRENT_VERSION: i64 = 28;
|
||||
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, 24, 25,
|
||||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
|
||||
27, 28,
|
||||
];
|
||||
const BASELINE_SOURCE_SHA256: &str =
|
||||
"eb1656fc5b4b5be9ee390d237d1d58e4b2274ae5ba9b7ba06a2f3f860dfda675";
|
||||
@@ -344,6 +348,24 @@ impl MigrationAuthority {
|
||||
durable_tasks_v25::SOURCE_SHA256,
|
||||
24,
|
||||
),
|
||||
expand_descriptor(
|
||||
26,
|
||||
durable_tasks_v26::NAME,
|
||||
durable_tasks_v26::SOURCE_SHA256,
|
||||
25,
|
||||
),
|
||||
expand_descriptor(
|
||||
27,
|
||||
durable_tasks_v27::NAME,
|
||||
durable_tasks_v27::SOURCE_SHA256,
|
||||
26,
|
||||
),
|
||||
expand_descriptor(
|
||||
28,
|
||||
durable_tasks_v28::NAME,
|
||||
durable_tasks_v28::SOURCE_SHA256,
|
||||
27,
|
||||
),
|
||||
]
|
||||
}
|
||||
pub fn validate_sequence() -> Result<(), MigrationError> {
|
||||
@@ -509,6 +531,15 @@ impl MigrationAuthority {
|
||||
if from < 25 {
|
||||
durable_tasks_v25::apply(&mut transaction, &Self::sequence()[24]).await?;
|
||||
}
|
||||
if from < 26 {
|
||||
durable_tasks_v26::apply(&mut transaction, &Self::sequence()[25]).await?;
|
||||
}
|
||||
if from < 27 {
|
||||
durable_tasks_v27::apply(&mut transaction, &Self::sequence()[26]).await?;
|
||||
}
|
||||
if from < 28 {
|
||||
durable_tasks_v28::apply(&mut transaction, &Self::sequence()[27]).await?;
|
||||
}
|
||||
match inspect(&mut transaction).await? {
|
||||
MigrationPreflight::Current {
|
||||
version: CURRENT_VERSION,
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
use sqlx::{Postgres, Transaction, query};
|
||||
|
||||
use super::authority::{MigrationDescriptor, MigrationError};
|
||||
|
||||
pub(super) const NAME: &str = "durable-tasks-v26";
|
||||
pub(super) const SOURCE: &str = include_str!("durable_tasks_v26.sql");
|
||||
pub(super) const SOURCE_SHA256: &str =
|
||||
"6dcbf9990deabb3984a333acbfc3cb490cfc886c2ec30093e3b46d9113616089";
|
||||
|
||||
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.durable_tasks_v26",
|
||||
Some(26),
|
||||
"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.durable_tasks_v26",
|
||||
Some(26),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
-- V26: PostgreSQL lease/fencing/CAS additions for durable background Tasks (Story 4.3).
|
||||
alter table tasks add column if not exists fence bigint not null default 0;
|
||||
alter table tasks add column if not exists lease_owner text;
|
||||
alter table tasks add column if not exists lease_until timestamptz;
|
||||
alter table tasks add column if not exists current_attempt_id text;
|
||||
alter table tasks add column if not exists dispatch_started_at timestamptz;
|
||||
@@ -0,0 +1,45 @@
|
||||
use sqlx::{Postgres, Transaction, query};
|
||||
|
||||
use super::authority::{MigrationDescriptor, MigrationError};
|
||||
|
||||
pub(super) const NAME: &str = "durable-tasks-v27";
|
||||
pub(super) const SOURCE: &str = include_str!("durable_tasks_v27.sql");
|
||||
pub(super) const SOURCE_SHA256: &str =
|
||||
"a3c5335cbf81c244359faaee993487ae132d8b3be6b9c63fa322788021273dc8";
|
||||
|
||||
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.durable_tasks_v27",
|
||||
Some(27),
|
||||
"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.durable_tasks_v27",
|
||||
Some(27),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
-- V27: encrypted executable Task input (Story 4.3).
|
||||
alter table tasks add column if not exists executable_input_ciphertext text;
|
||||
alter table tasks add column if not exists executable_input_key_version text;
|
||||
alter table tasks add column if not exists executable_input_master_key_epoch bigint;
|
||||
|
||||
alter table tasks add constraint tasks_executable_input_key_version_check check (
|
||||
executable_input_ciphertext is null
|
||||
or (executable_input_key_version is not null and octet_length(executable_input_key_version) between 1 and 64)
|
||||
);
|
||||
|
||||
alter table tasks add column if not exists target_executable_input_ciphertext text;
|
||||
alter table tasks add column if not exists target_executable_input_key_version text;
|
||||
alter table tasks add column if not exists target_executable_input_master_key_epoch bigint;
|
||||
|
||||
alter table tasks add constraint tasks_executable_input_epoch_check check (
|
||||
executable_input_ciphertext is null
|
||||
or (executable_input_master_key_epoch is not null
|
||||
and executable_input_master_key_epoch >= 1)
|
||||
);
|
||||
@@ -0,0 +1,45 @@
|
||||
use sqlx::{Postgres, Transaction, query};
|
||||
|
||||
use super::authority::{MigrationDescriptor, MigrationError};
|
||||
|
||||
pub(super) const NAME: &str = "durable-tasks-v28";
|
||||
pub(super) const SOURCE: &str = include_str!("durable_tasks_v28.sql");
|
||||
pub(super) const SOURCE_SHA256: &str =
|
||||
"4dc77739c2ea1e32a4b00abd70df0f00fd82b7cf7933372f869f2c1e997a3676";
|
||||
|
||||
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.durable_tasks_v28",
|
||||
Some(28),
|
||||
"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.durable_tasks_v28",
|
||||
Some(28),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
-- V28: typed Platform API key authority reference of a durable Task (Story 4.3).
|
||||
-- Only the immutable key identifier is stored, never the bearer secret.
|
||||
alter table tasks add column if not exists platform_api_key_id text;
|
||||
|
||||
alter table tasks add constraint tasks_platform_api_key_id_check check (
|
||||
platform_api_key_id is null
|
||||
or octet_length(platform_api_key_id) between 1 and 160
|
||||
);
|
||||
@@ -480,8 +480,40 @@ pub(super) async fn validate_schema_fingerprint(
|
||||
if !super::schema_guard_v25::validate_v25_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
} else {
|
||||
if !super::schema_guard_v26::validate_v26_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
if !super::schema_guard_v27::validate_v27_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
if !super::schema_guard_v28::validate_v28_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
} else if current_version < 26 {
|
||||
super::schema_guard_v25::validate_v25_durable_tasks(connection).await?;
|
||||
if !super::schema_guard_v26::validate_v26_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
if !super::schema_guard_v28::validate_v28_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
} else if current_version < 27 {
|
||||
super::schema_guard_v26::validate_v26_durable_tasks(connection).await?;
|
||||
if !super::schema_guard_v27::validate_v27_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
if !super::schema_guard_v28::validate_v28_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
} else if current_version < 28 {
|
||||
super::schema_guard_v26::validate_v26_base_columns(connection).await?;
|
||||
super::schema_guard_v27::validate_v27_durable_tasks(connection).await?;
|
||||
if !super::schema_guard_v28::validate_v28_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
} else {
|
||||
super::schema_guard_v26::validate_v26_base_columns(connection).await?;
|
||||
super::schema_guard_v28::validate_v28_durable_tasks(connection).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
//! V26 schema guard: lease/fencing columns for durable background Tasks (Story 4.3).
|
||||
|
||||
use sqlx::{PgConnection, Row, query};
|
||||
|
||||
use super::authority::MigrationError;
|
||||
use super::schema_guard::relation_exists;
|
||||
|
||||
const TASKS: &str = "tasks";
|
||||
|
||||
const TASK_COLUMNS: &[(&str, &str, bool)] = &[
|
||||
("task_id", "uuid", false),
|
||||
("workspace_id", "text", false),
|
||||
("owner_kind", "text", false),
|
||||
("owner_id", "text", false),
|
||||
("authorization_scope", "text", false),
|
||||
("operation_id", "text", false),
|
||||
("operation_version", "integer", false),
|
||||
("scoped_key", "text", false),
|
||||
("input_fingerprint", "text", false),
|
||||
("request_id", "text", false),
|
||||
("trace_id", "text", false),
|
||||
("traceparent", "text", false),
|
||||
("trace_sampled", "boolean", false),
|
||||
("policy_mode", "text", false),
|
||||
("approval_reference", "text", true),
|
||||
("state", "text", false),
|
||||
("version", "integer", false),
|
||||
("attempts", "integer", false),
|
||||
("input_envelope", "jsonb", false),
|
||||
("progress_envelope", "jsonb", true),
|
||||
("result_envelope", "jsonb", true),
|
||||
("error_envelope", "jsonb", true),
|
||||
("execution_deadline", "timestamp with time zone", false),
|
||||
("retain_until", "timestamp with time zone", false),
|
||||
("created_at", "timestamp with time zone", false),
|
||||
("updated_at", "timestamp with time zone", false),
|
||||
("fence", "bigint", false),
|
||||
("lease_owner", "text", true),
|
||||
("lease_until", "timestamp with time zone", true),
|
||||
("current_attempt_id", "text", true),
|
||||
("dispatch_started_at", "timestamp with time zone", true),
|
||||
];
|
||||
|
||||
fn v26_error(stage: &'static str) -> MigrationError {
|
||||
MigrationError::new(
|
||||
"partial_sequence",
|
||||
stage,
|
||||
Some(26),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) async fn validate_v26_absent(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<bool, MigrationError> {
|
||||
if relation_exists(connection, TASKS).await? {
|
||||
// delegate to v25 absent for relation mostly; V26 columns must not exist.
|
||||
for column in [
|
||||
"fence",
|
||||
"lease_owner",
|
||||
"lease_until",
|
||||
"current_attempt_id",
|
||||
"dispatch_started_at",
|
||||
] {
|
||||
if super::schema_guard::column_exists(connection, TASKS, column).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(super) async fn validate_v26_base_columns(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<(), MigrationError> {
|
||||
if !relation_exists(connection, TASKS).await? {
|
||||
return Err(v26_error("v26.relations"));
|
||||
}
|
||||
for (column, data_type, nullable) in TASK_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(TASKS)
|
||||
.bind(column)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
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" })
|
||||
});
|
||||
if !valid {
|
||||
return Err(v26_error("v26.columns"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn validate_v26_durable_tasks(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<(), MigrationError> {
|
||||
validate_v26_base_columns(connection).await?;
|
||||
let count: i64 = query(
|
||||
"select count(*)::bigint as count from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = $1",
|
||||
)
|
||||
.bind(TASKS)
|
||||
.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(TASK_COLUMNS.len()).unwrap_or_default() {
|
||||
return Err(v26_error("v26.columns"));
|
||||
}
|
||||
// Constraints/index checks inherited conceptually from V25; V26 adds columns only.
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
//! V27 schema guard: encrypted executable Task input columns (Story 4.3).
|
||||
|
||||
use sqlx::{PgConnection, Row, query};
|
||||
|
||||
use super::authority::MigrationError;
|
||||
use super::schema_guard::relation_exists;
|
||||
use super::schema_guard_v26::validate_v26_base_columns;
|
||||
|
||||
const TASKS: &str = "tasks";
|
||||
|
||||
pub(super) async fn validate_v27_absent(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<bool, MigrationError> {
|
||||
if relation_exists(connection, TASKS).await? {
|
||||
for column in [
|
||||
"executable_input_ciphertext",
|
||||
"executable_input_key_version",
|
||||
"executable_input_master_key_epoch",
|
||||
] {
|
||||
if super::schema_guard::column_exists(connection, TASKS, column).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(super) async fn validate_v27_durable_tasks(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<(), MigrationError> {
|
||||
validate_v26_base_columns(connection).await?;
|
||||
// Additional V27 columns.
|
||||
let extra = [
|
||||
("executable_input_ciphertext", "text", true),
|
||||
("executable_input_key_version", "text", true),
|
||||
("executable_input_master_key_epoch", "bigint", true),
|
||||
("target_executable_input_ciphertext", "text", true),
|
||||
("target_executable_input_key_version", "text", true),
|
||||
("target_executable_input_master_key_epoch", "bigint", true),
|
||||
];
|
||||
for (column, data_type, nullable) in extra {
|
||||
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(TASKS)
|
||||
.bind(column)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
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" })
|
||||
});
|
||||
if !valid {
|
||||
return Err(MigrationError::new(
|
||||
"partial_sequence",
|
||||
"v27.columns",
|
||||
Some(27),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
}
|
||||
// Exact total column count for version 27: 43 V26 columns + 3 V27 columns.
|
||||
let count: i64 = query(
|
||||
"select count(*)::bigint as count from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = $1",
|
||||
)
|
||||
.bind(TASKS)
|
||||
.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(37).unwrap_or_default() {
|
||||
return Err(MigrationError::new(
|
||||
"partial_sequence",
|
||||
"v27.columns",
|
||||
Some(27),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
//! V28 schema guard: typed Platform API key authority reference of a durable Task (Story 4.3).
|
||||
|
||||
use sqlx::{PgConnection, Row, query};
|
||||
|
||||
use super::authority::MigrationError;
|
||||
use super::schema_guard::relation_exists;
|
||||
|
||||
const TASKS: &str = "tasks";
|
||||
|
||||
pub(super) async fn validate_v28_absent(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<bool, MigrationError> {
|
||||
if relation_exists(connection, TASKS).await? {
|
||||
if super::schema_guard::column_exists(connection, TASKS, "platform_api_key_id").await? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(super) async fn validate_v28_durable_tasks(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<(), MigrationError> {
|
||||
// The V27 column set is still required and unchanged; V28 only appends one column.
|
||||
validate_v27_base_columns(connection).await?;
|
||||
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(TASKS)
|
||||
.bind("platform_api_key_id")
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
row.try_get::<String, _>("data_type").ok().as_deref() == Some("text")
|
||||
&& row.try_get::<String, _>("is_nullable").ok().as_deref() == Some("YES")
|
||||
});
|
||||
if !valid {
|
||||
return Err(MigrationError::new(
|
||||
"partial_sequence",
|
||||
"v28.columns",
|
||||
Some(28),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
// Exact total column count for version 28: the 37 V27 columns + 1 V28 column.
|
||||
let count: i64 = query(
|
||||
"select count(*)::bigint as count from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = $1",
|
||||
)
|
||||
.bind(TASKS)
|
||||
.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(38).unwrap_or_default() {
|
||||
return Err(MigrationError::new(
|
||||
"partial_sequence",
|
||||
"v28.columns",
|
||||
Some(28),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// V27 columns must still be exactly present before V28 is considered applied.
|
||||
async fn validate_v27_base_columns(connection: &mut PgConnection) -> Result<(), MigrationError> {
|
||||
for column in [
|
||||
"executable_input_ciphertext",
|
||||
"executable_input_key_version",
|
||||
"executable_input_master_key_epoch",
|
||||
"target_executable_input_ciphertext",
|
||||
"target_executable_input_key_version",
|
||||
"target_executable_input_master_key_epoch",
|
||||
] {
|
||||
if !super::schema_guard::column_exists(connection, TASKS, column).await? {
|
||||
return Err(MigrationError::new(
|
||||
"partial_sequence",
|
||||
"v28.columns",
|
||||
Some(28),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -577,6 +577,145 @@ pub(super) async fn insert_admission_entry(
|
||||
Ok(u64::try_from(ticket_id).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Shared grant step used by the durable Task store: grants one reserved Task intent if capacity allows,
|
||||
/// marks it `executing`, persists the weighted round-robin cursor, and returns its Task id. It reuses
|
||||
/// the same selector/capacity logic as synchronous admission so no second policy exists.
|
||||
pub(super) async fn grant_next_task(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &str,
|
||||
cursor: &AdmissionCursor,
|
||||
limits: &AdmissionLimits,
|
||||
scheduler: AdmissionSchedulerConfig,
|
||||
) -> Result<(Option<Uuid>, AdmissionCursor), AttemptError> {
|
||||
let rows = sqlx::query(
|
||||
"select ticket_id, agent_key, operation_id, task_id
|
||||
from execution_admission_entries
|
||||
where state = 'reserved' and task_id is not null
|
||||
order by ticket_id
|
||||
limit $1
|
||||
for update skip locked",
|
||||
)
|
||||
.bind(QUEUE_READ_LIMIT)
|
||||
.fetch_all(&mut **transaction)
|
||||
.await
|
||||
.map_err(AttemptError::from_sql)?;
|
||||
if rows.is_empty() {
|
||||
return Ok((None, cursor.clone()));
|
||||
}
|
||||
struct Candidate {
|
||||
entry: AdmissionQueueEntry,
|
||||
task_id: Uuid,
|
||||
}
|
||||
let mut candidates = Vec::with_capacity(rows.len());
|
||||
for row in rows {
|
||||
let ticket_id: i64 = row.try_get("ticket_id").map_err(AttemptError::from_sql)?;
|
||||
let task_id: Uuid = row.try_get("task_id").map_err(AttemptError::from_sql)?;
|
||||
candidates.push(Candidate {
|
||||
entry: AdmissionQueueEntry {
|
||||
ticket_id: u64::try_from(ticket_id).unwrap_or_default(),
|
||||
sequence: 0,
|
||||
agent_key: row.try_get("agent_key").map_err(AttemptError::from_sql)?,
|
||||
operation_id: row
|
||||
.try_get("operation_id")
|
||||
.map_err(AttemptError::from_sql)?,
|
||||
},
|
||||
task_id,
|
||||
});
|
||||
}
|
||||
let queue: Vec<AdmissionQueueEntry> = candidates.iter().map(|c| c.entry.clone()).collect();
|
||||
let Some(selection) = select_next_grant(&queue, cursor, scheduler) else {
|
||||
return Ok((None, cursor.clone()));
|
||||
};
|
||||
let head_index = selection.index;
|
||||
let head = &candidates[head_index];
|
||||
|
||||
let global_executing: i64 = sqlx::query(
|
||||
"select count(*)::bigint as count from execution_admission_entries where state = 'executing'",
|
||||
)
|
||||
.fetch_one(&mut **transaction)
|
||||
.await
|
||||
.map_err(AttemptError::from_sql)?
|
||||
.try_get("count")
|
||||
.map_err(AttemptError::from_sql)?;
|
||||
let agent_counts = sqlx::query(
|
||||
"select agent_key as key, count(*)::bigint as count
|
||||
from execution_admission_entries where state = 'executing' group by agent_key",
|
||||
)
|
||||
.fetch_all(&mut **transaction)
|
||||
.await
|
||||
.map_err(AttemptError::from_sql)?;
|
||||
let mut agent_map = std::collections::BTreeMap::new();
|
||||
for row in agent_counts {
|
||||
let key: String = row.try_get("key").map_err(AttemptError::from_sql)?;
|
||||
let count: i64 = row.try_get("count").map_err(AttemptError::from_sql)?;
|
||||
agent_map.insert(key, u64::try_from(count).unwrap_or_default());
|
||||
}
|
||||
let tool_counts = sqlx::query(
|
||||
"select operation_id as key, count(*)::bigint as count
|
||||
from execution_admission_entries where state = 'executing' group by operation_id",
|
||||
)
|
||||
.fetch_all(&mut **transaction)
|
||||
.await
|
||||
.map_err(AttemptError::from_sql)?;
|
||||
let mut tool_map = std::collections::BTreeMap::new();
|
||||
for row in tool_counts {
|
||||
let key: String = row.try_get("key").map_err(AttemptError::from_sql)?;
|
||||
let count: i64 = row.try_get("count").map_err(AttemptError::from_sql)?;
|
||||
tool_map.insert(key, u64::try_from(count).unwrap_or_default());
|
||||
}
|
||||
|
||||
if u64::try_from(global_executing).unwrap_or(u64::MAX)
|
||||
>= u64::try_from(limits.global_limit).unwrap_or(u64::MAX)
|
||||
{
|
||||
return Ok((None, cursor.clone()));
|
||||
}
|
||||
let agent_executing = agent_map
|
||||
.get(head.entry.agent_key.as_str())
|
||||
.copied()
|
||||
.unwrap_or_default();
|
||||
if agent_executing >= u64::try_from(limits.agent_limit).unwrap_or(u64::MAX) {
|
||||
return Ok((None, cursor.clone()));
|
||||
}
|
||||
let tool_executing = tool_map
|
||||
.get(head.entry.operation_id.as_str())
|
||||
.copied()
|
||||
.unwrap_or_default();
|
||||
if tool_executing >= u64::try_from(limits.tool_limit).unwrap_or(u64::MAX) {
|
||||
return Ok((None, cursor.clone()));
|
||||
}
|
||||
|
||||
sqlx::query(
|
||||
"update execution_admission_entries
|
||||
set state = 'executing', granted_at = clock_timestamp()
|
||||
where ticket_id = $1 and state = 'reserved'",
|
||||
)
|
||||
.bind(i64::try_from(head.entry.ticket_id).unwrap_or(i64::MAX))
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(AttemptError::from_sql)?;
|
||||
|
||||
sqlx::query(
|
||||
"update execution_admission_controllers
|
||||
set cursor_agent = $2,
|
||||
cursor_agent_credit = $3,
|
||||
cursor_tool = $4,
|
||||
cursor_tool_credit = $5,
|
||||
updated_at = now()
|
||||
where workspace_id = $1",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(selection.cursor.agent.as_deref())
|
||||
.bind(i32::try_from(selection.cursor.agent_credit).unwrap_or_default())
|
||||
.bind(selection.cursor.tool.as_deref())
|
||||
.bind(i32::try_from(selection.cursor.tool_credit).unwrap_or_default())
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(AttemptError::from_sql)?;
|
||||
|
||||
Ok((Some(head.task_id), selection.cursor))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) enum AttemptError {
|
||||
/// Lock or statement timeout: the transaction made no decision and the waiter retries.
|
||||
Contended,
|
||||
|
||||
@@ -170,6 +170,69 @@ impl PostgresRegistry {
|
||||
.transpose()
|
||||
}
|
||||
|
||||
/// Authoritative revalidation of the Platform API key that authorized a durable Task (Story 4.3).
|
||||
///
|
||||
/// The key is returned only when the exact immutable ID is still active, unexpired and bound to
|
||||
/// the same workspace and agent; otherwise `None`, so a worker fails closed. Only the immutable
|
||||
/// identity is supplied here — the bearer secret is never stored or re-read.
|
||||
pub async fn revalidate_platform_api_key(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
agent_id: &AgentId,
|
||||
key_id: &PlatformApiKeyId,
|
||||
) -> Result<Option<PlatformApiKeyRecord>, RegistryError> {
|
||||
let row = sqlx::query(
|
||||
"select
|
||||
k.id,
|
||||
k.workspace_id,
|
||||
k.agent_id,
|
||||
k.key_kind,
|
||||
k.name,
|
||||
k.prefix,
|
||||
k.scopes_json,
|
||||
k.status,
|
||||
k.created_at,
|
||||
k.last_used_at,
|
||||
k.expires_at,
|
||||
k.allowed_origins_json
|
||||
from platform_api_keys k
|
||||
where k.id = $1
|
||||
and k.workspace_id = $2
|
||||
and k.agent_id = $3
|
||||
and k.key_kind = 'mcp_client'
|
||||
and k.status = 'active'
|
||||
and (k.expires_at is null or k.expires_at > now())
|
||||
limit 1",
|
||||
)
|
||||
.bind(key_id.as_str())
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(agent_id.as_str())
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
|
||||
row.map(|row| {
|
||||
Ok(PlatformApiKeyRecord {
|
||||
api_key: PlatformApiKey {
|
||||
id: PlatformApiKeyId::new(row.get::<String, _>("id")),
|
||||
workspace_id: WorkspaceId::new(row.get::<String, _>("workspace_id")),
|
||||
agent_id: row.get::<Option<String>, _>("agent_id").map(AgentId::new),
|
||||
key_kind: deserialize_enum_text(&row.get::<String, _>("key_kind"), "key_kind")?,
|
||||
name: row.get("name"),
|
||||
prefix: row.get("prefix"),
|
||||
scopes: deserialize_json_value(row.get::<Value, _>("scopes_json"))?,
|
||||
status: deserialize_enum_text(&row.get::<String, _>("status"), "status")?,
|
||||
created_at: row.get("created_at"),
|
||||
last_used_at: row.get("last_used_at"),
|
||||
expires_at: row.get("expires_at"),
|
||||
allowed_origins: deserialize_json_value(
|
||||
row.get::<Value, _>("allowed_origins_json"),
|
||||
)?,
|
||||
},
|
||||
})
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub async fn get_approval_api_key_by_secret_for_agent_slug(
|
||||
&self,
|
||||
workspace_slug: &str,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::*;
|
||||
|
||||
const MASTER_KEY_PAGE_LIMIT_MAX: i64 = 10_000;
|
||||
pub(super) const MASTER_KEY_PAGE_LIMIT_MAX: i64 = 10_000;
|
||||
|
||||
impl PostgresRegistry {
|
||||
pub async fn verify_or_register_master_key_identity(
|
||||
@@ -356,12 +356,19 @@ impl PostgresRegistry {
|
||||
return Err(RegistryError::MasterKeyRotationConflict);
|
||||
}
|
||||
|
||||
let total = sqlx::query_scalar::<_, i64>(
|
||||
let secret_total = sqlx::query_scalar::<_, i64>(
|
||||
"select count(*) from secret_versions where master_key_epoch = $1",
|
||||
)
|
||||
.bind(source_epoch)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
let task_total = sqlx::query_scalar::<_, i64>(
|
||||
"select count(*) from tasks where executable_input_master_key_epoch = $1",
|
||||
)
|
||||
.bind(source_epoch)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
let total = secret_total + task_total;
|
||||
let rotation_id = format!("master-key-e{source_epoch}-to-e{target_epoch}");
|
||||
let aborted = sqlx::query(
|
||||
"select
|
||||
@@ -403,6 +410,16 @@ impl PostgresRegistry {
|
||||
.bind(target_epoch)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"update tasks
|
||||
set target_executable_input_ciphertext = null,
|
||||
target_executable_input_key_version = null,
|
||||
target_executable_input_master_key_epoch = null
|
||||
where target_executable_input_master_key_epoch = $1",
|
||||
)
|
||||
.bind(target_epoch)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"update master_key_rotations
|
||||
set state = 'running',
|
||||
@@ -662,9 +679,24 @@ impl PostgresRegistry {
|
||||
.bind(rotation.target_epoch)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"update tasks
|
||||
set executable_input_ciphertext = target_executable_input_ciphertext,
|
||||
executable_input_key_version = target_executable_input_key_version,
|
||||
executable_input_master_key_epoch = target_executable_input_master_key_epoch,
|
||||
target_executable_input_ciphertext = null,
|
||||
target_executable_input_key_version = null,
|
||||
target_executable_input_master_key_epoch = null
|
||||
where executable_input_master_key_epoch = $1
|
||||
and target_executable_input_master_key_epoch = $2",
|
||||
)
|
||||
.bind(rotation.source_epoch)
|
||||
.bind(rotation.target_epoch)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"update master_key_rotations
|
||||
set state = 'promoted',
|
||||
set state = 'promoted',
|
||||
updated_at = $2::timestamptz
|
||||
where id = $1",
|
||||
)
|
||||
@@ -697,6 +729,16 @@ impl PostgresRegistry {
|
||||
.bind(rotation.target_epoch)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"update tasks
|
||||
set target_executable_input_ciphertext = null,
|
||||
target_executable_input_key_version = null,
|
||||
target_executable_input_master_key_epoch = null
|
||||
where target_executable_input_master_key_epoch = $1",
|
||||
)
|
||||
.bind(rotation.target_epoch)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"update master_key_rotations
|
||||
set state = 'aborted',
|
||||
@@ -883,7 +925,7 @@ async fn select_active_master_key_identity_for_update(
|
||||
Ok(row.map(map_master_key_identity))
|
||||
}
|
||||
|
||||
async fn select_master_key_rotation_for_update(
|
||||
pub(super) async fn select_master_key_rotation_for_update(
|
||||
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
rotation_id: &str,
|
||||
) -> Result<MasterKeyRotationRecord, RegistryError> {
|
||||
@@ -915,16 +957,19 @@ async fn select_master_key_rotation_for_update(
|
||||
})
|
||||
}
|
||||
|
||||
async fn count_staged_rotation_targets(
|
||||
pub(super) async fn count_staged_rotation_targets(
|
||||
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
source_epoch: i64,
|
||||
target_epoch: i64,
|
||||
) -> Result<i64, RegistryError> {
|
||||
let count = sqlx::query_scalar::<_, i64>(
|
||||
"select count(*)
|
||||
from secret_versions
|
||||
where master_key_epoch = $1
|
||||
and target_master_key_epoch = $2",
|
||||
"select
|
||||
(select count(*) from secret_versions
|
||||
where master_key_epoch = $1
|
||||
and target_master_key_epoch = $2) +
|
||||
(select count(*) from tasks
|
||||
where executable_input_master_key_epoch = $1
|
||||
and target_executable_input_master_key_epoch = $2)",
|
||||
)
|
||||
.bind(source_epoch)
|
||||
.bind(target_epoch)
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
//! Task ciphertext paging/staging of the master-key rotation (Story 4.3).
|
||||
//!
|
||||
//! Extracted from `master_key.rs` without logic changes so that module stays within the
|
||||
//! code-health line limit; the operations and their SQL are unchanged.
|
||||
|
||||
use super::master_key::{
|
||||
MASTER_KEY_PAGE_LIMIT_MAX, count_staged_rotation_targets, select_master_key_rotation_for_update,
|
||||
};
|
||||
use super::*;
|
||||
|
||||
fn map_master_key_task_version(
|
||||
row: sqlx::postgres::PgRow,
|
||||
) -> Result<MasterKeyTaskVersion, RegistryError> {
|
||||
Ok(MasterKeyTaskVersion {
|
||||
task_id: row.get::<String, _>("task_id"),
|
||||
ciphertext: row
|
||||
.get::<Option<String>, _>("executable_input_ciphertext")
|
||||
.unwrap_or_default(),
|
||||
key_version: row
|
||||
.get::<Option<String>, _>("executable_input_key_version")
|
||||
.unwrap_or_default(),
|
||||
epoch: row
|
||||
.get::<Option<i64>, _>("executable_input_master_key_epoch")
|
||||
.unwrap_or_default(),
|
||||
target_ciphertext: row.get::<Option<String>, _>("target_executable_input_ciphertext"),
|
||||
target_key_version: row.get::<Option<String>, _>("target_executable_input_key_version"),
|
||||
target_epoch: row.get::<Option<i64>, _>("target_executable_input_master_key_epoch"),
|
||||
})
|
||||
}
|
||||
|
||||
impl PostgresRegistry {
|
||||
pub async fn list_tasks_for_master_key_epoch_page(
|
||||
&self,
|
||||
epoch: i64,
|
||||
after_task_id: Option<&str>,
|
||||
limit: i64,
|
||||
) -> Result<Vec<MasterKeyTaskVersion>, RegistryError> {
|
||||
if epoch < 1 || !(1..=MASTER_KEY_PAGE_LIMIT_MAX).contains(&limit) {
|
||||
return Err(RegistryError::InvalidMasterKeyIdentity);
|
||||
}
|
||||
let rows = sqlx::query(
|
||||
"select task_id::text as task_id, executable_input_ciphertext, executable_input_key_version, executable_input_master_key_epoch, target_executable_input_ciphertext, target_executable_input_key_version, target_executable_input_master_key_epoch from tasks where executable_input_master_key_epoch = $1 and ($2::text is null or task_id::text > $2::text) order by task_id asc limit $3",
|
||||
)
|
||||
.bind(epoch)
|
||||
.bind(after_task_id)
|
||||
.bind(limit)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
rows.into_iter().map(map_master_key_task_version).collect()
|
||||
}
|
||||
|
||||
pub async fn list_target_tasks_for_master_key_rotation_page(
|
||||
&self,
|
||||
target_epoch: i64,
|
||||
after_task_id: Option<&str>,
|
||||
limit: i64,
|
||||
) -> Result<Vec<MasterKeyTaskVersion>, RegistryError> {
|
||||
if target_epoch < 1 || !(1..=MASTER_KEY_PAGE_LIMIT_MAX).contains(&limit) {
|
||||
return Err(RegistryError::InvalidMasterKeyIdentity);
|
||||
}
|
||||
let rows = sqlx::query(
|
||||
"select task_id::text as task_id, executable_input_ciphertext, executable_input_key_version, executable_input_master_key_epoch, target_executable_input_ciphertext, target_executable_input_key_version, target_executable_input_master_key_epoch from tasks where target_executable_input_master_key_epoch = $1 and ($2::text is null or task_id::text > $2::text) order by task_id asc limit $3",
|
||||
)
|
||||
.bind(target_epoch)
|
||||
.bind(after_task_id)
|
||||
.bind(limit)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
rows.into_iter().map(map_master_key_task_version).collect()
|
||||
}
|
||||
|
||||
pub async fn stage_master_key_rotation_task_ciphertext(
|
||||
&self,
|
||||
rotation_id: &str,
|
||||
task_id: &str,
|
||||
source_epoch: i64,
|
||||
target_ciphertext: &str,
|
||||
target_key_version: &str,
|
||||
target_epoch: i64,
|
||||
now: &OffsetDateTime,
|
||||
) -> Result<MasterKeyRotationRecord, RegistryError> {
|
||||
let mut tx = self.pool.begin().await?;
|
||||
let rotation = select_master_key_rotation_for_update(&mut tx, rotation_id).await?;
|
||||
if rotation.state != "running"
|
||||
|| rotation.source_epoch != source_epoch
|
||||
|| rotation.target_epoch != target_epoch
|
||||
{
|
||||
return Err(RegistryError::MasterKeyRotationConflict);
|
||||
}
|
||||
let result = sqlx::query(
|
||||
"update tasks
|
||||
set target_executable_input_ciphertext = $3,
|
||||
target_executable_input_key_version = $4,
|
||||
target_executable_input_master_key_epoch = $5
|
||||
where task_id::text = $1
|
||||
and executable_input_master_key_epoch = $2
|
||||
and (
|
||||
target_executable_input_master_key_epoch is null
|
||||
or target_executable_input_master_key_epoch = $5
|
||||
)
|
||||
and (
|
||||
target_executable_input_ciphertext is null
|
||||
or target_executable_input_ciphertext = $3
|
||||
)",
|
||||
)
|
||||
.bind(task_id)
|
||||
.bind(source_epoch)
|
||||
.bind(target_ciphertext)
|
||||
.bind(target_key_version)
|
||||
.bind(target_epoch)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
if result.rows_affected() != 1 {
|
||||
return Err(RegistryError::MasterKeyRotationConflict);
|
||||
}
|
||||
let processed = count_staged_rotation_targets(&mut tx, source_epoch, target_epoch).await?;
|
||||
sqlx::query(
|
||||
"update master_key_rotations
|
||||
set checkpoint_secret_id = checkpoint_secret_id,
|
||||
processed_secret_versions = $2,
|
||||
updated_at = $3::timestamptz
|
||||
where id = $1",
|
||||
)
|
||||
.bind(rotation_id)
|
||||
.bind(processed)
|
||||
.bind(now)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
let updated = select_master_key_rotation_for_update(&mut tx, rotation_id).await?;
|
||||
tx.commit().await?;
|
||||
Ok(updated)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MasterKeyTaskVersion {
|
||||
pub task_id: String,
|
||||
pub ciphertext: String,
|
||||
pub key_version: String,
|
||||
pub epoch: i64,
|
||||
pub target_ciphertext: Option<String>,
|
||||
pub target_key_version: Option<String>,
|
||||
pub target_epoch: Option<i64>,
|
||||
}
|
||||
@@ -10,6 +10,7 @@ mod auth;
|
||||
mod connection;
|
||||
mod import_job;
|
||||
mod master_key;
|
||||
mod master_key_tasks;
|
||||
mod observability;
|
||||
mod onboarding;
|
||||
mod onboarding_import;
|
||||
|
||||
@@ -13,9 +13,9 @@
|
||||
use async_trait::async_trait;
|
||||
use crank_core::{
|
||||
AdmissionMode, AdmissionRequest, AdmissionScope, ApprovalEvidence, NoTasksFallback,
|
||||
TaskAcceptRequest, TaskAcceptance, TaskAccess, TaskEnvelope, TaskError, TaskFinishRequest,
|
||||
TaskId, TaskOwnerKind, TaskPins, TaskPurgeReport, TaskRecord, TaskState, TaskStore,
|
||||
TaskSupportIds, ToolExecutionMode,
|
||||
PlatformApiKeyId, TaskAcceptRequest, TaskAcceptance, TaskAccess, TaskEnvelope, TaskError,
|
||||
TaskFinishRequest, TaskId, TaskLease, TaskOwnerKind, TaskPins, TaskPurgeReport, TaskRecord,
|
||||
TaskState, TaskStore, TaskSupportIds, ToolExecutionMode,
|
||||
};
|
||||
use serde_json::Value;
|
||||
use sqlx::{PgPool, Postgres, Row, Transaction};
|
||||
@@ -27,10 +27,14 @@ use super::admission::{
|
||||
};
|
||||
|
||||
const TASK_PROJECTION: &str = "task_id, state, workspace_id, owner_kind, owner_id,
|
||||
authorization_scope, operation_id, input_fingerprint, operation_version, policy_mode,
|
||||
authorization_scope, platform_api_key_id, operation_id, input_fingerprint, operation_version,
|
||||
policy_mode,
|
||||
approval_reference,
|
||||
request_id, trace_id, traceparent, trace_sampled, input_envelope, progress_envelope,
|
||||
result_envelope, error_envelope, attempts, version,
|
||||
result_envelope, error_envelope, attempts, fence, lease_owner, lease_until,
|
||||
(extract(epoch from lease_until) * 1000)::bigint as lease_until_ms,
|
||||
current_attempt_id, dispatch_started_at,
|
||||
(extract(epoch from dispatch_started_at) * 1000)::bigint as dispatch_started_at_ms, version,
|
||||
(extract(epoch from execution_deadline) * 1000)::bigint as execution_deadline_ms,
|
||||
(extract(epoch from retain_until) * 1000)::bigint as retain_until_ms,
|
||||
(extract(epoch from created_at) * 1000)::bigint as created_ms,
|
||||
@@ -40,6 +44,7 @@ const TASK_PROJECTION: &str = "task_id, state, workspace_id, owner_kind, owner_i
|
||||
pub struct PostgresTaskStore {
|
||||
pool: PgPool,
|
||||
limits: AdmissionLimits,
|
||||
scheduler: crank_core::AdmissionSchedulerConfig,
|
||||
}
|
||||
|
||||
impl PostgresTaskStore {
|
||||
@@ -54,7 +59,11 @@ impl PostgresTaskStore {
|
||||
scheduler
|
||||
.validate()
|
||||
.map_err(|error| TaskError::invalid(error.to_string()))?;
|
||||
Ok(Self { pool, limits })
|
||||
Ok(Self {
|
||||
pool,
|
||||
limits,
|
||||
scheduler,
|
||||
})
|
||||
}
|
||||
|
||||
fn unavailable(error: impl std::fmt::Display) -> TaskError {
|
||||
@@ -151,6 +160,20 @@ impl TaskStore for PostgresTaskStore {
|
||||
async fn accept(&self, request: TaskAcceptRequest) -> Result<TaskAcceptance, TaskError> {
|
||||
request.validate()?;
|
||||
let mut transaction = self.start().await?;
|
||||
super::master_key::ensure_no_active_master_key_rotation(&mut transaction)
|
||||
.await
|
||||
.map_err(|error| match error {
|
||||
crate::RegistryError::Storage(_) => TaskError::unavailable(error.to_string()),
|
||||
_ => TaskError::StateConflict,
|
||||
})?;
|
||||
if let Some(epoch) = request.executable_input_master_key_epoch {
|
||||
super::master_key::ensure_active_master_key_epoch(&mut transaction, epoch)
|
||||
.await
|
||||
.map_err(|error| match error {
|
||||
crate::RegistryError::Storage(_) => TaskError::unavailable(error.to_string()),
|
||||
_ => TaskError::StateConflict,
|
||||
})?;
|
||||
}
|
||||
let outcome = self.accept_locked(&mut transaction, &request).await;
|
||||
match outcome {
|
||||
Ok(Accepted::Created(acceptance) | Accepted::Replayed(acceptance)) => {
|
||||
@@ -252,6 +275,7 @@ impl TaskStore for PostgresTaskStore {
|
||||
where task_id = $4 and workspace_id = $5 and owner_kind = $6
|
||||
and owner_id = $7 and authorization_scope = $8
|
||||
and state = $9 and version = $10
|
||||
and (lease_owner is null or fence = 0)
|
||||
returning {TASK_PROJECTION}"
|
||||
)))
|
||||
.bind(request.target_state.as_str())
|
||||
@@ -285,6 +309,12 @@ impl TaskStore for PostgresTaskStore {
|
||||
async fn purge_expired(&self, batch: u32) -> Result<TaskPurgeReport, TaskError> {
|
||||
let batch = i64::from(batch.clamp(1, crank_core::TASK_PURGE_BATCH_LIMIT));
|
||||
let mut transaction = self.start().await?;
|
||||
super::master_key::ensure_no_active_master_key_rotation(&mut transaction)
|
||||
.await
|
||||
.map_err(|error| match error {
|
||||
crate::RegistryError::Storage(_) => TaskError::unavailable(error.to_string()),
|
||||
_ => TaskError::StateConflict,
|
||||
})?;
|
||||
let expired = sqlx::query(
|
||||
"with expired as (
|
||||
update tasks
|
||||
@@ -295,6 +325,7 @@ impl TaskStore for PostgresTaskStore {
|
||||
where task_id in (
|
||||
select task_id from tasks
|
||||
where state = 'queued' and execution_deadline <= now()
|
||||
and lease_owner is null
|
||||
order by task_id
|
||||
limit $1
|
||||
)
|
||||
@@ -332,6 +363,351 @@ impl TaskStore for PostgresTaskStore {
|
||||
expired_terminal: purged.rows_affected(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn claim_batch(
|
||||
&self,
|
||||
owner: &str,
|
||||
batch_limit: u32,
|
||||
lease_ms: i64,
|
||||
) -> Result<Vec<TaskLease>, TaskError> {
|
||||
let batch = (batch_limit.clamp(1, 64)) as usize;
|
||||
// A checkpointed attempt is never redispatched: once its lease expires the outbound outcome
|
||||
// is uncertain, so it resolves to outcome_unknown and releases its admission slot. Story 4.4
|
||||
// owns any later retry/cancellation of that uncertain outcome.
|
||||
let mut transaction = self.start().await?;
|
||||
sqlx::query(
|
||||
"with candidates as (
|
||||
select task_id from tasks
|
||||
where state = 'working' and lease_owner is not null
|
||||
and current_attempt_id is not null
|
||||
and lease_until < clock_timestamp()
|
||||
order by task_id
|
||||
limit 64
|
||||
), resolved as (
|
||||
update tasks
|
||||
set state = 'outcome_unknown',
|
||||
lease_owner = null,
|
||||
lease_until = null,
|
||||
version = version + 1,
|
||||
updated_at = now()
|
||||
where task_id in (select task_id from candidates)
|
||||
and state = 'working'
|
||||
returning task_id
|
||||
)
|
||||
delete from execution_admission_entries
|
||||
where task_id in (select task_id from resolved)",
|
||||
)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
|
||||
// A crash before the durable dispatch checkpoint left the Task queued for execution: its
|
||||
// admission intent is re-armed as reserved and the Task becomes claimable again. Recovery is
|
||||
// bounded by the <=30s lease expiry, inside the 60s story budget.
|
||||
sqlx::query(
|
||||
"with candidates as (
|
||||
select task_id from tasks
|
||||
where state = 'working' and lease_owner is not null
|
||||
and current_attempt_id is null
|
||||
and lease_until < clock_timestamp()
|
||||
order by task_id
|
||||
limit 64
|
||||
), requeued as (
|
||||
update tasks
|
||||
set state = 'queued',
|
||||
lease_owner = null,
|
||||
lease_until = null,
|
||||
version = version + 1,
|
||||
updated_at = now()
|
||||
where task_id in (select task_id from candidates)
|
||||
and state = 'working'
|
||||
returning task_id
|
||||
)
|
||||
update execution_admission_entries
|
||||
set state = 'reserved', granted_at = null
|
||||
where task_id in (select task_id from requeued) and state = 'executing'",
|
||||
)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
transaction.commit().await.map_err(Self::unavailable)?;
|
||||
|
||||
let mut leases = Vec::new();
|
||||
for _ in 0..batch {
|
||||
let mut transaction = self.start().await?;
|
||||
let workspace_cursor =
|
||||
match super::admission::lock_admission_in_tx(&mut transaction, "*").await {
|
||||
Ok(cursor) => cursor,
|
||||
Err(error) => {
|
||||
transaction.rollback().await.ok();
|
||||
return Err(TaskError::unavailable(format!("{error:?}")));
|
||||
}
|
||||
};
|
||||
let (task_id, _updated_cursor) = match super::admission::grant_next_task(
|
||||
&mut transaction,
|
||||
"*",
|
||||
&workspace_cursor,
|
||||
&self.limits,
|
||||
self.scheduler,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(value) => value,
|
||||
Err(error) => {
|
||||
transaction.rollback().await.ok();
|
||||
return Err(TaskError::unavailable(format!("{error:?}")));
|
||||
}
|
||||
};
|
||||
// Persist the updated controller cursor even when no task is granted.
|
||||
let Some(task_id) = task_id else {
|
||||
transaction.commit().await.map_err(Self::unavailable)?;
|
||||
break;
|
||||
};
|
||||
let row = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"update tasks
|
||||
set state = 'working',
|
||||
lease_owner = $1,
|
||||
lease_until = clock_timestamp() + ($2::bigint || ' milliseconds')::interval,
|
||||
fence = fence + 1,
|
||||
updated_at = now()
|
||||
where task_id = $3
|
||||
and (
|
||||
(state = 'queued' and lease_owner is null)
|
||||
or (state = 'working' and lease_owner is not null
|
||||
and lease_until < clock_timestamp() and current_attempt_id is null)
|
||||
)
|
||||
returning {TASK_PROJECTION}"
|
||||
)))
|
||||
.bind(owner)
|
||||
.bind(lease_ms)
|
||||
.bind(task_id)
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
// Persist cursor update (grant_next_task already did it) regardless.
|
||||
let Some(row) = row else {
|
||||
transaction.rollback().await.ok();
|
||||
break;
|
||||
};
|
||||
let record = record_from_row(&row).map_err(Self::unavailable)?;
|
||||
leases.push(TaskLease {
|
||||
owner: owner.to_owned(),
|
||||
fence: record.fence,
|
||||
lease_until: record.lease_until_unix_ms.unwrap_or_default(),
|
||||
record,
|
||||
});
|
||||
transaction.commit().await.map_err(Self::unavailable)?;
|
||||
}
|
||||
Ok(leases)
|
||||
}
|
||||
|
||||
async fn renew_lease(
|
||||
&self,
|
||||
owner: &str,
|
||||
task_id: TaskId,
|
||||
fence: u64,
|
||||
lease_ms: i64,
|
||||
) -> Result<TaskLease, TaskError> {
|
||||
let mut transaction = self.start().await?;
|
||||
let row = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"update tasks
|
||||
set lease_until = clock_timestamp() + ($1::bigint || ' milliseconds')::interval,
|
||||
updated_at = now()
|
||||
where task_id = $2 and lease_owner = $3 and fence = $4
|
||||
and lease_until > clock_timestamp()
|
||||
returning {TASK_PROJECTION}"
|
||||
)))
|
||||
.bind(lease_ms)
|
||||
.bind(task_id.as_uuid())
|
||||
.bind(owner)
|
||||
.bind(i64::try_from(fence).unwrap_or_default())
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
let Some(row) = row else {
|
||||
transaction.rollback().await.ok();
|
||||
return Err(TaskError::StateConflict);
|
||||
};
|
||||
let record = record_from_row(&row).map_err(Self::unavailable)?;
|
||||
let lease = TaskLease {
|
||||
owner: owner.to_owned(),
|
||||
fence: record.fence,
|
||||
lease_until: record.lease_until_unix_ms.unwrap_or_default(),
|
||||
record,
|
||||
};
|
||||
transaction.commit().await.map_err(Self::unavailable)?;
|
||||
Ok(lease)
|
||||
}
|
||||
|
||||
async fn write_progress(
|
||||
&self,
|
||||
owner: &str,
|
||||
task_id: TaskId,
|
||||
fence: u64,
|
||||
progress: TaskEnvelope,
|
||||
) -> Result<TaskRecord, TaskError> {
|
||||
let mut transaction = self.start().await?;
|
||||
let row = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"update tasks
|
||||
set progress_envelope = $1, updated_at = now()
|
||||
where task_id = $2 and lease_owner = $3 and fence = $4
|
||||
and lease_until > clock_timestamp()
|
||||
returning {TASK_PROJECTION}"
|
||||
)))
|
||||
.bind(progress.value().clone())
|
||||
.bind(task_id.as_uuid())
|
||||
.bind(owner)
|
||||
.bind(i64::try_from(fence).unwrap_or_default())
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
let Some(row) = row else {
|
||||
transaction.rollback().await.ok();
|
||||
return Err(TaskError::StateConflict);
|
||||
};
|
||||
let record = record_from_row(&row).map_err(Self::unavailable)?;
|
||||
transaction.commit().await.map_err(Self::unavailable)?;
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
async fn read_executable_input(
|
||||
&self,
|
||||
owner: &str,
|
||||
task_id: TaskId,
|
||||
fence: u64,
|
||||
) -> Result<(String, String, i64), TaskError> {
|
||||
let row = sqlx::query(
|
||||
"select executable_input_ciphertext, executable_input_key_version, executable_input_master_key_epoch
|
||||
from tasks
|
||||
where task_id = $1 and state = 'working' and lease_owner = $2 and fence = $3
|
||||
and lease_until > clock_timestamp()",
|
||||
)
|
||||
.bind(task_id.as_uuid())
|
||||
.bind(owner)
|
||||
.bind(i64::try_from(fence).unwrap_or_default())
|
||||
.fetch_optional(&self.pool)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
let Some(row) = row else {
|
||||
return Err(TaskError::StateConflict);
|
||||
};
|
||||
let ciphertext: Option<String> = row
|
||||
.try_get("executable_input_ciphertext")
|
||||
.map_err(Self::unavailable)?;
|
||||
let key_version: Option<String> = row
|
||||
.try_get("executable_input_key_version")
|
||||
.map_err(Self::unavailable)?;
|
||||
let epoch: Option<i64> = row
|
||||
.try_get("executable_input_master_key_epoch")
|
||||
.map_err(Self::unavailable)?;
|
||||
if let Some(epoch) = epoch {
|
||||
let active = sqlx::query_scalar::<_, i64>(
|
||||
"select epoch from master_key_identities where status = 'active' order by epoch desc limit 1",
|
||||
)
|
||||
.fetch_optional(&self.pool)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
if let Some(active) = active {
|
||||
if active != epoch {
|
||||
return Err(TaskError::StateConflict);
|
||||
}
|
||||
}
|
||||
}
|
||||
match (ciphertext, key_version, epoch) {
|
||||
(Some(ciphertext), Some(key_version), Some(epoch)) if !ciphertext.is_empty() => {
|
||||
Ok((ciphertext, key_version, epoch))
|
||||
}
|
||||
_ => Err(TaskError::NotFound),
|
||||
}
|
||||
}
|
||||
|
||||
async fn checkpoint_dispatch(
|
||||
&self,
|
||||
owner: &str,
|
||||
task_id: TaskId,
|
||||
fence: u64,
|
||||
attempt_id: String,
|
||||
) -> Result<TaskRecord, TaskError> {
|
||||
let mut transaction = self.start().await?;
|
||||
let row = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"update tasks
|
||||
set current_attempt_id = $1,
|
||||
dispatch_started_at = now(),
|
||||
attempts = attempts + 1,
|
||||
updated_at = now()
|
||||
where task_id = $2 and lease_owner = $3 and fence = $4
|
||||
and lease_until > clock_timestamp() and current_attempt_id is null
|
||||
returning {TASK_PROJECTION}"
|
||||
)))
|
||||
.bind(&attempt_id)
|
||||
.bind(task_id.as_uuid())
|
||||
.bind(owner)
|
||||
.bind(i64::try_from(fence).unwrap_or_default())
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
let Some(row) = row else {
|
||||
transaction.rollback().await.ok();
|
||||
return Err(TaskError::StateConflict);
|
||||
};
|
||||
let record = record_from_row(&row).map_err(Self::unavailable)?;
|
||||
transaction.commit().await.map_err(Self::unavailable)?;
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
async fn finish_leased(
|
||||
&self,
|
||||
request: TaskFinishRequest,
|
||||
owner: &str,
|
||||
fence: u64,
|
||||
) -> Result<TaskRecord, TaskError> {
|
||||
request.validate()?;
|
||||
let mut transaction = self.start().await?;
|
||||
let access = &request.access;
|
||||
let row = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"update tasks
|
||||
set state = $1,
|
||||
result_envelope = $2,
|
||||
error_envelope = $3,
|
||||
version = version + 1,
|
||||
updated_at = now(),
|
||||
lease_owner = null,
|
||||
lease_until = null
|
||||
where task_id = $4 and workspace_id = $5 and owner_kind = $6
|
||||
and owner_id = $7 and authorization_scope = $8
|
||||
and state = $9 and version = $10
|
||||
and lease_owner = $11 and fence = $12
|
||||
and lease_until > clock_timestamp()
|
||||
returning {TASK_PROJECTION}"
|
||||
)))
|
||||
.bind(request.target_state.as_str())
|
||||
.bind(request.result.as_ref().map(|value| value.value().clone()))
|
||||
.bind(request.error.as_ref().map(|value| value.value().clone()))
|
||||
.bind(request.task_id.as_uuid())
|
||||
.bind(&access.workspace_id)
|
||||
.bind(access.owner_kind.as_str())
|
||||
.bind(&access.owner_id)
|
||||
.bind(&access.authorization_scope)
|
||||
.bind(request.expected_state.as_str())
|
||||
.bind(i64::from(request.expected_version))
|
||||
.bind(owner)
|
||||
.bind(i64::try_from(fence).unwrap_or_default())
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
let Some(row) = row else {
|
||||
transaction.rollback().await.ok();
|
||||
return Err(TaskError::StateConflict);
|
||||
};
|
||||
let record = record_from_row(&row).map_err(Self::unavailable)?;
|
||||
sqlx::query("delete from execution_admission_entries where task_id = $1")
|
||||
.bind(request.task_id.as_uuid())
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
transaction.commit().await.map_err(Self::unavailable)?;
|
||||
Ok(record)
|
||||
}
|
||||
}
|
||||
|
||||
impl PostgresTaskStore {
|
||||
@@ -377,11 +753,12 @@ impl PostgresTaskStore {
|
||||
task_id, workspace_id, owner_kind, owner_id, authorization_scope, operation_id,
|
||||
operation_version, scoped_key, input_fingerprint, request_id, trace_id, traceparent,
|
||||
trace_sampled, policy_mode, approval_reference, state, input_envelope,
|
||||
execution_deadline, retain_until
|
||||
execution_deadline, retain_until, executable_input_ciphertext, executable_input_key_version,
|
||||
executable_input_master_key_epoch, platform_api_key_id
|
||||
) values (
|
||||
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, 'queued',
|
||||
$16, to_timestamp($17::double precision / 1000.0),
|
||||
to_timestamp($18::double precision / 1000.0)
|
||||
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, 'queued', $16,
|
||||
to_timestamp($17::double precision / 1000.0),
|
||||
to_timestamp($18::double precision / 1000.0), $19, $20, $21, $22
|
||||
)
|
||||
returning (extract(epoch from created_at) * 1000)::bigint as created_ms",
|
||||
)
|
||||
@@ -403,6 +780,15 @@ impl PostgresTaskStore {
|
||||
.bind(request.input.value().clone())
|
||||
.bind(request.pins.execution_deadline_unix_ms)
|
||||
.bind(request.pins.retain_until_unix_ms)
|
||||
.bind(request.executable_input_ciphertext.as_deref())
|
||||
.bind(request.executable_input_key_version.as_deref())
|
||||
.bind(request.executable_input_master_key_epoch)
|
||||
.bind(
|
||||
request
|
||||
.platform_api_key_id
|
||||
.as_ref()
|
||||
.map(PlatformApiKeyId::as_str),
|
||||
)
|
||||
.fetch_one(&mut **transaction)
|
||||
.await
|
||||
.map_err(task_sql_error)?
|
||||
@@ -540,6 +926,10 @@ fn record_from_row(row: &sqlx::postgres::PgRow) -> Result<TaskRecord, TaskError>
|
||||
authorization_scope: row
|
||||
.try_get("authorization_scope")
|
||||
.map_err(unavailable_row)?,
|
||||
platform_api_key_id: row
|
||||
.try_get::<Option<String>, _>("platform_api_key_id")
|
||||
.map_err(unavailable_row)?
|
||||
.map(PlatformApiKeyId::new),
|
||||
operation_id: row.try_get("operation_id").map_err(unavailable_row)?,
|
||||
input_fingerprint: row.try_get("input_fingerprint").map_err(unavailable_row)?,
|
||||
pins: TaskPins {
|
||||
@@ -574,6 +964,14 @@ fn record_from_row(row: &sqlx::postgres::PgRow) -> Result<TaskRecord, TaskError>
|
||||
error: envelope("error_envelope")?,
|
||||
attempts: u32::try_from(row.try_get::<i32, _>("attempts").map_err(unavailable_row)?)
|
||||
.unwrap_or_default(),
|
||||
fence: u64::try_from(row.try_get::<i64, _>("fence").map_err(unavailable_row)?)
|
||||
.unwrap_or_default(),
|
||||
lease_owner: row.try_get("lease_owner").map_err(unavailable_row)?,
|
||||
lease_until_unix_ms: row.try_get("lease_until_ms").map_err(unavailable_row)?,
|
||||
current_attempt_id: row.try_get("current_attempt_id").map_err(unavailable_row)?,
|
||||
dispatch_started_at_unix_ms: row
|
||||
.try_get("dispatch_started_at_ms")
|
||||
.map_err(unavailable_row)?,
|
||||
version: u32::try_from(row.try_get::<i32, _>("version").map_err(unavailable_row)?)
|
||||
.unwrap_or_default(),
|
||||
created_at_unix_ms: row.try_get("created_ms").map_err(unavailable_row)?,
|
||||
|
||||
@@ -2,6 +2,7 @@ use crank_registry::{MigrationAuthority, MigrationPreflight, PostgresRegistry};
|
||||
use sqlx::Row;
|
||||
|
||||
mod artifact_metadata;
|
||||
mod durable_tasks_guard;
|
||||
mod import_plan;
|
||||
mod legacy_adoption;
|
||||
mod preflight;
|
||||
@@ -72,6 +73,9 @@ async fn controlled_authority_is_versioned_and_safe_under_concurrent_apply() {
|
||||
(23, "prompt-dependencies-v23"),
|
||||
(24, "execution-admission-v24"),
|
||||
(25, "durable-tasks-v25"),
|
||||
(26, "durable-tasks-v26"),
|
||||
(27, "durable-tasks-v27"),
|
||||
(28, "durable-tasks-v28"),
|
||||
];
|
||||
assert_eq!(rows.len(), expected.len());
|
||||
for (row, (version, name)) in rows.iter().zip(expected) {
|
||||
@@ -182,7 +186,7 @@ async fn controlled_authority_is_versioned_and_safe_under_concurrent_apply() {
|
||||
);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(first.pool()).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
MigrationPreflight::Current { version: 28 }
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
@@ -230,7 +234,7 @@ async fn v18_guard_rejects_missing_agent_resource_binding_trigger() {
|
||||
.expect("the V18-local guard must be restorable");
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 25 },
|
||||
MigrationPreflight::Current { version: 28 },
|
||||
"restoring the exact V18 contract must return the current verdict"
|
||||
);
|
||||
}
|
||||
@@ -356,7 +360,7 @@ async fn ledgerless_legacy_baseline_is_consolidated_without_data_loss() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: 25,
|
||||
target: 28,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -469,13 +473,13 @@ async fn healthy_v2_is_reported_as_migration_required_and_upgrades_to_v3() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 2,
|
||||
target: 25,
|
||||
target: 28,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
MigrationPreflight::Current { version: 28 }
|
||||
);
|
||||
let trace_column: bool = sqlx::query_scalar(
|
||||
"select exists (
|
||||
@@ -518,7 +522,7 @@ async fn healthy_v3_upgrades_to_v4_with_honest_legacy_snapshot_provenance() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 3,
|
||||
target: 25,
|
||||
target: 28,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -578,7 +582,7 @@ async fn healthy_v4_upgrades_to_v5_without_fabricating_legacy_outcomes() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 4,
|
||||
target: 25,
|
||||
target: 28,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -832,6 +836,6 @@ async fn v3_upgrade_ignores_oversized_legacy_request_ids_in_partial_index() {
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
MigrationPreflight::Current { version: 28 }
|
||||
);
|
||||
}
|
||||
@@ -32,7 +32,7 @@ async fn healthy_v11_upgrades_to_v13_without_rewriting_prior_ledger() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 11,
|
||||
target: 25,
|
||||
target: 28,
|
||||
}
|
||||
);
|
||||
|
||||
@@ -177,7 +177,7 @@ async fn v12_guard_still_rejects_column_constraint_index_and_relation_drift() {
|
||||
sqlx::raw_sql(restore).execute(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 25 },
|
||||
MigrationPreflight::Current { version: 28 },
|
||||
"restore: {restore}"
|
||||
);
|
||||
}
|
||||
@@ -230,7 +230,7 @@ async fn v13_guard_rejects_wrong_cleanup_index_order_and_predicate() {
|
||||
sqlx::raw_sql(restore).execute(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 25 },
|
||||
MigrationPreflight::Current { version: 28 },
|
||||
"restore: {restore}"
|
||||
);
|
||||
}
|
||||
@@ -507,7 +507,7 @@ async fn assert_v12_drift(pool: &sqlx::PgPool, drift: &str, restore: &str) {
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 25 },
|
||||
MigrationPreflight::Current { version: 28 },
|
||||
"restore: {restore}"
|
||||
);
|
||||
}
|
||||
@@ -845,7 +845,7 @@ async fn v17_guard_rejects_publication_schema_drift() {
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
MigrationPreflight::Current { version: 28 }
|
||||
);
|
||||
|
||||
for (drift, restore) in [
|
||||
@@ -879,7 +879,7 @@ async fn v17_guard_rejects_publication_schema_drift() {
|
||||
sqlx::raw_sql(restore).execute(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 25 },
|
||||
MigrationPreflight::Current { version: 28 },
|
||||
"restore: {restore}"
|
||||
);
|
||||
}
|
||||
|
||||
+8
-8
@@ -289,7 +289,7 @@ async fn assert_primary_key_nullability(pool: &sqlx::PgPool, table: &str, column
|
||||
);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 25 },
|
||||
MigrationPreflight::Current { version: 28 },
|
||||
"a rejected primary-key nullability change must leave the schema current"
|
||||
);
|
||||
|
||||
@@ -473,7 +473,7 @@ async fn assert_definition_only_drift(
|
||||
assert_eq!(super::catalog_constraint_definitions(pool).await, before);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
MigrationPreflight::Current { version: 28 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -554,7 +554,7 @@ async fn story36_v16_guard_rejects_constraint_and_created_index_definition_drift
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 25 },
|
||||
MigrationPreflight::Current { version: 28 },
|
||||
"the baseline before the drift matrix must be the current V16 schema"
|
||||
);
|
||||
let mut observations: Vec<String> = Vec::new();
|
||||
@@ -773,7 +773,7 @@ async fn story36_v16_guard_rejects_constraint_and_created_index_definition_drift
|
||||
.await
|
||||
.expect("restoring the exact definition must apply");
|
||||
let restored = MigrationAuthority::preflight(&pool).await;
|
||||
let restored_current = matches!(restored, Ok(MigrationPreflight::Current { version: 25 }));
|
||||
let restored_current = matches!(restored, Ok(MigrationPreflight::Current { version: 28 }));
|
||||
// Точное восстановление доказывается сравнением снятого снимка с baseline, а не
|
||||
// мнением того же guard-а, который принимает неправильные определения (F4).
|
||||
let restored_exact = catalog_definition_snapshot(&pool).await == before;
|
||||
@@ -804,7 +804,7 @@ async fn story36_v16_guard_resolves_dependent_source_fk_in_the_current_schema()
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 25 },
|
||||
MigrationPreflight::Current { version: 28 },
|
||||
"baseline before inserting the shadow schema"
|
||||
);
|
||||
|
||||
@@ -875,7 +875,7 @@ async fn story36_v16_guard_resolves_dependent_source_fk_in_the_current_schema()
|
||||
// Тень не меняет вердикт guard-а по текущей схеме.
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 25 },
|
||||
MigrationPreflight::Current { version: 28 },
|
||||
"a same-named object in another schema must not change the verdict for the current schema"
|
||||
);
|
||||
|
||||
@@ -947,7 +947,7 @@ async fn story36_v16_guard_resolves_dependent_source_fk_in_the_current_schema()
|
||||
);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 25 },
|
||||
MigrationPreflight::Current { version: 28 },
|
||||
"the exact restoration must return the current V16 schema"
|
||||
);
|
||||
|
||||
@@ -958,7 +958,7 @@ async fn story36_v16_guard_resolves_dependent_source_fk_in_the_current_schema()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
MigrationPreflight::Current { version: 28 }
|
||||
);
|
||||
|
||||
assert!(
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
use super::*;
|
||||
use crank_registry::MigrationApplyResult;
|
||||
|
||||
#[tokio::test]
|
||||
async fn clean_legacy_ledger_upgrades_to_v28_after_v25_removal() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v43_clean_legacy").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
super::remove_v25_schema(&pool).await;
|
||||
// remove_v25_schema drops `tasks` and ledger >= 25, but V25 also added the
|
||||
// nullable dispatch-intent column/index/FK to execution_admission_entries;
|
||||
// restore those to the V24 shape so the legacy ledger is self-consistent.
|
||||
sqlx::raw_sql(
|
||||
"alter table execution_admission_entries drop constraint if exists execution_admission_entries_task_fkey;
|
||||
drop index if exists execution_admission_entries_task_uidx;
|
||||
alter table execution_admission_entries drop column if exists task_id;",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 24,
|
||||
target: 28,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
MigrationAuthority::apply(&pool).await.unwrap(),
|
||||
MigrationApplyResult::Applied { from: 24, to: 28 }
|
||||
);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 28 }
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn partial_v27_on_legacy_ledger_is_rejected_by_preflight() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v43_partial_v27").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
super::remove_v25_schema(&pool).await;
|
||||
sqlx::raw_sql(
|
||||
"alter table execution_admission_entries drop constraint if exists execution_admission_entries_task_fkey;
|
||||
drop index if exists execution_admission_entries_task_uidx;
|
||||
alter table execution_admission_entries drop column if exists task_id;",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
// Reintroduce a partial V27-shaped `tasks` table on top of the legacy (v24) ledger.
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(
|
||||
"create table tasks (
|
||||
task_id uuid primary key,
|
||||
executable_input_ciphertext text,
|
||||
executable_input_key_version text,
|
||||
executable_input_master_key_epoch bigint
|
||||
);",
|
||||
))
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||||
assert_eq!(error.code(), "partial_sequence");
|
||||
// The rejection today is attributed to V25's absent-schema guard because the
|
||||
// `tasks` relation already exists, so a behavioral RED pin for the missing
|
||||
// V27 guard line cannot be reached; this test fixes the rejection contract
|
||||
// instead of claiming new behavior.
|
||||
assert_eq!(error.version(), Some(24));
|
||||
assert_eq!(error.stage(), "preflight.schema");
|
||||
|
||||
let count: i64 =
|
||||
sqlx::query_scalar("select count(*)::bigint from __crank_migrations where version >= 25")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
count, 0,
|
||||
"nothing at or above V25 should have been applied over the partial fixture"
|
||||
);
|
||||
}
|
||||
@@ -71,7 +71,7 @@ async fn fresh_install_exposes_import_plan_objects_with_cascading_job_fk() {
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
MigrationPreflight::Current { version: 28 }
|
||||
);
|
||||
let tables = sqlx::query(
|
||||
"select table_name
|
||||
@@ -224,7 +224,7 @@ async fn healthy_v13_upgrades_to_v14_without_changing_prior_ledger() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 13,
|
||||
target: 25,
|
||||
target: 28,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
|
||||
@@ -88,7 +88,7 @@ async fn published_ledgerless_baseline_upgrades_without_data_loss() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: 25,
|
||||
target: 28,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -101,7 +101,7 @@ async fn published_ledgerless_baseline_upgrades_without_data_loss() {
|
||||
assert_eq!(operation_count, 1);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
MigrationPreflight::Current { version: 28 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -194,7 +194,7 @@ async fn published_ledgerless_historical_column_layout_upgrades_without_data_los
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: 25,
|
||||
target: 28,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -230,7 +230,7 @@ async fn published_ledgerless_historical_column_layout_upgrades_without_data_los
|
||||
);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
MigrationPreflight::Current { version: 28 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -262,7 +262,7 @@ async fn published_initial_mcp_layout_is_accepted() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: 25,
|
||||
target: 28,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -280,7 +280,7 @@ async fn published_initial_mcp_layout_is_accepted() {
|
||||
assert!(supports_elicitation);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
MigrationPreflight::Current { version: 28 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -314,13 +314,13 @@ async fn published_in_place_mcp_upgrade_layout_is_accepted() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: 25,
|
||||
target: 28,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
MigrationPreflight::Current { version: 28 }
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+13
-7
@@ -14,7 +14,7 @@ async fn fresh_install_creates_the_empty_revocation_authority() {
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
MigrationPreflight::Current { version: 28 }
|
||||
);
|
||||
let rows: i64 = sqlx::query_scalar("select count(*) from resource_security_revocations")
|
||||
.fetch_one(&pool)
|
||||
@@ -42,12 +42,12 @@ async fn v18_upgrades_to_v19_without_rewriting_the_prior_ledger() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 18,
|
||||
target: 25,
|
||||
target: 28,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
MigrationAuthority::apply(&pool).await.unwrap(),
|
||||
MigrationApplyResult::Applied { from: 18, to: 25 }
|
||||
MigrationApplyResult::Applied { from: 18, to: 28 }
|
||||
);
|
||||
let after: Vec<(i64, String, String)> =
|
||||
sqlx::query_as("select version, name, checksum from __crank_migrations where version < 19 order by version")
|
||||
@@ -57,7 +57,7 @@ async fn v18_upgrades_to_v19_without_rewriting_the_prior_ledger() {
|
||||
assert_eq!(before, after, "V16–V18 ledger rows must not be rewritten");
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
MigrationPreflight::Current { version: 28 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -86,16 +86,22 @@ async fn a_database_newer_than_the_binary_fails_closed_at_startup() {
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
// The same `version > CURRENT_VERSION` branch an older binary takes when it meets a newer
|
||||
// database; a synthetic version above the current one exercises it without a second binary.
|
||||
let current: i64 = sqlx::query_scalar("select max(version) from __crank_migrations")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let future = current + 1;
|
||||
sqlx::query(
|
||||
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
|
||||
values (26, 'future-v26', repeat('a', 64), 'expand', 'n-minus-one-readable')",
|
||||
values ($1, 'future-synthetic', repeat('a', 64), 'expand', 'n-minus-one-readable')",
|
||||
)
|
||||
.bind(future)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||||
assert_eq!(error.code(), "future_version");
|
||||
assert_eq!(error.version(), Some(26));
|
||||
assert_eq!(error.version(), Some(future));
|
||||
assert_eq!(error.recovery(), "install_matching_application");
|
||||
assert!(
|
||||
MigrationAuthority::require_current(&pool).await.is_err(),
|
||||
@@ -155,7 +161,7 @@ async fn failed_v19_migration_rolls_back_schema_and_ledger() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 18,
|
||||
target: 25,
|
||||
target: 28,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -63,7 +63,7 @@ async fn failed_artifact_metadata_migration_rolls_back_schema_and_ledger() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 11,
|
||||
target: 25,
|
||||
target: 28,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -330,9 +330,10 @@ pub(crate) async fn remove_v12_schema(pool: &sqlx::PgPool) {
|
||||
|
||||
/// Story 4.2: снять V25 (durable Tasks и Task-linked dispatch intent) перед возвратом к < 25.
|
||||
pub(crate) async fn remove_v25_schema(pool: &sqlx::PgPool) {
|
||||
// V25 created `tasks`; V26–V28 only altered it, so dropping the table removes their schema too.
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists tasks cascade;
|
||||
delete from __crank_migrations where version = 25;",
|
||||
delete from __crank_migrations where version >= 25;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
|
||||
+228
-5
@@ -8,14 +8,18 @@
|
||||
use super::common;
|
||||
|
||||
use crank_core::{
|
||||
AdmissionMode, AdmissionOutcome, AdmissionRequest, AdmissionScope, ApprovalEvidence,
|
||||
ExecutionAdmission, NoTasksFallback, RequestId, TaskAcceptRequest, TaskAccess, TaskEnvelope,
|
||||
TaskError, TaskFinishRequest, TaskId, TaskOwnerKind, TaskPins, TaskState, TaskStore,
|
||||
TaskSupportIds, ToolExecutionMode, TraceContext, current_unix_ms,
|
||||
AdmissionMode, AdmissionOutcome, AdmissionRequest, AdmissionScope, AgentId, ApprovalEvidence,
|
||||
ExecutionAdmission, NoTasksFallback, PlatformApiKey, PlatformApiKeyId, PlatformApiKeyKind,
|
||||
PlatformApiKeyScope, PlatformApiKeyStatus, RequestId, TaskAcceptRequest, TaskAccess,
|
||||
TaskEnvelope, TaskError, TaskFinishRequest, TaskId, TaskOwnerKind, TaskPins, TaskState,
|
||||
TaskStore, TaskSupportIds, ToolExecutionMode, TraceContext, WorkspaceId, current_unix_ms,
|
||||
};
|
||||
use crank_registry::{
|
||||
AdmissionLimits, CreatePlatformApiKeyRequest, PostgresExecutionAdmission, PostgresTaskStore,
|
||||
};
|
||||
use crank_registry::{AdmissionLimits, PostgresExecutionAdmission, PostgresTaskStore};
|
||||
use serde_json::json;
|
||||
use sqlx::{PgPool, Row};
|
||||
use time::{Duration as TimeDuration, OffsetDateTime};
|
||||
|
||||
const WORKSPACE: &str = "ws_default";
|
||||
const AGENT: &str = "agent_a";
|
||||
@@ -48,6 +52,7 @@ fn request(key: &str, fingerprint: &str, agent: &str, deadline_in_ms: i64) -> Ta
|
||||
owner_kind: TaskOwnerKind::Agent,
|
||||
owner_id: agent.to_owned(),
|
||||
authorization_scope: format!("credential:pk_{agent}"),
|
||||
platform_api_key_id: Some(PlatformApiKeyId::new(format!("pk_{agent}"))),
|
||||
operation_id: "op_report".to_owned(),
|
||||
pins: TaskPins {
|
||||
operation_version: 3,
|
||||
@@ -60,6 +65,9 @@ fn request(key: &str, fingerprint: &str, agent: &str, deadline_in_ms: i64) -> Ta
|
||||
input_fingerprint: fingerprint.to_owned(),
|
||||
input: TaskEnvelope::try_redacted(&json!({"report": "q3", "api_key": "sk_live"})).unwrap(),
|
||||
support: unsampled_support(),
|
||||
executable_input_ciphertext: None,
|
||||
executable_input_key_version: None,
|
||||
executable_input_master_key_epoch: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -664,6 +672,70 @@ async fn invalid_bounded_envelope_is_rejected_before_persistence() {
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn task_worker_lease_and_fencing_contract() {
|
||||
let database = common::TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let store = store_with(registry.pool().clone(), 8);
|
||||
|
||||
let created = store
|
||||
.accept(request(&key("lease1"), &digest("f1"), AGENT, 30_000))
|
||||
.await
|
||||
.unwrap();
|
||||
let leases = store.claim_batch("worker_1", 4, 10_000).await.unwrap();
|
||||
assert_eq!(leases.len(), 1);
|
||||
assert_eq!(leases[0].record.task_id, created.task_id);
|
||||
assert_eq!(leases[0].record.state, TaskState::Working);
|
||||
assert_eq!(leases[0].owner, "worker_1");
|
||||
|
||||
let lease = &leases[0];
|
||||
let fenced_progress = store
|
||||
.write_progress(
|
||||
"worker_1",
|
||||
lease.record.task_id,
|
||||
lease.fence,
|
||||
TaskEnvelope::try_redacted(&json!({"progress": 1})).unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(fenced_progress.progress.is_some());
|
||||
|
||||
// stale fence rejected
|
||||
let bad = store
|
||||
.renew_lease("worker_1", lease.record.task_id, lease.fence + 1, 10_000)
|
||||
.await;
|
||||
assert!(bad.is_err());
|
||||
|
||||
// checkpoint dispatch once
|
||||
let checkpointed = store
|
||||
.checkpoint_dispatch(
|
||||
"worker_1",
|
||||
lease.record.task_id,
|
||||
lease.fence,
|
||||
"attempt-1".to_owned(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
checkpointed.current_attempt_id.as_deref(),
|
||||
Some("attempt-1")
|
||||
);
|
||||
assert!(checkpointed.dispatch_started_at_unix_ms.is_some());
|
||||
|
||||
// second checkpoint rejected
|
||||
let second = store
|
||||
.checkpoint_dispatch(
|
||||
"worker_1",
|
||||
lease.record.task_id,
|
||||
lease.fence,
|
||||
"attempt-2".to_owned(),
|
||||
)
|
||||
.await;
|
||||
assert!(second.is_err());
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn store_failure_fails_closed_without_records() {
|
||||
let database = common::TestDatabase::new().await;
|
||||
@@ -680,3 +752,154 @@ async fn store_failure_fails_closed_without_records() {
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
/// Story 4.3 ATDD: the typed immutable Platform API key reference of an accepted Task is persisted,
|
||||
/// read back through the lease, and only an active, unexpired, exactly bound key is authoritatively
|
||||
/// revalidated. Revocation, expiry and a foreign workspace/agent binding all close; an administrator
|
||||
/// Task stores no machine key identity at all, so a worker fails closed on it.
|
||||
#[tokio::test]
|
||||
async fn accepted_task_authority_reference_is_persisted_and_revalidated() {
|
||||
let database = common::TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let store = store_with(registry.pool().clone(), 8);
|
||||
|
||||
let workspace = WorkspaceId::new(WORKSPACE);
|
||||
let now = OffsetDateTime::now_utc();
|
||||
// `ws_default` is seeded by the baseline migration; the keys only need that workspace row.
|
||||
let agent = AgentId::new(AGENT);
|
||||
|
||||
let active_id = PlatformApiKeyId::new("pk_task_active");
|
||||
for key in [
|
||||
authority_key(
|
||||
"pk_task_active",
|
||||
&workspace,
|
||||
AGENT,
|
||||
PlatformApiKeyStatus::Active,
|
||||
None,
|
||||
),
|
||||
authority_key(
|
||||
"pk_task_revoked",
|
||||
&workspace,
|
||||
AGENT,
|
||||
PlatformApiKeyStatus::Revoked,
|
||||
None,
|
||||
),
|
||||
authority_key(
|
||||
"pk_task_expired",
|
||||
&workspace,
|
||||
AGENT,
|
||||
PlatformApiKeyStatus::Active,
|
||||
Some(now - TimeDuration::hours(1)),
|
||||
),
|
||||
] {
|
||||
let secret_hash = format!("secret-hash-{}", key.id.as_str());
|
||||
registry
|
||||
.create_platform_api_key(CreatePlatformApiKeyRequest {
|
||||
secret_hash: &secret_hash,
|
||||
api_key: &key,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
// Acceptance persists only the immutable typed reference, never the bearer secret.
|
||||
let mut accepted = request(&key("k_authority"), &digest("fa"), AGENT, 300_000);
|
||||
accepted.platform_api_key_id = Some(active_id.clone());
|
||||
let task_id = accepted.task_id;
|
||||
store.accept(accepted).await.expect("acceptance commits");
|
||||
|
||||
let leases = store
|
||||
.claim_batch("worker_authority", 8, 30_000)
|
||||
.await
|
||||
.expect("claim");
|
||||
let lease = leases
|
||||
.into_iter()
|
||||
.find(|lease| lease.record.task_id == task_id)
|
||||
.expect("accepted task is leased");
|
||||
assert_eq!(lease.record.platform_api_key_id.as_ref(), Some(&active_id));
|
||||
|
||||
// Positive: the exact active key of this workspace/agent is revalidated authoritatively.
|
||||
let revalidated = registry
|
||||
.revalidate_platform_api_key(&workspace, &agent, &active_id)
|
||||
.await
|
||||
.expect("authoritative read")
|
||||
.expect("active key is authoritative");
|
||||
assert!(
|
||||
revalidated
|
||||
.api_key
|
||||
.scopes
|
||||
.contains(&PlatformApiKeyScope::Write)
|
||||
);
|
||||
|
||||
// Negatives: revocation, expiry and a foreign workspace/agent binding all fail closed.
|
||||
let foreign_agent = AgentId::new("agent_b");
|
||||
let foreign_workspace = WorkspaceId::new("ws_elsewhere");
|
||||
for (other_workspace, other_agent, other_key) in [
|
||||
(&workspace, &agent, PlatformApiKeyId::new("pk_task_revoked")),
|
||||
(&workspace, &agent, PlatformApiKeyId::new("pk_task_expired")),
|
||||
(&workspace, &foreign_agent, active_id.clone()),
|
||||
(&foreign_workspace, &agent, active_id.clone()),
|
||||
] {
|
||||
let found = registry
|
||||
.revalidate_platform_api_key(other_workspace, other_agent, &other_key)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
found.is_none(),
|
||||
"authority must fail closed for {}",
|
||||
other_key.as_str()
|
||||
);
|
||||
}
|
||||
|
||||
// An administrator Task carries no machine key identity: the worker has nothing to revalidate.
|
||||
let mut admin_request = request(&key("k_admin"), &digest("fb"), AGENT, 300_000);
|
||||
admin_request.owner_kind = TaskOwnerKind::Admin;
|
||||
admin_request.owner_id = "user_admin".to_owned();
|
||||
admin_request.authorization_scope = "admin:user_admin".to_owned();
|
||||
admin_request.platform_api_key_id = None;
|
||||
let admin_task = admin_request.task_id;
|
||||
store
|
||||
.accept(admin_request)
|
||||
.await
|
||||
.expect("administrator acceptance commits");
|
||||
let admin_record = store
|
||||
.read(
|
||||
&TaskAccess {
|
||||
workspace_id: WORKSPACE.to_owned(),
|
||||
owner_kind: TaskOwnerKind::Admin,
|
||||
owner_id: "user_admin".to_owned(),
|
||||
authorization_scope: "admin:user_admin".to_owned(),
|
||||
},
|
||||
admin_task,
|
||||
)
|
||||
.await
|
||||
.expect("owner read");
|
||||
assert_eq!(admin_record.platform_api_key_id, None);
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
fn authority_key(
|
||||
id: &str,
|
||||
workspace_id: &WorkspaceId,
|
||||
agent: &str,
|
||||
status: PlatformApiKeyStatus,
|
||||
expires_at: Option<OffsetDateTime>,
|
||||
) -> PlatformApiKey {
|
||||
PlatformApiKey {
|
||||
id: PlatformApiKeyId::new(id),
|
||||
workspace_id: workspace_id.clone(),
|
||||
agent_id: Some(AgentId::new(agent)),
|
||||
key_kind: PlatformApiKeyKind::McpClient,
|
||||
name: id.to_owned(),
|
||||
prefix: "crk_live".to_owned(),
|
||||
scopes: vec![PlatformApiKeyScope::Write],
|
||||
status,
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
last_used_at: None,
|
||||
expires_at,
|
||||
allowed_origins: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
mod task_worker;
|
||||
@@ -0,0 +1,163 @@
|
||||
//! Story 4.3 ATDD: durable Task leases, fencing, crash recovery and bounded claim behavior.
|
||||
//!
|
||||
//! Split from `tasks.rs` to keep both integration files inside the code-health limit.
|
||||
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
/// Story 4.3 ATDD: a worker crash before the durable dispatch checkpoint leaves only an expired
|
||||
/// lease. PostgreSQL is authoritative, so another worker recovers the Task and the dead owner can
|
||||
/// never commit a terminal outcome with its old fence.
|
||||
#[tokio::test]
|
||||
async fn task_worker_expired_pre_checkpoint_lease_is_recovered_and_stale_owner_cannot_commit() {
|
||||
let database = common::TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let store = store_with(registry.pool().clone(), 8);
|
||||
|
||||
let created = store
|
||||
.accept(request(&key("recover1"), &digest("f2"), AGENT, 30_000))
|
||||
.await
|
||||
.unwrap();
|
||||
let first = store.claim_batch("worker_dead", 1, 150).await.unwrap();
|
||||
assert_eq!(first.len(), 1);
|
||||
assert_eq!(first[0].record.task_id, created.task_id);
|
||||
|
||||
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
|
||||
|
||||
// Recovery on the next bounded authoritative scan, with no Valkey wake-up.
|
||||
let recovered = store.claim_batch("worker_live", 4, 10_000).await.unwrap();
|
||||
let lease = recovered
|
||||
.into_iter()
|
||||
.find(|lease| lease.record.task_id == created.task_id)
|
||||
.expect("expired pre-checkpoint Task is recovered");
|
||||
assert!(lease.fence > first[0].fence, "recovery bumps the fence");
|
||||
|
||||
// The previous owner's terminal CAS is rejected; the live owner wins exactly once.
|
||||
let stale = store
|
||||
.finish_leased(
|
||||
TaskFinishRequest {
|
||||
access: access(AGENT),
|
||||
task_id: created.task_id,
|
||||
expected_state: first[0].record.state,
|
||||
expected_version: first[0].record.version,
|
||||
target_state: TaskState::Completed,
|
||||
result: Some(TaskEnvelope::try_redacted(&json!({"stale": true})).unwrap()),
|
||||
error: None,
|
||||
},
|
||||
"worker_dead",
|
||||
first[0].fence,
|
||||
)
|
||||
.await;
|
||||
assert!(matches!(stale, Err(TaskError::StateConflict)));
|
||||
|
||||
let finished = store
|
||||
.finish_leased(
|
||||
TaskFinishRequest {
|
||||
access: access(AGENT),
|
||||
task_id: created.task_id,
|
||||
expected_state: lease.record.state,
|
||||
expected_version: lease.record.version,
|
||||
target_state: TaskState::Completed,
|
||||
result: Some(TaskEnvelope::try_redacted(&json!({"ok": true})).unwrap()),
|
||||
error: None,
|
||||
},
|
||||
"worker_live",
|
||||
lease.fence,
|
||||
)
|
||||
.await
|
||||
.expect("current lease wins the terminal CAS");
|
||||
assert_eq!(finished.state, TaskState::Completed);
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
/// Story 4.3 ATDD: after the dispatch checkpoint the outbound outcome is uncertain. An expired
|
||||
/// attempt resolves to `outcome_unknown`, is never redispatched automatically and releases the
|
||||
/// admission slot it held.
|
||||
#[tokio::test]
|
||||
async fn task_worker_expired_checkpointed_attempt_becomes_outcome_unknown_without_redispatch() {
|
||||
let database = common::TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let store = store_with(registry.pool().clone(), 8);
|
||||
|
||||
let created = store
|
||||
.accept(request(&key("uncertain1"), &digest("f3"), AGENT, 30_000))
|
||||
.await
|
||||
.unwrap();
|
||||
let leases = store.claim_batch("worker_dead", 1, 150).await.unwrap();
|
||||
let lease = leases.into_iter().next().expect("claim");
|
||||
store
|
||||
.checkpoint_dispatch(
|
||||
"worker_dead",
|
||||
lease.record.task_id,
|
||||
lease.fence,
|
||||
"attempt-uncertain".to_owned(),
|
||||
)
|
||||
.await
|
||||
.expect("durable dispatch checkpoint");
|
||||
|
||||
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
|
||||
|
||||
// The authority scan resolves uncertainty instead of handing the attempt to another worker.
|
||||
let after = store.claim_batch("worker_live", 4, 10_000).await.unwrap();
|
||||
assert!(
|
||||
after.is_empty(),
|
||||
"a checkpointed attempt must never be redispatched"
|
||||
);
|
||||
let record = store.read(&access(AGENT), created.task_id).await.unwrap();
|
||||
assert_eq!(record.state, TaskState::OutcomeUnknown);
|
||||
assert_eq!(
|
||||
record.current_attempt_id.as_deref(),
|
||||
Some("attempt-uncertain")
|
||||
);
|
||||
let intents: i64 = sqlx::query_scalar(
|
||||
"select count(*)::bigint from execution_admission_entries where task_id = $1",
|
||||
)
|
||||
.bind(created.task_id.as_uuid())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(intents, 0, "uncertain terminal outcome releases capacity");
|
||||
|
||||
// Still no automatic retry on the following scans.
|
||||
assert!(
|
||||
store
|
||||
.claim_batch("worker_live", 4, 10_000)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
/// Story 4.3 ATDD: concurrent claimers never hold the same Task at once.
|
||||
#[tokio::test]
|
||||
async fn task_worker_concurrent_claimers_never_double_lease_one_task() {
|
||||
let database = common::TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let store = std::sync::Arc::new(store_with(registry.pool().clone(), 8));
|
||||
|
||||
let created = store
|
||||
.accept(request(&key("concurrent1"), &digest("f4"), AGENT, 30_000))
|
||||
.await
|
||||
.unwrap();
|
||||
let mut handles = Vec::new();
|
||||
for index in 0..4 {
|
||||
let store = store.clone();
|
||||
handles.push(tokio::spawn(async move {
|
||||
store
|
||||
.claim_batch(&format!("worker_{index}"), 1, 10_000)
|
||||
.await
|
||||
.unwrap()
|
||||
}));
|
||||
}
|
||||
let mut leased = Vec::new();
|
||||
for handle in handles {
|
||||
leased.extend(handle.await.unwrap());
|
||||
}
|
||||
assert_eq!(leased.len(), 1, "exactly one owner wins the claim");
|
||||
assert_eq!(leased[0].record.task_id, created.task_id);
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
Reference in new issue
Block a user