feat(epic4): безопасные повторы и отмена durable Task (Story 4.4)
CI / UI Checks (pull_request) Successful in 8s
CI / Rust Checks (pull_request) Successful in 20m46s
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

Durable per-outbound attempt до отправки запроса, bounded retry/read,
server-owned verified writes, честный cancel/unknown, deadline/fencing,
additive schema v29. Staged renames task.rs/tasks.rs разложены на модули.

Includes disclosed cosmetic parity exception: единственная правка вне
принятой дельты — удалена лишняя пустая строка в конце
scripts/ci-story-checks.sh (EOF blank line); story-код не менялся.
This commit is contained in:
bsodfather committed 2026-10-30 12:21:57 +00:00
1 parent 8c02380762
commit a3057de51e
44 files changed
+4547 -815

No files matched your search

@@ -76,6 +76,7 @@ async fn controlled_authority_is_versioned_and_safe_under_concurrent_apply() {
(26, "durable-tasks-v26"),
(27, "durable-tasks-v27"),
(28, "durable-tasks-v28"),
(29, "durable-tasks-v29"),
];
assert_eq!(rows.len(), expected.len());
for (row, (version, name)) in rows.iter().zip(expected) {
@@ -186,7 +187,7 @@ async fn controlled_authority_is_versioned_and_safe_under_concurrent_apply() {
);
assert_eq!(
MigrationAuthority::preflight(first.pool()).await.unwrap(),
MigrationPreflight::Current { version: 28 }
MigrationPreflight::Current { version: 29 }
);
}
#[tokio::test]
@@ -234,7 +235,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: 28 },
MigrationPreflight::Current { version: 29 },
"restoring the exact V18 contract must return the current verdict"
);
}
@@ -360,7 +361,7 @@ async fn ledgerless_legacy_baseline_is_consolidated_without_data_loss() {
MigrationAuthority::preflight(&pool).await.unwrap(),
MigrationPreflight::MigrationRequired {
current: 0,
target: 28,
target: 29,
}
);
MigrationAuthority::apply(&pool).await.unwrap();
@@ -473,13 +474,13 @@ async fn healthy_v2_is_reported_as_migration_required_and_upgrades_to_v3() {
MigrationAuthority::preflight(&pool).await.unwrap(),
MigrationPreflight::MigrationRequired {
current: 2,
target: 28,
target: 29,
}
);
MigrationAuthority::apply(&pool).await.unwrap();
assert_eq!(
MigrationAuthority::preflight(&pool).await.unwrap(),
MigrationPreflight::Current { version: 28 }
MigrationPreflight::Current { version: 29 }
);
let trace_column: bool = sqlx::query_scalar(
"select exists (
@@ -522,7 +523,7 @@ async fn healthy_v3_upgrades_to_v4_with_honest_legacy_snapshot_provenance() {
MigrationAuthority::preflight(&pool).await.unwrap(),
MigrationPreflight::MigrationRequired {
current: 3,
target: 28,
target: 29,
}
);
MigrationAuthority::apply(&pool).await.unwrap();
@@ -582,7 +583,7 @@ async fn healthy_v4_upgrades_to_v5_without_fabricating_legacy_outcomes() {
MigrationAuthority::preflight(&pool).await.unwrap(),
MigrationPreflight::MigrationRequired {
current: 4,
target: 28,
target: 29,
}
);
MigrationAuthority::apply(&pool).await.unwrap();
@@ -836,6 +837,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: 28 }
MigrationPreflight::Current { version: 29 }
);
}
@@ -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: 28,
target: 29,
}
);
@@ -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: 28 },
MigrationPreflight::Current { version: 29 },
"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: 28 },
MigrationPreflight::Current { version: 29 },
"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: 28 },
MigrationPreflight::Current { version: 29 },
"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: 28 }
MigrationPreflight::Current { version: 29 }
);
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: 28 },
MigrationPreflight::Current { version: 29 },
"restore: {restore}"
);
}
@@ -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: 28 },
MigrationPreflight::Current { version: 29 },
"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: 28 }
MigrationPreflight::Current { version: 29 }
);
}
@@ -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: 28 },
MigrationPreflight::Current { version: 29 },
"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: 28 }));
let restored_current = matches!(restored, Ok(MigrationPreflight::Current { version: 29 }));
// Точное восстановление доказывается сравнением снятого снимка с 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: 28 },
MigrationPreflight::Current { version: 29 },
"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: 28 },
MigrationPreflight::Current { version: 29 },
"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: 28 },
MigrationPreflight::Current { version: 29 },
"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: 28 }
MigrationPreflight::Current { version: 29 }
);
assert!(
@@ -22,16 +22,16 @@ async fn clean_legacy_ledger_upgrades_to_v28_after_v25_removal() {
MigrationAuthority::preflight(&pool).await.unwrap(),
MigrationPreflight::MigrationRequired {
current: 24,
target: 28,
target: 29,
}
);
assert_eq!(
MigrationAuthority::apply(&pool).await.unwrap(),
MigrationApplyResult::Applied { from: 24, to: 28 }
MigrationApplyResult::Applied { from: 24, to: 29 }
);
assert_eq!(
MigrationAuthority::preflight(&pool).await.unwrap(),
MigrationPreflight::Current { version: 28 }
MigrationPreflight::Current { version: 29 }
);
}
@@ -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: 28 }
MigrationPreflight::Current { version: 29 }
);
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: 28,
target: 29,
}
);
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: 28,
target: 29,
}
);
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: 28 }
MigrationPreflight::Current { version: 29 }
);
}
@@ -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: 28,
target: 29,
}
);
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: 28 }
MigrationPreflight::Current { version: 29 }
);
}
@@ -262,7 +262,7 @@ async fn published_initial_mcp_layout_is_accepted() {
MigrationAuthority::preflight(&pool).await.unwrap(),
MigrationPreflight::MigrationRequired {
current: 0,
target: 28,
target: 29,
}
);
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: 28 }
MigrationPreflight::Current { version: 29 }
);
}
@@ -314,13 +314,13 @@ async fn published_in_place_mcp_upgrade_layout_is_accepted() {
MigrationAuthority::preflight(&pool).await.unwrap(),
MigrationPreflight::MigrationRequired {
current: 0,
target: 28,
target: 29,
}
);
MigrationAuthority::apply(&pool).await.unwrap();
assert_eq!(
MigrationAuthority::preflight(&pool).await.unwrap(),
MigrationPreflight::Current { version: 28 }
MigrationPreflight::Current { version: 29 }
);
}
@@ -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: 28 }
MigrationPreflight::Current { version: 29 }
);
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: 28,
target: 29,
}
);
assert_eq!(
MigrationAuthority::apply(&pool).await.unwrap(),
MigrationApplyResult::Applied { from: 18, to: 28 }
MigrationApplyResult::Applied { from: 18, to: 29 }
);
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: 28 }
MigrationPreflight::Current { version: 29 }
);
}
@@ -161,7 +161,7 @@ async fn failed_v19_migration_rolls_back_schema_and_ledger() {
MigrationAuthority::preflight(&pool).await.unwrap(),
MigrationPreflight::MigrationRequired {
current: 18,
target: 28,
target: 29,
}
);
}
@@ -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: 28,
target: 29,
}
);
}
@@ -9,10 +9,11 @@ use super::common;
use crank_core::{
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,
BeginAttempt, 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,
@@ -60,6 +61,7 @@ fn request(key: &str, fingerprint: &str, agent: &str, deadline_in_ms: i64) -> Ta
execution_deadline_unix_ms: deadline,
retain_until_unix_ms: deadline + 3_600_000,
approval_reference: Some("appr_1".to_owned()),
retry: crank_core::TaskRetryPolicy::single_attempt(),
},
scoped_key: key.to_owned(),
input_fingerprint: fingerprint.to_owned(),
@@ -708,28 +710,38 @@ async fn task_worker_lease_and_fencing_contract() {
// checkpoint dispatch once
let checkpointed = store
.checkpoint_dispatch(
"worker_1",
lease.record.task_id,
lease.fence,
"attempt-1".to_owned(),
)
.checkpoint_dispatch(BeginAttempt {
task_id: lease.record.task_id,
owner: "worker_1".to_owned(),
fence: lease.fence,
expected_version: lease.record.version,
attempt_id: "attempt-1".to_owned(),
input_fingerprint: lease.record.input_fingerprint.clone(),
upstream_key_digest: None,
retry_allowed: true,
})
.await
.unwrap();
assert_eq!(checkpointed.attempt.attempt_id, "attempt-1");
assert_eq!(checkpointed.attempt.ordinal, 1);
assert!(checkpointed.task.dispatch_started_at_unix_ms.is_some());
assert_eq!(
checkpointed.current_attempt_id.as_deref(),
checkpointed.task.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(),
)
.checkpoint_dispatch(BeginAttempt {
task_id: lease.record.task_id,
owner: "worker_1".to_owned(),
fence: lease.fence,
expected_version: checkpointed.task.version,
attempt_id: "attempt-2".to_owned(),
input_fingerprint: lease.record.input_fingerprint.clone(),
upstream_key_digest: None,
retry_allowed: true,
})
.await;
assert!(second.is_err());
@@ -902,4 +914,5 @@ fn authority_key(
}
}
mod task_attempts;
mod task_worker;
@@ -0,0 +1,534 @@
use super::*;
use crank_core::{
AttemptOutcome, AttemptOutcomeClass, AttemptPhase, AttemptResolution, BeginAttempt,
TaskCancelOutcome, TaskCancelRequest, TaskRetryPolicy,
};
use serde_json::json;
#[tokio::test]
async fn cancel_before_checkpoint_wins_race_with_claim_and_never_dispatches() {
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("cancel_before_1"),
&digest("fb1"),
AGENT,
30_000,
))
.await
.unwrap();
let outcome = store
.cancel(TaskCancelRequest {
access: access(AGENT),
task_id: created.task_id,
expected_version: None,
reason: "cancel before dispatch".to_owned(),
})
.await
.unwrap();
match outcome {
TaskCancelOutcome::Cancelled(record) => assert_eq!(record.state, TaskState::Cancelled),
other => panic!("expected Cancelled, got {other:?}"),
}
let claims = store.claim_batch("worker", 4, 10_000).await.unwrap();
assert!(claims.is_empty(), "cancelled task must not be claimed");
let attempts = store
.attempts(&access(AGENT), created.task_id)
.await
.unwrap();
assert!(attempts.is_empty(), "no attempts for cancelled task");
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, "dispatch intent must be removed");
database.cleanup().await;
}
#[tokio::test]
async fn cancel_after_checkpoint_is_uncertain_and_never_cancelled_or_retried() {
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("cancel_after_1"),
&digest("fa1"),
AGENT,
30_000,
))
.await
.unwrap();
let leases = store.claim_batch("worker", 1, 10_000).await.unwrap();
let lease = leases.into_iter().next().expect("claim");
let leased = store
.checkpoint_dispatch(BeginAttempt {
task_id: lease.record.task_id,
owner: "worker".to_owned(),
fence: lease.fence,
expected_version: lease.record.version,
attempt_id: "attempt-cancel-after".to_owned(),
input_fingerprint: lease.record.input_fingerprint.clone(),
upstream_key_digest: None,
retry_allowed: true,
})
.await
.expect("checkpoint");
let outcome = store
.cancel(TaskCancelRequest {
access: access(AGENT),
task_id: created.task_id,
expected_version: None,
reason: "cancel after checkpoint".to_owned(),
})
.await
.unwrap();
match outcome {
TaskCancelOutcome::OutcomeUnknown(record) => {
assert_eq!(record.state, TaskState::OutcomeUnknown)
}
other => panic!("expected OutcomeUnknown, got {other:?}"),
}
let record = store.read(&access(AGENT), created.task_id).await.unwrap();
assert_eq!(record.state, TaskState::OutcomeUnknown);
let attempts = store
.attempts(&access(AGENT), created.task_id)
.await
.unwrap();
assert_eq!(attempts.len(), 1);
assert_eq!(
attempts[0].outcome,
Some(AttemptOutcomeClass::OutcomeUnknown)
);
// Repeated cancel stays uncertain.
let outcome2 = store
.cancel(TaskCancelRequest {
access: access(AGENT),
task_id: created.task_id,
expected_version: None,
reason: "cancel after checkpoint".to_owned(),
})
.await
.unwrap();
assert!(matches!(outcome2, TaskCancelOutcome::OutcomeUnknown(_)));
// finish_leased by the original lease must be rejected.
let finish = store
.finish_leased(
TaskFinishRequest {
access: access(AGENT),
task_id: created.task_id,
expected_state: leased.task.state,
expected_version: leased.task.version,
target_state: TaskState::Completed,
result: Some(TaskEnvelope::try_redacted(&json!({"ok": true})).unwrap()),
error: None,
},
"worker",
leased.attempt.fence,
)
.await;
assert!(matches!(finish, Err(TaskError::StateConflict)));
let claims2 = store.claim_batch("worker2", 4, 10_000).await.unwrap();
assert!(
!claims2.iter().any(|l| l.record.task_id == created.task_id),
"outcome unknown task must never be claimed"
);
database.cleanup().await;
}
#[tokio::test]
async fn checkpoint_and_resolve_are_cas_guarded_and_history_is_immutable() {
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("cas_1"), &digest("fc1"), AGENT, 30_000))
.await
.unwrap();
let leases = store.claim_batch("worker", 1, 10_000).await.unwrap();
let lease = leases.into_iter().next().expect("claim");
let first_version = lease.record.version;
let committed = store
.checkpoint_dispatch(BeginAttempt {
task_id: lease.record.task_id,
owner: "worker".to_owned(),
fence: lease.fence,
expected_version: lease.record.version,
attempt_id: "attempt-cas".to_owned(),
input_fingerprint: lease.record.input_fingerprint.clone(),
upstream_key_digest: None,
retry_allowed: false,
})
.await
.expect("first checkpoint");
let committed_lease = committed;
// Repeated checkpoint with the same old version -> StateConflict.
let second = store
.checkpoint_dispatch(BeginAttempt {
task_id: lease.record.task_id,
owner: "worker".to_owned(),
fence: lease.fence,
expected_version: first_version,
attempt_id: "attempt-cas-2".to_owned(),
input_fingerprint: lease.record.input_fingerprint.clone(),
upstream_key_digest: None,
retry_allowed: false,
})
.await;
assert!(matches!(second, Err(TaskError::StateConflict)));
// resolve with a modified lease task version -> StateConflict.
let mut bad_lease = committed_lease.clone();
bad_lease.task.version = first_version;
let bad_resolve = store
.resolve_attempt(
&bad_lease,
AttemptOutcome::Completed(TaskEnvelope::try_redacted(&json!({"ok": true})).unwrap()),
)
.await;
assert!(matches!(bad_resolve, Err(TaskError::StateConflict)));
// Correct resolve -> Finished(Completed).
let ok = store
.resolve_attempt(
&committed_lease,
AttemptOutcome::Completed(TaskEnvelope::try_redacted(&json!({"ok": true})).unwrap()),
)
.await
.expect("resolve");
match ok {
AttemptResolution::Finished(rec) => assert_eq!(rec.state, TaskState::Completed),
other => panic!("expected Finished, got {other:?}"),
}
// Repeated resolve -> StateConflict.
let repeat = store
.resolve_attempt(
&committed_lease,
AttemptOutcome::Completed(TaskEnvelope::try_redacted(&json!({"ok": true})).unwrap()),
)
.await;
assert!(matches!(repeat, Err(TaskError::StateConflict)));
let attempts = store
.attempts(&access(AGENT), created.task_id)
.await
.unwrap();
assert_eq!(attempts.len(), 1, "exactly one immutable attempt record");
assert_eq!(attempts[0].outcome, Some(AttemptOutcomeClass::Completed));
let _ = created;
database.cleanup().await;
}
#[tokio::test]
async fn expired_checkpointed_attempt_recovers_only_with_safe_retry_evidence() {
let database = common::TestDatabase::new().await;
let registry = database.registry().await;
let store = store_with(registry.pool().clone(), 8);
// Task A: retry policy allows 2 attempts, retry_allowed=true.
let mut req_a = request(&key("rec_a"), &digest("fa"), AGENT, 30_000);
req_a.pins.retry = TaskRetryPolicy::new(2, 0);
let created_a = store.accept(req_a).await.unwrap();
// Task B: single attempt, retry_allowed=false.
let created_b = store
.accept(request(&key("rec_b"), &digest("fb"), AGENT, 30_000))
.await
.unwrap();
let claims = store.claim_batch("worker_dead", 2, 150).await.unwrap();
assert_eq!(claims.len(), 2);
let lease_a = claims
.iter()
.find(|l| l.record.task_id == created_a.task_id)
.cloned()
.expect("claim A");
let lease_b = claims
.iter()
.find(|l| l.record.task_id == created_b.task_id)
.cloned()
.expect("claim B");
store
.checkpoint_dispatch(BeginAttempt {
task_id: lease_b.record.task_id,
owner: "worker_dead".to_owned(),
fence: lease_b.fence,
expected_version: lease_b.record.version,
attempt_id: "attempt-b".to_owned(),
input_fingerprint: lease_b.record.input_fingerprint.clone(),
upstream_key_digest: None,
retry_allowed: false,
})
.await
.expect("checkpoint B");
store
.checkpoint_dispatch(BeginAttempt {
task_id: lease_a.record.task_id,
owner: "worker_dead".to_owned(),
fence: lease_a.fence,
expected_version: lease_a.record.version,
attempt_id: "attempt-a".to_owned(),
input_fingerprint: lease_a.record.input_fingerprint.clone(),
upstream_key_digest: None,
retry_allowed: true,
})
.await
.expect("checkpoint A");
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
let recovered = store.claim_batch("worker_live", 4, 10_000).await.unwrap();
let lease_a2 = recovered
.iter()
.find(|l| l.record.task_id == created_a.task_id)
.cloned()
.expect("A recovered");
assert!(lease_a2.fence > lease_a.fence, "recovery bumps fence");
assert!(
matches!(
lease_a2.record.state,
TaskState::Working | TaskState::Queued
),
"A state working/queued"
);
assert!(
!recovered
.iter()
.any(|l| l.record.task_id == created_b.task_id),
"B must not be redispatched"
);
let record_b = store.read(&access(AGENT), created_b.task_id).await.unwrap();
assert_eq!(record_b.state, TaskState::OutcomeUnknown);
// A prior attempt resolved as uncertain.
let attempts_a = store
.attempts(&access(AGENT), created_a.task_id)
.await
.unwrap();
assert!(!attempts_a.is_empty());
assert_eq!(
attempts_a[0].outcome,
Some(AttemptOutcomeClass::OutcomeUnknown)
);
// Further scans do not hand B back.
assert!(
store
.claim_batch("worker_live", 4, 10_000)
.await
.unwrap()
.iter()
.all(|l| l.record.task_id != created_b.task_id)
);
database.cleanup().await;
}
#[tokio::test]
async fn before_dispatch_failed_attempt_does_not_erase_recorded_uncertainty() {
let database = common::TestDatabase::new().await;
let registry = database.registry().await;
let store = store_with(registry.pool().clone(), 8);
let mut req = request(&key("bd_1"), &digest("fbd"), AGENT, 30_000);
req.pins.retry = TaskRetryPolicy::new(2, 0);
let created = store.accept(req).await.unwrap();
let leases = store.claim_batch("worker", 1, 10_000).await.unwrap();
let lease_a = leases.into_iter().next().expect("claim A");
let committed_a = store
.checkpoint_dispatch(BeginAttempt {
task_id: lease_a.record.task_id,
owner: "worker".to_owned(),
fence: lease_a.fence,
expected_version: lease_a.record.version,
attempt_id: "attempt-a".to_owned(),
input_fingerprint: lease_a.record.input_fingerprint.clone(),
upstream_key_digest: None,
retry_allowed: true,
})
.await
.expect("checkpoint A");
// Attempt A resolves to a bounded retry (uncertain outcome).
let retry = store
.resolve_attempt(
&committed_a,
AttemptOutcome::Uncertain {
error: TaskEnvelope::try_redacted(
&json!({"code":"outcome_unknown","phase":"dispatched"}),
)
.unwrap(),
repeatable: true,
phase: AttemptPhase::Dispatched,
},
)
.await
.expect("resolve A");
let retry_task = match retry {
AttemptResolution::RetryAt { task, .. } => task,
other => panic!("expected RetryAt, got {other:?}"),
};
assert_eq!(retry_task.state, TaskState::Working);
assert!(retry_task.current_attempt_id.is_none());
let retry_version = retry_task.version;
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
// The Task keeps its lease across the pinned backoff: the next attempt checkpoints under the
// same owner/fence and the version the RetryAt record reported.
let committed_b_result = store
.checkpoint_dispatch(BeginAttempt {
task_id: retry_task.task_id,
owner: "worker".to_owned(),
fence: lease_a.fence,
expected_version: retry_version,
attempt_id: "attempt-b".to_owned(),
input_fingerprint: retry_task.input_fingerprint.clone(),
upstream_key_digest: None,
retry_allowed: false,
})
.await;
let committed_b = committed_b_result.expect("checkpoint B");
// Attempt B never reached upstream: a before_dispatch failure must NOT overwrite
// the recorded uncertainty of the previously dispatched attempt.
let resolution = store
.resolve_attempt(
&committed_b,
AttemptOutcome::Failed {
error: TaskEnvelope::try_redacted(
&json!({"code":"shutdown_before_dispatch","phase":"before_dispatch"}),
)
.unwrap(),
retryable: false,
phase: AttemptPhase::BeforeDispatch,
},
)
.await
.expect("resolve B");
match resolution {
AttemptResolution::Unknown(record) => assert_eq!(record.state, TaskState::OutcomeUnknown),
other => panic!("expected Unknown, got {other:?}"),
}
let record = store.read(&access(AGENT), created.task_id).await.unwrap();
assert_eq!(record.state, TaskState::OutcomeUnknown);
assert!(record.result.is_none());
let error = record.error.expect("error envelope present");
assert_eq!(error.value()["code"], json!("shutdown_before_dispatch"));
assert_eq!(error.value()["phase"], json!("dispatched"));
assert_eq!(record.attempts, 2);
let attempts = store
.attempts(&access(AGENT), created.task_id)
.await
.unwrap();
assert_eq!(attempts.len(), 2);
assert_eq!(
attempts[0].outcome,
Some(AttemptOutcomeClass::RetryScheduled)
);
assert_eq!(
attempts[0].certainty,
Some(crank_core::AttemptCertainty::Unknown)
);
assert_eq!(attempts[0].phase, Some(AttemptPhase::Dispatched));
assert_eq!(attempts[1].outcome, Some(AttemptOutcomeClass::Failed));
assert_eq!(
attempts[1].certainty,
Some(crank_core::AttemptCertainty::Known)
);
assert_eq!(attempts[1].phase, Some(AttemptPhase::BeforeDispatch));
// Repeated read/cancel must not turn the state terminal.
let again = store.read(&access(AGENT), created.task_id).await.unwrap();
assert_eq!(again.state, TaskState::OutcomeUnknown);
database.cleanup().await;
}
#[tokio::test]
async fn before_dispatch_failed_single_attempt_stays_failed() {
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("bd_single"), &digest("fbf"), AGENT, 30_000))
.await
.unwrap();
let leases = store.claim_batch("worker", 1, 10_000).await.unwrap();
let lease = leases.into_iter().next().expect("claim");
let committed = store
.checkpoint_dispatch(BeginAttempt {
task_id: lease.record.task_id,
owner: "worker".to_owned(),
fence: lease.fence,
expected_version: lease.record.version,
attempt_id: "attempt-single".to_owned(),
input_fingerprint: lease.record.input_fingerprint.clone(),
upstream_key_digest: None,
retry_allowed: false,
})
.await
.expect("checkpoint");
let resolution = store
.resolve_attempt(
&committed,
AttemptOutcome::Failed {
error: TaskEnvelope::try_redacted(
&json!({"code":"shutdown_before_dispatch","phase":"before_dispatch"}),
)
.unwrap(),
retryable: false,
phase: AttemptPhase::BeforeDispatch,
},
)
.await
.expect("resolve");
match resolution {
AttemptResolution::Finished(record) => assert_eq!(record.state, TaskState::Failed),
other => panic!("expected Finished, got {other:?}"),
}
let record = store.read(&access(AGENT), created.task_id).await.unwrap();
assert_eq!(record.state, TaskState::Failed);
let error = record.error.expect("error envelope present");
assert_eq!(error.value()["phase"], json!("before_dispatch"));
database.cleanup().await;
}
@@ -87,12 +87,16 @@ async fn task_worker_expired_checkpointed_attempt_becomes_outcome_unknown_withou
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(),
)
.checkpoint_dispatch(BeginAttempt {
task_id: lease.record.task_id,
owner: "worker_dead".to_owned(),
fence: lease.fence,
expected_version: lease.record.version,
attempt_id: "attempt-uncertain".to_owned(),
input_fingerprint: lease.record.input_fingerprint.clone(),
upstream_key_digest: None,
retry_allowed: false,
})
.await
.expect("durable dispatch checkpoint");