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

+151 -103
View File
@@ -1,6 +1,10 @@
//! Application-level durable Task handler for Story 4.3.
//! Application-level durable Task handler and attempt authority (Story 4.3/4.4).
//!
//! The handler owns everything that touches product authority: the exact published pin, the typed
//! Platform API key, the approval policy, the encrypted executable input and the resolved upstream
//! auth. The runtime owns the single bounded retry loop and the durable attempt checkpoint/resolution;
//! this module only revalidates and prepares one attempt at a time.
use std::sync::Arc;
use std::time::{Duration, Instant};
use async_trait::async_trait;
@@ -12,9 +16,11 @@ use crank_core::{
use crank_registry::PostgresRegistry;
use crank_registry::PublishedAgentTool;
use crank_runtime::{
ExecutionAuthorization, ExecutionRequestError, RuntimeExecutionRequest, RuntimeExecutor,
SecretCrypto, TaskDispatchPermit, TaskHandler, TaskService, TaskWorkerError,
ExecutionAuthorization, RuntimeExecutor, RuntimeOperation, SecretCrypto, TaskAttemptAuthority,
TaskAttemptContext, TaskAttemptOutcome, TaskAttemptPlan, TaskAttemptRefusal, TaskHandler,
TaskService, TaskWorkerError,
};
use sha2::{Digest, Sha256};
use super::TaskApplication;
use super::auth_resolution::resolve_operation_auth_with;
@@ -22,12 +28,31 @@ use super::tool_resolution::runtime_operation;
use crate::access::{allows_scope, credential_allows_security_level};
use crate::catalog::PublishedToolCatalog;
/// Server-owned evidence that one published operation deduplicates repeated sends of the same stable
/// idempotency key.
///
/// The descriptor is constructed by the application for an integration whose upstream contract was
/// actually qualified (key delivery, dedup scope, canonical input binding and a dedup window that
/// covers the pinned retry budget). It is never deserialized from Task input, so a caller key or
/// header alone can never make a write retryable. Production wiring passes an empty set until such a
/// contract exists.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct VerifiedIdempotentWrite {
pub operation_id: String,
pub operation_version: u32,
/// Header through which the stable key is delivered to this exact upstream.
pub key_header: String,
/// Dedup window of the upstream contract, which must cover the pinned retry budget.
pub validity_ms: i64,
}
pub struct TaskWorkerHandler {
registry: PostgresRegistry,
catalog: PublishedToolCatalog,
runtime: RuntimeExecutor,
secret_crypto: SecretCrypto,
service: TaskService,
verified_writes: Vec<VerifiedIdempotentWrite>,
}
impl TaskWorkerHandler {
@@ -46,9 +71,16 @@ impl TaskWorkerHandler {
runtime,
secret_crypto,
service: tasks.task_service(),
verified_writes: Vec::new(),
}
}
/// Registers server-owned verified-idempotency evidence of qualified integrations.
pub fn with_verified_writes(mut self, verified_writes: Vec<VerifiedIdempotentWrite>) -> Self {
self.verified_writes = verified_writes;
self
}
/// Authoritative pre-dispatch authorization of one leased Task (Story 4.3).
///
/// Resolves the exact pinned Published Version in the current publication, repeats the approval
@@ -143,6 +175,74 @@ impl TaskWorkerHandler {
}
Ok(tool)
}
/// Safe-retry classification of one attempt and the stable upstream key digest.
///
/// A read is always safe to repeat. A write is only safe to repeat when this process holds
/// server-owned evidence for the exact published operation and that evidence's dedup window still
/// covers the accepted retry budget; the presence of a client key or an idempotency header alone
/// never qualifies.
fn retry_classification(
&self,
operation: &RuntimeOperation,
input: &serde_json::Value,
retry_window_ms: i64,
) -> (bool, Option<String>) {
if matches!(
&operation.target,
crank_core::Target::Rest(target) if target.method == crank_core::HttpMethod::Get
) {
return (true, None);
}
let Some(policy) = operation.execution_config.idempotency.as_ref() else {
return (false, None);
};
let Some(field) = policy
.input_field
.as_deref()
.filter(|field| !field.trim().is_empty())
else {
return (false, None);
};
let Some(header) = policy
.header_name
.as_deref()
.filter(|value| !value.is_empty())
else {
return (false, None);
};
let key = match input.get(field) {
Some(serde_json::Value::String(value)) if !value.trim().is_empty() => value.clone(),
Some(serde_json::Value::Number(value)) => value.to_string(),
_ => return (false, None),
};
let evidence = self.verified_writes.iter().find(|evidence| {
evidence.operation_id == operation.operation_id.as_str()
&& evidence.operation_version == operation.operation_version
&& evidence.key_header.eq_ignore_ascii_case(header)
&& evidence.validity_ms >= retry_window_ms
});
let Some(evidence) = evidence else {
return (false, None);
};
// Only a digest of the stable key is persisted; the key itself stays in the encrypted input.
let mut digest = Sha256::new();
digest.update(evidence.key_header.as_bytes());
digest.update([0u8]);
digest.update(key.as_bytes());
(true, Some(format!("{:x}", digest.finalize())))
}
/// Maps a preparation failure onto the attempt refusal vocabulary: a transient authority-store
/// outage leaves the Task leased for recovery, everything else is a proven pre-dispatch refusal.
fn refusal(error: TaskError) -> TaskAttemptRefusal {
match error {
TaskError::Unavailable { .. } => TaskAttemptRefusal::Stopped,
_ => TaskAttemptRefusal::Failed {
code: "task_authority_rejected".to_owned(),
},
}
}
}
#[async_trait]
@@ -154,74 +254,54 @@ impl TaskHandler for TaskWorkerHandler {
Ok(())
}
async fn execute(
async fn execute(&self, context: TaskAttemptContext) -> TaskAttemptOutcome {
self.runtime.execute_task_outcome(&context, self).await
}
}
#[async_trait]
impl TaskAttemptAuthority for TaskWorkerHandler {
async fn prepare_attempt(
&self,
lease: &TaskLease,
_attempt_id: &str,
cancelled: Arc<std::sync::atomic::AtomicBool>,
permit: TaskDispatchPermit,
) -> crank_runtime::TaskAttemptOutcome {
use crank_runtime::TaskAttemptOutcome;
use std::sync::atomic::Ordering;
// The lease may have been lost between the checkpoint and the outbound call; never dispatch
// on behalf of a worker that no longer owns the Task.
if cancelled.load(Ordering::Acquire) {
return TaskAttemptOutcome::OutcomeUnknown;
}
let tool = match self.authorize(lease).await {
Ok(tool) => tool,
Err(error) => {
return TaskAttemptOutcome::Failed(serde_json::json!({"code": error.to_string()}));
}
};
let input = match self.service.executable_input(lease).await {
Ok(input) => input,
Err(error) => {
return TaskAttemptOutcome::Failed(serde_json::json!({"code": error.to_string()}));
}
};
) -> Result<TaskAttemptPlan, TaskAttemptRefusal> {
let tool = self.authorize(lease).await.map_err(Self::refusal)?;
let input = self
.service
.executable_input(lease)
.await
.map_err(Self::refusal)?;
let operation = runtime_operation(&tool);
let now_ms = current_unix_ms();
let deadline_ms = lease.record.pins.execution_deadline_unix_ms;
if deadline_ms <= now_ms {
return TaskAttemptOutcome::Failed(
serde_json::json!({"code": "task deadline elapsed"}),
);
// The accepted absolute deadline already elapsed: no further attempt may be dispatched,
// and any previous uncertainty was already recorded as such.
return Err(TaskAttemptRefusal::Failed {
code: "task_deadline_elapsed".to_owned(),
});
}
let deadline = Instant::now()
+ Duration::from_millis((deadline_ms - now_ms).min(i64::MAX as i64) as u64);
let deadline = Instant::now() + Duration::from_millis((deadline_ms - now_ms) as u64);
let workspace_id = WorkspaceId::new(lease.record.workspace_id.as_str());
let agent_id = AgentId::new(lease.record.owner_id.as_str());
let resolved_auth = match resolve_operation_auth_with(
let resolved_auth = resolve_operation_auth_with(
&self.registry,
&self.secret_crypto,
&workspace_id,
&operation.execution_config,
)
.await
{
Ok(auth) => auth,
Err(error) => {
return TaskAttemptOutcome::Failed(
serde_json::json!({ "code": error.to_string() }),
);
}
};
// Continue the parent trace persisted with the accepted Task; the worker's attempt span is a
// child of it, and the executor records the attempt identity. Trace data stays out of labels.
let trace_context = match TraceContext::parse(&lease.record.support.traceparent) {
Ok(context) => context,
Err(_) => {
return TaskAttemptOutcome::Failed(
serde_json::json!({ "code": "task trace parent is invalid" }),
);
}
};
.map_err(|_| TaskAttemptRefusal::Failed {
code: "task_auth_resolution_failed".to_owned(),
})?;
// Continue the parent trace persisted with the accepted Task; every attempt adds its own
// child `adapter_attempt` span carrying the committed durable attempt ID.
let trace_context =
TraceContext::parse(&lease.record.support.traceparent).map_err(|_| {
TaskAttemptRefusal::Failed {
code: "task_trace_parent_invalid".to_owned(),
}
})?;
let request_context = crank_runtime::RuntimeRequestContext::new(
lease.record.support.request_id.clone(),
trace_context,
@@ -231,52 +311,20 @@ impl TaskHandler for TaskWorkerHandler {
Some(agent_id.clone()),
crank_core::InvocationSource::AgentToolCall,
);
let request = match RuntimeExecutionRequest::try_new(
&workspace_id,
ExecutionOrigin::AgentSnapshot,
Some(&agent_id),
&operation,
&input,
ExecutionAuthorization::Authorized,
resolved_auth.as_ref(),
&request_context,
let (retry_allowed, upstream_key_digest) =
self.retry_classification(&operation, &input, deadline_ms - now_ms);
Ok(TaskAttemptPlan {
workspace_id,
origin: ExecutionOrigin::AgentSnapshot,
agent_id: Some(agent_id),
operation,
input,
authorization: ExecutionAuthorization::Authorized,
resolved_auth,
request_context,
deadline,
) {
Ok(request) => request,
Err(error) => {
return TaskAttemptOutcome::Failed(match error {
ExecutionRequestError::InvalidOrigin => {
serde_json::json!({"code": "invalid execution origin"})
}
ExecutionRequestError::InvalidOperationVersion => {
serde_json::json!({"code": "invalid operation version"})
}
ExecutionRequestError::DeadlineElapsed => {
serde_json::json!({"code": "task deadline elapsed"})
}
ExecutionRequestError::InvalidMeteringScope => {
serde_json::json!({"code": "invalid metering scope"})
}
});
}
};
if cancelled.load(Ordering::Acquire) {
return TaskAttemptOutcome::OutcomeUnknown;
}
match self.runtime.execute_task_outcome(request, permit).await {
Ok(success) => TaskAttemptOutcome::Completed(success.output),
Err(failure) => {
// An ambiguous outbound failure is recorded as uncertainty, never as a retryable
// failure: the durable checkpoint already exists, so Story 4.4 may reconcile it.
if failure.outcome_certainty() == crank_core::OutcomeCertainty::OutcomeUnknown {
return TaskAttemptOutcome::OutcomeUnknown;
}
TaskAttemptOutcome::Failed(
serde_json::json!({ "code": format!("{:?}", failure.error_code()) }),
)
}
}
retry_allowed,
upstream_key_digest,
})
}
}