feat(epic4): подтверждать durable Task после атомарного PG-commit (Story 4.2)
CI / UI Checks (pull_request) Successful in 8s
CI / Rust Checks (pull_request) Successful in 19m34s
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) Successful in 1s
CI / Deploy (pull_request) Skipped
CI / UI Checks (pull_request) Successful in 8s
CI / Rust Checks (pull_request) Successful in 19m34s
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) Successful in 1s
CI / Deploy (pull_request) Skipped
Application entry выдаёт Task ID только после атомарного PostgreSQL commit Task+intent+capacity; replay/conflict, owner scope, bounded envelope, terminal CAS и fail-closed readiness проверены на реальном PG. Также включён принятый план перехода на rmcp (только документ, миграция не запускается).
This commit is contained in:
1 parent
cc612516a2
commit
2219a7217d
37 files changed
+4028
-136
No files matched your search
@@ -70,6 +70,8 @@ async fn controlled_authority_is_versioned_and_safe_under_concurrent_apply() {
|
||||
(21, "prompts-v21"),
|
||||
(22, "prompt-publications-v22"),
|
||||
(23, "prompt-dependencies-v23"),
|
||||
(24, "execution-admission-v24"),
|
||||
(25, "durable-tasks-v25"),
|
||||
];
|
||||
assert_eq!(rows.len(), expected.len());
|
||||
for (row, (version, name)) in rows.iter().zip(expected) {
|
||||
@@ -180,7 +182,7 @@ async fn controlled_authority_is_versioned_and_safe_under_concurrent_apply() {
|
||||
);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(first.pool()).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
@@ -228,7 +230,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: 23 },
|
||||
MigrationPreflight::Current { version: 25 },
|
||||
"restoring the exact V18 contract must return the current verdict"
|
||||
);
|
||||
}
|
||||
@@ -354,7 +356,7 @@ async fn ledgerless_legacy_baseline_is_consolidated_without_data_loss() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: 23,
|
||||
target: 25,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -467,13 +469,13 @@ async fn healthy_v2_is_reported_as_migration_required_and_upgrades_to_v3() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 2,
|
||||
target: 23,
|
||||
target: 25,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
);
|
||||
let trace_column: bool = sqlx::query_scalar(
|
||||
"select exists (
|
||||
@@ -516,7 +518,7 @@ async fn healthy_v3_upgrades_to_v4_with_honest_legacy_snapshot_provenance() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 3,
|
||||
target: 23,
|
||||
target: 25,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -576,7 +578,7 @@ async fn healthy_v4_upgrades_to_v5_without_fabricating_legacy_outcomes() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 4,
|
||||
target: 23,
|
||||
target: 25,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -830,6 +832,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: 23 }
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
);
|
||||
}
|
||||
@@ -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: 23,
|
||||
target: 25,
|
||||
}
|
||||
);
|
||||
|
||||
@@ -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: 23 },
|
||||
MigrationPreflight::Current { version: 25 },
|
||||
"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: 23 },
|
||||
MigrationPreflight::Current { version: 25 },
|
||||
"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: 23 },
|
||||
MigrationPreflight::Current { version: 25 },
|
||||
"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: 23 }
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
);
|
||||
|
||||
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: 23 },
|
||||
MigrationPreflight::Current { version: 25 },
|
||||
"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: 23 },
|
||||
MigrationPreflight::Current { version: 25 },
|
||||
"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: 23 }
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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: 23 },
|
||||
MigrationPreflight::Current { version: 25 },
|
||||
"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: 23 }));
|
||||
let restored_current = matches!(restored, Ok(MigrationPreflight::Current { version: 25 }));
|
||||
// Точное восстановление доказывается сравнением снятого снимка с 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: 23 },
|
||||
MigrationPreflight::Current { version: 25 },
|
||||
"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: 23 },
|
||||
MigrationPreflight::Current { version: 25 },
|
||||
"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: 23 },
|
||||
MigrationPreflight::Current { version: 25 },
|
||||
"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: 23 }
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
);
|
||||
|
||||
assert!(
|
||||
|
||||
@@ -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: 23 }
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
);
|
||||
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: 23,
|
||||
target: 25,
|
||||
}
|
||||
);
|
||||
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: 23,
|
||||
target: 25,
|
||||
}
|
||||
);
|
||||
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: 23 }
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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: 23,
|
||||
target: 25,
|
||||
}
|
||||
);
|
||||
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: 23 }
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -262,7 +262,7 @@ async fn published_initial_mcp_layout_is_accepted() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: 23,
|
||||
target: 25,
|
||||
}
|
||||
);
|
||||
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: 23 }
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -314,13 +314,13 @@ async fn published_in_place_mcp_upgrade_layout_is_accepted() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: 23,
|
||||
target: 25,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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: 23 }
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
);
|
||||
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: 23,
|
||||
target: 25,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
MigrationAuthority::apply(&pool).await.unwrap(),
|
||||
MigrationApplyResult::Applied { from: 18, to: 23 }
|
||||
MigrationApplyResult::Applied { from: 18, to: 25 }
|
||||
);
|
||||
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: 23 }
|
||||
MigrationPreflight::Current { version: 25 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -84,18 +84,18 @@ async fn a_database_newer_than_the_binary_fails_closed_at_startup() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v19_future_version").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
// The same `version > CURRENT_VERSION` branch an old V23 binary takes when it
|
||||
// meets a V24 database; a synthetic V24 row exercises it without a second binary.
|
||||
// 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.
|
||||
sqlx::query(
|
||||
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
|
||||
values (24, 'future-v24', repeat('a', 64), 'expand', 'n-minus-one-readable')",
|
||||
values (26, 'future-v26', repeat('a', 64), 'expand', 'n-minus-one-readable')",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||||
assert_eq!(error.code(), "future_version");
|
||||
assert_eq!(error.version(), Some(24));
|
||||
assert_eq!(error.version(), Some(26));
|
||||
assert_eq!(error.recovery(), "install_matching_application");
|
||||
assert!(
|
||||
MigrationAuthority::require_current(&pool).await.is_err(),
|
||||
@@ -155,7 +155,7 @@ async fn failed_v19_migration_rolls_back_schema_and_ledger() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 18,
|
||||
target: 23,
|
||||
target: 25,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -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: 23,
|
||||
target: 25,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -38,6 +38,7 @@ pub(crate) async fn remove_v4_schema(pool: &sqlx::PgPool) {
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v5_schema(pool: &sqlx::PgPool) {
|
||||
remove_v24_schema(pool).await;
|
||||
remove_v6_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop index if exists invocation_logs_workspace_operation_version_idx;
|
||||
@@ -154,6 +155,7 @@ pub(crate) async fn remove_v11_schema(pool: &sqlx::PgPool) {
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v14_schema(pool: &sqlx::PgPool) {
|
||||
remove_v24_schema(pool).await;
|
||||
remove_v15_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists import_plan_applications;
|
||||
@@ -224,6 +226,7 @@ pub(crate) async fn remove_v18_schema(pool: &sqlx::PgPool) {
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v19_schema(pool: &sqlx::PgPool) {
|
||||
remove_v24_schema(pool).await;
|
||||
remove_v20_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists resource_security_revocations;
|
||||
@@ -307,6 +310,7 @@ pub(crate) async fn remove_v20_schema(pool: &sqlx::PgPool) {
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v12_schema(pool: &sqlx::PgPool) {
|
||||
remove_v24_schema(pool).await;
|
||||
remove_v14_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop index if exists import_jobs_openapi_source_idx;
|
||||
@@ -323,3 +327,27 @@ pub(crate) async fn remove_v12_schema(pool: &sqlx::PgPool) {
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Story 4.2: снять V25 (durable Tasks и Task-linked dispatch intent) перед возвратом к < 25.
|
||||
pub(crate) async fn remove_v25_schema(pool: &sqlx::PgPool) {
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists tasks cascade;
|
||||
delete from __crank_migrations where version = 25;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Story 4.1: снять V24 (authoritative execution admission) перед возвратом к < 24.
|
||||
pub(crate) async fn remove_v24_schema(pool: &sqlx::PgPool) {
|
||||
remove_v25_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists execution_admission_entries;
|
||||
drop table if exists execution_admission_controllers;
|
||||
delete from __crank_migrations where version = 24;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
@@ -0,0 +1,682 @@
|
||||
//! ATDD Story 4.2 (FR-22/FR-23): durable Task acceptance on a real PostgreSQL schema.
|
||||
//!
|
||||
//! These oracles drive the real store: Task + dispatch intent + queue slot in one transaction, replay
|
||||
//! and typed conflict before any capacity mutation, bounded shared capacity, the Task-linked intent
|
||||
//! guard of the legacy admission paths, one-winner terminal CAS with an immutable result, bounded
|
||||
//! retention, owner/authorization-scope isolation and fail-closed health.
|
||||
|
||||
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,
|
||||
};
|
||||
use crank_registry::{AdmissionLimits, PostgresExecutionAdmission, PostgresTaskStore};
|
||||
use serde_json::json;
|
||||
use sqlx::{PgPool, Row};
|
||||
|
||||
const WORKSPACE: &str = "ws_default";
|
||||
const AGENT: &str = "agent_a";
|
||||
|
||||
fn limits(queue: usize) -> AdmissionLimits {
|
||||
AdmissionLimits {
|
||||
global_limit: 4,
|
||||
agent_limit: 4,
|
||||
tool_limit: 4,
|
||||
queue_limit: queue,
|
||||
}
|
||||
}
|
||||
|
||||
fn store_with(pool: PgPool, queue: usize) -> PostgresTaskStore {
|
||||
PostgresTaskStore::new(pool, limits(queue), Default::default()).expect("valid store config")
|
||||
}
|
||||
|
||||
fn unsampled_support() -> TaskSupportIds {
|
||||
TaskSupportIds::new(
|
||||
RequestId::generate(),
|
||||
&TraceContext::parse("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00").unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
fn request(key: &str, fingerprint: &str, agent: &str, deadline_in_ms: i64) -> TaskAcceptRequest {
|
||||
let deadline = current_unix_ms() + deadline_in_ms;
|
||||
TaskAcceptRequest {
|
||||
task_id: TaskId::generate(),
|
||||
workspace_id: WORKSPACE.to_owned(),
|
||||
owner_kind: TaskOwnerKind::Agent,
|
||||
owner_id: agent.to_owned(),
|
||||
authorization_scope: format!("credential:pk_{agent}"),
|
||||
operation_id: "op_report".to_owned(),
|
||||
pins: TaskPins {
|
||||
operation_version: 3,
|
||||
policy_mode: ToolExecutionMode::Background,
|
||||
execution_deadline_unix_ms: deadline,
|
||||
retain_until_unix_ms: deadline + 3_600_000,
|
||||
approval_reference: Some("appr_1".to_owned()),
|
||||
},
|
||||
scoped_key: key.to_owned(),
|
||||
input_fingerprint: fingerprint.to_owned(),
|
||||
input: TaskEnvelope::try_redacted(&json!({"report": "q3", "api_key": "sk_live"})).unwrap(),
|
||||
support: unsampled_support(),
|
||||
}
|
||||
}
|
||||
|
||||
fn access(agent: &str) -> TaskAccess {
|
||||
TaskAccess {
|
||||
workspace_id: WORKSPACE.to_owned(),
|
||||
owner_kind: TaskOwnerKind::Agent,
|
||||
owner_id: agent.to_owned(),
|
||||
authorization_scope: format!("credential:pk_{agent}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn key(seed: &str) -> String {
|
||||
format!("{seed:0<64}").chars().take(64).collect()
|
||||
}
|
||||
|
||||
fn digest(seed: &str) -> String {
|
||||
format!("{seed:0<64}").chars().take(64).collect()
|
||||
}
|
||||
|
||||
async fn row_counts(pool: &PgPool) -> (i64, i64) {
|
||||
let row = sqlx::query(
|
||||
"select
|
||||
(select count(*)::bigint from tasks) as tasks,
|
||||
(select count(*)::bigint from execution_admission_entries where task_id is not null)
|
||||
as intents",
|
||||
)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
(row.get("tasks"), row.get("intents"))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn acceptance_commits_task_intent_and_slot_together() {
|
||||
let database = common::TestDatabase::new().await;
|
||||
// Fresh schema: the first connection applies the migration, later pools reuse the same schema.
|
||||
let _migrated = database.registry().await;
|
||||
let registry = database.concurrent_registry(4).await;
|
||||
let store = store_with(registry.pool().clone(), 8);
|
||||
|
||||
let request = request(&key("k1"), &digest("f1"), AGENT, 30_000);
|
||||
let task_id = request.task_id;
|
||||
let support = request.support.clone();
|
||||
|
||||
// Another connection holds both controller rows: the acceptance cannot commit yet.
|
||||
let mut blocker = registry.pool().begin().await.unwrap();
|
||||
sqlx::query(
|
||||
"insert into execution_admission_controllers (workspace_id) values ('*'), ($1)
|
||||
on conflict (workspace_id) do nothing",
|
||||
)
|
||||
.bind(WORKSPACE)
|
||||
.execute(&mut *blocker)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("update execution_admission_controllers set updated_at = updated_at")
|
||||
.execute(&mut *blocker)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let pool = registry.pool().clone();
|
||||
let acceptance = tokio::spawn(async move { store.accept(request).await });
|
||||
tokio::time::sleep(std::time::Duration::from_millis(150)).await;
|
||||
|
||||
// No partial Task, no intent and no accepted response exist before COMMIT.
|
||||
assert!(!acceptance.is_finished());
|
||||
assert_eq!(row_counts(&pool).await, (0, 0));
|
||||
|
||||
blocker.commit().await.unwrap();
|
||||
let acceptance = acceptance.await.unwrap().expect("acceptance commits");
|
||||
assert_eq!(acceptance.state, TaskState::Queued);
|
||||
assert!(!acceptance.replayed);
|
||||
assert_eq!(acceptance.task_id, task_id);
|
||||
assert_eq!(acceptance.support, support);
|
||||
assert_eq!(row_counts(registry.pool()).await, (1, 1));
|
||||
|
||||
// A fresh connection and store read the committed pins/identities back.
|
||||
let reader = store_with(database.concurrent_registry(2).await.pool().clone(), 8);
|
||||
let record = reader.read(&access(AGENT), task_id).await.unwrap();
|
||||
assert_eq!(record.state, TaskState::Queued);
|
||||
assert_eq!(record.pins.operation_version, 3);
|
||||
assert_eq!(record.pins.policy_mode, ToolExecutionMode::Background);
|
||||
assert_eq!(record.pins.approval_reference.as_deref(), Some("appr_1"));
|
||||
assert_eq!(record.support.request_id, support.request_id);
|
||||
assert_eq!(record.support.trace_id, support.trace_id);
|
||||
assert_eq!(record.support.traceparent, support.traceparent);
|
||||
assert!(!record.support.trace_sampled);
|
||||
// Secret-bearing input is classified before persistence.
|
||||
assert_eq!(record.input.value()["api_key"], json!("[redacted]"));
|
||||
assert_eq!(record.input.value()["report"], json!("q3"));
|
||||
assert!(record.result.is_none());
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn replay_returns_the_same_task_and_one_slot() {
|
||||
let database = common::TestDatabase::new().await;
|
||||
// Fresh schema: the first connection applies the migration, later pools reuse the same schema.
|
||||
let _migrated = database.registry().await;
|
||||
let registry = database.concurrent_registry(4).await;
|
||||
let store = store_with(registry.pool().clone(), 8);
|
||||
|
||||
let first = store
|
||||
.accept(request(&key("k1"), &digest("f1"), AGENT, 30_000))
|
||||
.await
|
||||
.expect("first acceptance");
|
||||
let before = store.read(&access(AGENT), first.task_id).await.unwrap();
|
||||
|
||||
let replay = store
|
||||
.accept(request(&key("k1"), &digest("f1"), AGENT, 30_000))
|
||||
.await
|
||||
.expect("replay returns the accepted Task");
|
||||
assert_eq!(replay.task_id, first.task_id);
|
||||
assert!(replay.replayed);
|
||||
assert_eq!(replay.support.request_id, first.support.request_id);
|
||||
assert_eq!(row_counts(registry.pool()).await, (1, 1));
|
||||
|
||||
// Replay never rewrites the accepted row or its audit evidence.
|
||||
let after = store.read(&access(AGENT), first.task_id).await.unwrap();
|
||||
assert_eq!(after.version, before.version);
|
||||
assert_eq!(after.updated_at_unix_ms, before.updated_at_unix_ms);
|
||||
assert_eq!(after.created_at_unix_ms, before.created_at_unix_ms);
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn replay_stays_available_with_a_full_queue_and_past_execution_deadline() {
|
||||
let database = common::TestDatabase::new().await;
|
||||
// Fresh schema: the first connection applies the migration, later pools reuse the same schema.
|
||||
let _migrated = database.registry().await;
|
||||
let registry = database.concurrent_registry(4).await;
|
||||
let store = store_with(registry.pool().clone(), 1);
|
||||
|
||||
// A short deadline: the Task is still retained after its execution deadline elapsed.
|
||||
let first = store
|
||||
.accept(request(&key("k1"), &digest("f1"), AGENT, 1))
|
||||
.await
|
||||
.expect("first acceptance");
|
||||
sqlx::query(
|
||||
"update tasks set execution_deadline = now() - interval '1 hour' where task_id = $1",
|
||||
)
|
||||
.bind(first.task_id.as_uuid())
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
|
||||
|
||||
let replayed = store
|
||||
.accept(request(&key("k1"), &digest("f1"), AGENT, 1))
|
||||
.await
|
||||
.expect("replay works with a full queue and an elapsed execution deadline");
|
||||
assert_eq!(replayed.task_id, first.task_id);
|
||||
assert!(replayed.replayed);
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_different_fingerprint_on_the_same_key_is_a_typed_conflict() {
|
||||
let database = common::TestDatabase::new().await;
|
||||
// Fresh schema: the first connection applies the migration, later pools reuse the same schema.
|
||||
let _migrated = database.registry().await;
|
||||
let registry = database.concurrent_registry(4).await;
|
||||
let store = store_with(registry.pool().clone(), 8);
|
||||
|
||||
let first = store
|
||||
.accept(request(&key("k1"), &digest("f1"), AGENT, 30_000))
|
||||
.await
|
||||
.expect("first acceptance");
|
||||
let before = store.read(&access(AGENT), first.task_id).await.unwrap();
|
||||
|
||||
let conflict = store
|
||||
.accept(request(&key("k1"), &digest("f2"), AGENT, 30_000))
|
||||
.await
|
||||
.expect_err("different input is a conflict");
|
||||
assert_eq!(conflict, TaskError::FingerprintConflict);
|
||||
assert_eq!(row_counts(registry.pool()).await, (1, 1));
|
||||
|
||||
let after = store.read(&access(AGENT), first.task_id).await.unwrap();
|
||||
assert_eq!(after.version, before.version);
|
||||
assert_eq!(after.updated_at_unix_ms, before.updated_at_unix_ms);
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bounded_capacity_is_shared_and_overload_creates_nothing() {
|
||||
let database = common::TestDatabase::new().await;
|
||||
// Fresh schema: the first connection applies the migration, later pools reuse the same schema.
|
||||
let _migrated = database.registry().await;
|
||||
let registry = database.concurrent_registry(4).await;
|
||||
let store = store_with(registry.pool().clone(), 1);
|
||||
let admission =
|
||||
PostgresExecutionAdmission::new(registry.pool().clone(), limits(1), Default::default())
|
||||
.unwrap();
|
||||
|
||||
// A durable enqueue decision and a durable Task share the same bounded queue budget.
|
||||
let waiting = admission
|
||||
.admit(AdmissionRequest {
|
||||
scope: AdmissionScope {
|
||||
workspace_id: WORKSPACE.to_owned(),
|
||||
agent_key: AGENT.to_owned(),
|
||||
operation_id: "op_sync".to_owned(),
|
||||
operation_version: 1,
|
||||
},
|
||||
mode: AdmissionMode::Background,
|
||||
policy_mode: ToolExecutionMode::Background,
|
||||
no_tasks_fallback: NoTasksFallback::Synchronous,
|
||||
approval: ApprovalEvidence::NotRequired,
|
||||
fingerprint: "fp_sync".to_owned(),
|
||||
expires_at_unix_ms: current_unix_ms() + 30_000,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(matches!(waiting, AdmissionOutcome::Enqueued(_)));
|
||||
|
||||
let overloaded = store
|
||||
.accept(request(&key("k1"), &digest("f1"), AGENT, 30_000))
|
||||
.await
|
||||
.expect_err("queue is full");
|
||||
assert!(matches!(overloaded, TaskError::Overloaded { .. }));
|
||||
assert_eq!(row_counts(registry.pool()).await, (0, 0));
|
||||
assert_eq!(
|
||||
admission.snapshot().await.unwrap().waiting,
|
||||
1,
|
||||
"the durable refusal changed no capacity"
|
||||
);
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn legacy_cleanup_and_cancel_never_remove_a_task_linked_intent() {
|
||||
let database = common::TestDatabase::new().await;
|
||||
// Fresh schema: the first connection applies the migration, later pools reuse the same schema.
|
||||
let _migrated = database.registry().await;
|
||||
let registry = database.concurrent_registry(4).await;
|
||||
let store = store_with(registry.pool().clone(), 8);
|
||||
let admission =
|
||||
PostgresExecutionAdmission::new(registry.pool().clone(), limits(8), Default::default())
|
||||
.unwrap();
|
||||
|
||||
let accepted = store
|
||||
.accept(request(&key("k1"), &digest("f1"), AGENT, 1))
|
||||
.await
|
||||
.expect("acceptance");
|
||||
// The linked reserved row looks expired; the legacy TTL cleanup must ignore it.
|
||||
sqlx::query("update execution_admission_entries set expires_at = now() - interval '1 hour'")
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let ticket: i64 =
|
||||
sqlx::query("select ticket_id from execution_admission_entries where task_id = $1")
|
||||
.bind(accepted.task_id.as_uuid())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap()
|
||||
.get("ticket_id");
|
||||
let owner_token: String =
|
||||
sqlx::query("select owner_token from execution_admission_entries where ticket_id = $1")
|
||||
.bind(ticket)
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap()
|
||||
.get("owner_token");
|
||||
|
||||
// A legacy attempt runs the bounded expiry cleanup; a foreign/own legacy cancel is refused.
|
||||
let _ = admission
|
||||
.admit(AdmissionRequest {
|
||||
scope: AdmissionScope {
|
||||
workspace_id: WORKSPACE.to_owned(),
|
||||
agent_key: "agent_b".to_owned(),
|
||||
operation_id: "op_sync".to_owned(),
|
||||
operation_version: 1,
|
||||
},
|
||||
mode: AdmissionMode::Synchronous,
|
||||
policy_mode: ToolExecutionMode::Synchronous,
|
||||
no_tasks_fallback: NoTasksFallback::Synchronous,
|
||||
approval: ApprovalEvidence::NotRequired,
|
||||
fingerprint: "fp_sync".to_owned(),
|
||||
expires_at_unix_ms: current_unix_ms() + 50,
|
||||
})
|
||||
.await;
|
||||
assert!(!admission.cancel(ticket as u64, &owner_token).await.unwrap());
|
||||
assert_eq!(row_counts(registry.pool()).await, (1, 1));
|
||||
assert_eq!(
|
||||
store
|
||||
.read(&access(AGENT), accepted.task_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.state,
|
||||
TaskState::Queued
|
||||
);
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn terminal_transition_has_one_winner_and_an_immutable_result() {
|
||||
let database = common::TestDatabase::new().await;
|
||||
// Fresh schema: the first connection applies the migration, later pools reuse the same schema.
|
||||
let _migrated = database.registry().await;
|
||||
let registry = database.concurrent_registry(4).await;
|
||||
let store = store_with(registry.pool().clone(), 8);
|
||||
|
||||
let accepted = store
|
||||
.accept(request(&key("k1"), &digest("f1"), AGENT, 30_000))
|
||||
.await
|
||||
.unwrap();
|
||||
let queued = store.read(&access(AGENT), accepted.task_id).await.unwrap();
|
||||
assert_eq!(queued.version, 1);
|
||||
|
||||
// Moving a queued Task straight to completed is not an allowed transition.
|
||||
let skipped = TaskFinishRequest {
|
||||
access: access(AGENT),
|
||||
task_id: accepted.task_id,
|
||||
expected_state: TaskState::Queued,
|
||||
expected_version: queued.version,
|
||||
target_state: TaskState::Completed,
|
||||
result: Some(TaskEnvelope::try_redacted(&json!({"ok": true})).unwrap()),
|
||||
error: None,
|
||||
};
|
||||
assert_eq!(
|
||||
store
|
||||
.finish(skipped)
|
||||
.await
|
||||
.expect_err("transition rejected"),
|
||||
TaskError::Invalid {
|
||||
message: "task state transition is not allowed".to_owned()
|
||||
}
|
||||
);
|
||||
|
||||
let started = TaskFinishRequest {
|
||||
access: access(AGENT),
|
||||
task_id: accepted.task_id,
|
||||
expected_state: TaskState::Queued,
|
||||
expected_version: queued.version,
|
||||
target_state: TaskState::Working,
|
||||
result: None,
|
||||
error: None,
|
||||
};
|
||||
assert_eq!(
|
||||
store
|
||||
.finish(started)
|
||||
.await
|
||||
.expect_err("working is not terminal"),
|
||||
TaskError::Invalid {
|
||||
message: "task finish target is not terminal".to_owned()
|
||||
}
|
||||
);
|
||||
sqlx::query("update tasks set state = 'working' where task_id = $1")
|
||||
.bind(accepted.task_id.as_uuid())
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
let working = store.read(&access(AGENT), accepted.task_id).await.unwrap();
|
||||
|
||||
let mut finishers = Vec::new();
|
||||
for marker in ["first", "second"] {
|
||||
let store = store.clone();
|
||||
let mut finish = TaskFinishRequest {
|
||||
access: access(AGENT),
|
||||
task_id: accepted.task_id,
|
||||
expected_state: TaskState::Working,
|
||||
expected_version: working.version,
|
||||
target_state: TaskState::Completed,
|
||||
result: Some(TaskEnvelope::try_redacted(&json!({"marker": marker})).unwrap()),
|
||||
error: None,
|
||||
};
|
||||
finish.target_state = TaskState::Completed;
|
||||
finishers.push(tokio::spawn(async move { store.finish(finish).await }));
|
||||
}
|
||||
let first = finishers.remove(0).await.unwrap();
|
||||
let second = finishers.remove(0).await.unwrap();
|
||||
let winners = [&first, &second]
|
||||
.iter()
|
||||
.filter(|result| result.is_ok())
|
||||
.count();
|
||||
assert_eq!(winners, 1, "exactly one concurrent CAS wins");
|
||||
let loser = if first.is_err() { &first } else { &second };
|
||||
assert_eq!(
|
||||
loser.as_ref().err().unwrap(),
|
||||
&TaskError::StateConflict,
|
||||
"the loser observes a rejected transition, not a rewrite"
|
||||
);
|
||||
|
||||
let terminal = store.read(&access(AGENT), accepted.task_id).await.unwrap();
|
||||
assert_eq!(terminal.state, TaskState::Completed);
|
||||
assert_eq!(terminal.version, working.version + 1);
|
||||
let marker = terminal.result.as_ref().unwrap().value()["marker"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
assert!(marker == "first" || marker == "second");
|
||||
|
||||
// A repeated terminal write and a terminal->terminal move are rejected.
|
||||
let repeated = TaskFinishRequest {
|
||||
access: access(AGENT),
|
||||
task_id: accepted.task_id,
|
||||
expected_state: TaskState::Completed,
|
||||
expected_version: terminal.version,
|
||||
target_state: TaskState::Failed,
|
||||
result: None,
|
||||
error: Some(TaskEnvelope::try_redacted(&json!({"reason": "x"})).unwrap()),
|
||||
};
|
||||
assert!(repeated.validate().is_err());
|
||||
|
||||
// Terminal Task and its dispatch intent left together.
|
||||
assert_eq!(row_counts(registry.pool()).await, (1, 0));
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn retention_is_bounded_and_never_deletes_live_work() {
|
||||
let database = common::TestDatabase::new().await;
|
||||
// Fresh schema: the first connection applies the migration, later pools reuse the same schema.
|
||||
let _migrated = database.registry().await;
|
||||
let registry = database.concurrent_registry(4).await;
|
||||
let store = store_with(registry.pool().clone(), 8);
|
||||
|
||||
let queued = store
|
||||
.accept(request(&key("k1"), &digest("f1"), AGENT, 30_000))
|
||||
.await
|
||||
.unwrap();
|
||||
let expired_queued = store
|
||||
.accept(request(&key("k2"), &digest("f2"), AGENT, 1))
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"update tasks set execution_deadline = now() - interval '1 hour' where task_id = $1",
|
||||
)
|
||||
.bind(expired_queued.task_id.as_uuid())
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
// A retained terminal Task whose retention has not expired yet and one that has.
|
||||
let terminal = store
|
||||
.accept(request(&key("k3"), &digest("f3"), AGENT, 30_000))
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"update tasks set state = 'completed', result_envelope = '{\"ok\":true}'::jsonb,
|
||||
retain_until = now() + interval '1 hour' where task_id = $1",
|
||||
)
|
||||
.bind(terminal.task_id.as_uuid())
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("delete from execution_admission_entries where task_id = $1")
|
||||
.bind(terminal.task_id.as_uuid())
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
let expired_terminal = store
|
||||
.accept(request(&key("k4"), &digest("f4"), AGENT, 30_000))
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"update tasks set state = 'cancelled', execution_deadline = now() - interval '2 hours',
|
||||
retain_until = now() - interval '1 hour'
|
||||
where task_id = $1",
|
||||
)
|
||||
.bind(expired_terminal.task_id.as_uuid())
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("delete from execution_admission_entries where task_id = $1")
|
||||
.bind(expired_terminal.task_id.as_uuid())
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let report = store.purge_expired(64).await.unwrap();
|
||||
assert_eq!(report.expired_queued, 1);
|
||||
assert_eq!(report.expired_terminal, 1);
|
||||
|
||||
// Live queued work is never deleted or failed; the expired queued Task released its slot.
|
||||
assert_eq!(
|
||||
store
|
||||
.read(&access(AGENT), queued.task_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.state,
|
||||
TaskState::Queued
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.read(&access(AGENT), terminal.task_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.state,
|
||||
TaskState::Completed
|
||||
);
|
||||
assert!(matches!(
|
||||
store
|
||||
.read(&access(AGENT), expired_queued.task_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.state,
|
||||
TaskState::Failed
|
||||
));
|
||||
assert!(
|
||||
store
|
||||
.read(&access(AGENT), expired_terminal.task_id)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
let remaining: i64 = sqlx::query("select count(*)::bigint as count from execution_admission_entries where task_id is not null")
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap()
|
||||
.get("count");
|
||||
assert_eq!(remaining, 1, "only the live queued Task keeps its intent");
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn foreign_scope_reads_are_not_found_and_never_leak_payload() {
|
||||
let database = common::TestDatabase::new().await;
|
||||
// Fresh schema: the first connection applies the migration, later pools reuse the same schema.
|
||||
let _migrated = database.registry().await;
|
||||
let registry = database.concurrent_registry(4).await;
|
||||
let store = store_with(registry.pool().clone(), 8);
|
||||
|
||||
let accepted = store
|
||||
.accept(request(&key("k1"), &digest("f1"), AGENT, 30_000))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Positive control: the owner reads its Task.
|
||||
assert!(store.read(&access(AGENT), accepted.task_id).await.is_ok());
|
||||
|
||||
// Foreign owner, foreign authorization scope and foreign workspace are all not-found.
|
||||
let mut foreign_owner = access(AGENT);
|
||||
foreign_owner.owner_id = "agent_b".to_owned();
|
||||
assert_eq!(
|
||||
store
|
||||
.read(&foreign_owner, accepted.task_id)
|
||||
.await
|
||||
.unwrap_err(),
|
||||
TaskError::NotFound
|
||||
);
|
||||
let mut foreign_scope = access(AGENT);
|
||||
foreign_scope.authorization_scope = "credential:pk_other".to_owned();
|
||||
assert_eq!(
|
||||
store
|
||||
.read(&foreign_scope, accepted.task_id)
|
||||
.await
|
||||
.unwrap_err(),
|
||||
TaskError::NotFound
|
||||
);
|
||||
let mut foreign_workspace = access(AGENT);
|
||||
foreign_workspace.workspace_id = "ws_other".to_owned();
|
||||
assert_eq!(
|
||||
store
|
||||
.read(&foreign_workspace, accepted.task_id)
|
||||
.await
|
||||
.unwrap_err(),
|
||||
TaskError::NotFound
|
||||
);
|
||||
|
||||
// The same caller key under a foreign owner creates its own Task, never a visible collision.
|
||||
let other = store
|
||||
.accept(request(&key("k1"), &digest("f1"), "agent_b", 30_000))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_ne!(other.task_id, accepted.task_id);
|
||||
assert_eq!(row_counts(registry.pool()).await, (2, 2));
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_bounded_envelope_is_rejected_before_persistence() {
|
||||
let database = common::TestDatabase::new().await;
|
||||
// Fresh schema: the first connection applies the migration, later pools reuse the same schema.
|
||||
let _migrated = database.registry().await;
|
||||
let registry = database.concurrent_registry(4).await;
|
||||
let store = store_with(registry.pool().clone(), 8);
|
||||
|
||||
assert!(
|
||||
TaskEnvelope::try_redacted(&json!({"blob": "x".repeat(64 * 1024)})).is_err(),
|
||||
"an oversized envelope is rejected before any accept"
|
||||
);
|
||||
|
||||
let mut invalid = request(&key("k1"), &digest("f1"), AGENT, 30_000);
|
||||
invalid.scoped_key = "short".to_owned();
|
||||
assert!(matches!(invalid.validate(), Err(TaskError::Invalid { .. })));
|
||||
assert_eq!(
|
||||
store.accept(invalid).await.unwrap_err(),
|
||||
TaskError::Invalid {
|
||||
message: "task scoped key digest is invalid".to_owned()
|
||||
}
|
||||
);
|
||||
assert_eq!(row_counts(registry.pool()).await, (0, 0));
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn store_failure_fails_closed_without_records() {
|
||||
let database = common::TestDatabase::new().await;
|
||||
// No migration on this schema: the durable Task state does not exist yet.
|
||||
let unmigrated = database.raw_pool().await;
|
||||
let store = store_with(unmigrated, 8);
|
||||
|
||||
assert!(store.health().await.is_err());
|
||||
let error = store
|
||||
.accept(request(&key("k1"), &digest("f1"), AGENT, 30_000))
|
||||
.await
|
||||
.expect_err("acceptance fails closed");
|
||||
assert!(matches!(error, TaskError::Unavailable { .. }));
|
||||
|
||||
database.cleanup().await;
|
||||
}
|
||||
Reference in new issue
Block a user