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
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:
1 parent
8c02380762
commit
a3057de51e
44 files changed
+4547
-815
No files matched your search
@@ -24,9 +24,13 @@ use tokio::sync::{OwnedSemaphorePermit, Semaphore};
|
||||
use tracing::{Instrument, Span, debug, warn};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::task_attempt::{
|
||||
TaskAttemptAuthority, TaskAttemptContext, TaskAttemptOutcome, TaskAttemptPlan,
|
||||
TaskAttemptRefusal,
|
||||
};
|
||||
use crate::task_worker::TaskDispatchPermit;
|
||||
use crate::{
|
||||
AdapterResponse, ExecutionAuthorization, PreparedRequest, RuntimeError,
|
||||
AdapterResponse, ExecutionAuthorization, ExecutionRequestError, PreparedRequest, RuntimeError,
|
||||
RuntimeExecutionRequest, RuntimeLimits, RuntimeOperation, RuntimeRequestContext,
|
||||
auth::apply_resolved_auth,
|
||||
request_preparation::{adapter_prepared_request, validate_selected_body_variant},
|
||||
@@ -36,6 +40,18 @@ use crate::{
|
||||
},
|
||||
};
|
||||
|
||||
/// How many outbound sends one prepared request may perform.
|
||||
///
|
||||
/// `Legacy` keeps the existing synchronous `tools/call` retry behaviour inside the transport loop.
|
||||
/// `Single` performs exactly one send, because a durable Task attempt already has its own committed
|
||||
/// checkpoint and resolution around every send; it carries the pinned attempt ordinal and budget so
|
||||
/// the one `adapter_attempt` span still names the real durable attempt.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum SendMode {
|
||||
Legacy,
|
||||
Single { attempt: u32, max_attempts: u32 },
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RuntimeExecutor {
|
||||
adapters: AdapterRegistry,
|
||||
@@ -181,57 +197,273 @@ impl RuntimeExecutor {
|
||||
&self,
|
||||
request: RuntimeExecutionRequest<'_>,
|
||||
) -> Result<(Value, Value), RuntimeError> {
|
||||
self.execute_request_impl(request, None).await
|
||||
self.execute_request_impl(request, None, SendMode::Legacy)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Drives the bounded, durable retry budget of one leased background Task (Story 4.4).
|
||||
///
|
||||
/// Each outbound send is preceded by its own committed attempt checkpoint and followed by one
|
||||
/// atomic resolution; the pinned budget, the safe-retry decision and the accepted absolute
|
||||
/// deadline are enforced by PostgreSQL, so a restart or a second worker cannot extend them.
|
||||
pub async fn execute_task_outcome(
|
||||
&self,
|
||||
request: RuntimeExecutionRequest<'_>,
|
||||
permit: TaskDispatchPermit,
|
||||
) -> Result<crank_core::ExecutionSuccess, crank_core::ExecutionFailure> {
|
||||
let operation = request.operation().clone();
|
||||
let operation_id = operation.operation_id.clone();
|
||||
let operation_version = operation.operation_version;
|
||||
let origin = request.origin();
|
||||
let correlation = crank_core::CorrelationContext::new(
|
||||
request.request_context().request_id.clone(),
|
||||
request.request_context().trace_context.clone(),
|
||||
context: &TaskAttemptContext,
|
||||
authority: &dyn TaskAttemptAuthority,
|
||||
) -> TaskAttemptOutcome {
|
||||
let store = context.store().clone();
|
||||
let lease = context.lease().clone();
|
||||
let mut record = lease.record.clone();
|
||||
loop {
|
||||
if context.is_cancelled() || context.is_stopping() {
|
||||
return TaskAttemptOutcome::Stopped;
|
||||
}
|
||||
let current_lease = crank_core::TaskLease {
|
||||
record: record.clone(),
|
||||
owner: lease.owner.clone(),
|
||||
fence: lease.fence,
|
||||
lease_until: lease.lease_until,
|
||||
};
|
||||
let plan = match authority.prepare_attempt(¤t_lease).await {
|
||||
Ok(plan) => plan,
|
||||
Err(TaskAttemptRefusal::Stopped) => return TaskAttemptOutcome::Stopped,
|
||||
Err(TaskAttemptRefusal::Failed { code }) => {
|
||||
// A refused attempt never erases a proven ambiguity: if an earlier attempt of this
|
||||
// Task may already have reached the upstream, the store keeps the Task in the
|
||||
// non-terminal `outcome_unknown` instead of downgrading it to a plain failure.
|
||||
return match store.refuse_attempt(¤t_lease, &code).await {
|
||||
Ok(record) if record.state == crank_core::TaskState::OutcomeUnknown => {
|
||||
TaskAttemptOutcome::OutcomeUnknown
|
||||
}
|
||||
_ => TaskAttemptOutcome::Failed { code },
|
||||
};
|
||||
}
|
||||
};
|
||||
let attempt_id = format!("attempt-{}", Uuid::now_v7());
|
||||
let begin = crank_core::BeginAttempt {
|
||||
task_id: record.task_id,
|
||||
owner: lease.owner.clone(),
|
||||
fence: lease.fence,
|
||||
expected_version: record.version,
|
||||
attempt_id: attempt_id.clone(),
|
||||
input_fingerprint: record.input_fingerprint.clone(),
|
||||
upstream_key_digest: plan.upstream_key_digest.clone(),
|
||||
retry_allowed: plan.retry_allowed,
|
||||
};
|
||||
let attempt = match store.checkpoint_dispatch(begin).await {
|
||||
Ok(attempt) => attempt,
|
||||
// Cancellation, lease loss or a concurrent lifecycle change: nothing was dispatched.
|
||||
Err(crank_core::TaskError::StateConflict)
|
||||
| Err(crank_core::TaskError::NotFound)
|
||||
| Err(crank_core::TaskError::FingerprintConflict) => {
|
||||
return TaskAttemptOutcome::Stopped;
|
||||
}
|
||||
// An unproven commit is never retried by guess: no outbound call without a proven
|
||||
// durable checkpoint.
|
||||
Err(error) => {
|
||||
warn!(error = %error, "durable dispatch checkpoint failed; no outbound call");
|
||||
return TaskAttemptOutcome::Stopped;
|
||||
}
|
||||
};
|
||||
if context.is_stopping() {
|
||||
let code = "shutdown_before_dispatch".to_owned();
|
||||
// A stop that lands before the send is a proven failure of *this* attempt only: when
|
||||
// an earlier attempt of the same Task already lost its confirmation, the store keeps
|
||||
// the non-terminal `outcome_unknown` instead of downgrading it to a plain failure.
|
||||
return match store
|
||||
.resolve_attempt(
|
||||
&attempt,
|
||||
crank_core::AttemptOutcome::Failed {
|
||||
error: bounded_attempt_error(
|
||||
&code,
|
||||
crank_core::AttemptPhase::BeforeDispatch,
|
||||
),
|
||||
retryable: false,
|
||||
phase: crank_core::AttemptPhase::BeforeDispatch,
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(crank_core::AttemptResolution::Unknown(_)) => {
|
||||
TaskAttemptOutcome::OutcomeUnknown
|
||||
}
|
||||
_ => TaskAttemptOutcome::Failed { code },
|
||||
};
|
||||
}
|
||||
if context.is_cancelled() {
|
||||
let _ = store
|
||||
.resolve_attempt(
|
||||
&attempt,
|
||||
crank_core::AttemptOutcome::Uncertain {
|
||||
error: bounded_attempt_error(
|
||||
"outcome_unknown",
|
||||
crank_core::AttemptPhase::BeforeDispatch,
|
||||
),
|
||||
repeatable: false,
|
||||
phase: crank_core::AttemptPhase::BeforeDispatch,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
return TaskAttemptOutcome::OutcomeUnknown;
|
||||
}
|
||||
// Each attempt owns exactly one `adapter_attempt` span, created around the single send
|
||||
// inside the transport loop so the accepted trace shape (durable attempt → runtime
|
||||
// execution → adapter attempt) is preserved.
|
||||
let result = self.execute_task_send(&plan, &attempt).await;
|
||||
let (outcome, code) = self.classify_task_attempt(&plan, result);
|
||||
match store.resolve_attempt(&attempt, outcome).await {
|
||||
Ok(crank_core::AttemptResolution::Finished(task)) => {
|
||||
return if task.state == crank_core::TaskState::Completed {
|
||||
TaskAttemptOutcome::Completed
|
||||
} else {
|
||||
TaskAttemptOutcome::Failed {
|
||||
code: code.unwrap_or_else(|| "task_failed".to_owned()),
|
||||
}
|
||||
};
|
||||
}
|
||||
Ok(crank_core::AttemptResolution::Unknown(_)) => {
|
||||
return TaskAttemptOutcome::OutcomeUnknown;
|
||||
}
|
||||
Ok(crank_core::AttemptResolution::RetryAt {
|
||||
task,
|
||||
next_attempt_at_unix_ms,
|
||||
}) => {
|
||||
record = task;
|
||||
let remaining =
|
||||
next_attempt_at_unix_ms.saturating_sub(crank_core::current_unix_ms());
|
||||
let delay = Duration::from_millis(u64::try_from(remaining).unwrap_or(0));
|
||||
if !self.wait_before_attempt(context, delay).await {
|
||||
return TaskAttemptOutcome::Stopped;
|
||||
}
|
||||
}
|
||||
// A stale fence or version lost the resolution CAS: another writer owns the Task now.
|
||||
Err(_) => return TaskAttemptOutcome::Stopped,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One outbound send of one committed durable attempt.
|
||||
async fn execute_task_send(
|
||||
&self,
|
||||
plan: &TaskAttemptPlan,
|
||||
attempt: &crank_core::AttemptLease,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
let permit = TaskDispatchPermit::new(
|
||||
attempt.attempt.task_id,
|
||||
plan.operation.operation_id.as_str().to_owned(),
|
||||
plan.operation.operation_version,
|
||||
plan.workspace_id.as_str().to_owned(),
|
||||
plan.agent_id.as_ref().map(|id| id.as_str().to_owned()),
|
||||
attempt.attempt.owner.clone(),
|
||||
attempt.attempt.fence,
|
||||
attempt.attempt.attempt_id.clone(),
|
||||
);
|
||||
let request = match RuntimeExecutionRequest::try_new(
|
||||
&plan.workspace_id,
|
||||
plan.origin,
|
||||
plan.agent_id.as_ref(),
|
||||
&plan.operation,
|
||||
&plan.input,
|
||||
plan.authorization,
|
||||
plan.resolved_auth.as_ref(),
|
||||
&plan.request_context,
|
||||
plan.deadline,
|
||||
) {
|
||||
Ok(request) => request,
|
||||
Err(ExecutionRequestError::DeadlineElapsed) => {
|
||||
return Err(RuntimeError::ExecutionDeadlineElapsed {
|
||||
may_have_dispatched: false,
|
||||
});
|
||||
}
|
||||
Err(_) => return Err(RuntimeError::InvalidExecutionRequest),
|
||||
};
|
||||
let (output, _preview) = self
|
||||
.execute_request_impl(
|
||||
request,
|
||||
Some(permit),
|
||||
SendMode::Single {
|
||||
attempt: attempt.attempt.ordinal,
|
||||
max_attempts: attempt.task.pins.retry.max_attempts,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
// Validate permit binding before any adapter dispatch.
|
||||
if permit.operation_id() != operation_id.as_str()
|
||||
|| permit.operation_version() != operation_version
|
||||
|| permit.workspace_id() != request.workspace_id().as_str()
|
||||
|| permit.agent_id() != request.agent_id().map(|value| value.as_str())
|
||||
{
|
||||
return Err(crate::normalize_runtime_error_for_operation(
|
||||
&RuntimeError::InvalidExecutionRequest,
|
||||
&correlation,
|
||||
&operation,
|
||||
));
|
||||
}
|
||||
if !permit.consume() {
|
||||
return Err(crate::normalize_runtime_error_for_operation(
|
||||
&RuntimeError::InvalidExecutionRequest,
|
||||
&correlation,
|
||||
&operation,
|
||||
));
|
||||
/// Maps one outbound result of a durable attempt onto its persisted attempt outcome.
|
||||
fn classify_task_attempt(
|
||||
&self,
|
||||
plan: &TaskAttemptPlan,
|
||||
result: Result<Value, RuntimeError>,
|
||||
) -> (crank_core::AttemptOutcome, Option<String>) {
|
||||
match result {
|
||||
Ok(output) => match crank_core::TaskEnvelope::try_redacted(&output) {
|
||||
Ok(envelope) => (crank_core::AttemptOutcome::Completed(envelope), None),
|
||||
Err(_) => {
|
||||
let code = "result_not_redactable".to_owned();
|
||||
(
|
||||
crank_core::AttemptOutcome::Failed {
|
||||
error: bounded_attempt_error(
|
||||
&code,
|
||||
crank_core::AttemptPhase::Dispatched,
|
||||
),
|
||||
retryable: false,
|
||||
phase: crank_core::AttemptPhase::Dispatched,
|
||||
},
|
||||
Some(code),
|
||||
)
|
||||
}
|
||||
},
|
||||
Err(error) => {
|
||||
let phase = if runtime_error_may_have_dispatched(&error) {
|
||||
crank_core::AttemptPhase::Dispatched
|
||||
} else {
|
||||
crank_core::AttemptPhase::BeforeDispatch
|
||||
};
|
||||
let correlation = crank_core::CorrelationContext::new(
|
||||
plan.request_context.request_id.clone(),
|
||||
plan.request_context.trace_context.clone(),
|
||||
);
|
||||
let failure = crate::normalize_runtime_error_for_operation(
|
||||
&error,
|
||||
&correlation,
|
||||
&plan.operation,
|
||||
);
|
||||
let code = format!("{:?}", failure.error_code());
|
||||
let safe_to_repeat = retry_is_allowed(&plan.operation, &error, plan.retry_allowed);
|
||||
let envelope = bounded_attempt_error(&code, phase);
|
||||
let outcome = match failure.outcome_certainty() {
|
||||
crank_core::OutcomeCertainty::OutcomeUnknown => {
|
||||
crank_core::AttemptOutcome::Uncertain {
|
||||
error: envelope,
|
||||
repeatable: safe_to_repeat,
|
||||
phase,
|
||||
}
|
||||
}
|
||||
_ => crank_core::AttemptOutcome::Failed {
|
||||
error: envelope,
|
||||
retryable: safe_to_repeat,
|
||||
phase,
|
||||
},
|
||||
};
|
||||
(outcome, Some(code))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match self.execute_request_impl(request, Some(permit)).await {
|
||||
Ok((output, request_preview)) => Ok(crank_core::ExecutionSuccess {
|
||||
operation_id: operation_id.clone(),
|
||||
operation_version,
|
||||
origin,
|
||||
correlation,
|
||||
request_preview,
|
||||
output,
|
||||
}),
|
||||
Err(error) => Err(crate::normalize_runtime_error_for_operation(
|
||||
&error,
|
||||
&correlation,
|
||||
&operation,
|
||||
)),
|
||||
/// Bounded cooperative wait inside the pinned backoff window. The lease keeps being renewed by
|
||||
/// the worker, so a durable cancellation or lease loss still stops the local work here.
|
||||
async fn wait_before_attempt(&self, context: &TaskAttemptContext, delay: Duration) -> bool {
|
||||
let deadline = Instant::now() + delay;
|
||||
loop {
|
||||
if context.is_cancelled() || context.is_stopping() {
|
||||
return false;
|
||||
}
|
||||
let now = Instant::now();
|
||||
if now >= deadline {
|
||||
return true;
|
||||
}
|
||||
tokio::time::sleep((deadline - now).min(Duration::from_millis(50))).await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -239,6 +471,7 @@ impl RuntimeExecutor {
|
||||
&self,
|
||||
request: RuntimeExecutionRequest<'_>,
|
||||
permit: Option<TaskDispatchPermit>,
|
||||
send_mode: SendMode,
|
||||
) -> Result<(Value, Value), RuntimeError> {
|
||||
let operation = request.operation();
|
||||
// Derive trusted dispatch from a present permit; a missing permit always uses ordinary admission.
|
||||
@@ -320,6 +553,7 @@ impl RuntimeExecutor {
|
||||
Some(request_context),
|
||||
Arc::clone(&dispatch_started),
|
||||
durable_attempt_id.as_deref(),
|
||||
send_mode,
|
||||
)
|
||||
.await;
|
||||
if let Some(lease) = lease.as_mut() {
|
||||
@@ -415,6 +649,7 @@ impl RuntimeExecutor {
|
||||
Ok(prepared)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn execute_prepared(
|
||||
&self,
|
||||
operation: &RuntimeOperation,
|
||||
@@ -423,6 +658,7 @@ impl RuntimeExecutor {
|
||||
request_context: Option<&RuntimeRequestContext>,
|
||||
dispatch_started: Arc<AtomicBool>,
|
||||
durable_attempt_id: Option<&str>,
|
||||
send_mode: SendMode,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
let mut prepared_request = prepared_request;
|
||||
let idempotency_applicable = crate::idempotency::policy(operation).is_some();
|
||||
@@ -472,7 +708,11 @@ impl RuntimeExecutor {
|
||||
approval_result?;
|
||||
}
|
||||
|
||||
let idempotency = if idempotency_applicable {
|
||||
// The synchronous coordination guard is the replay authority of one `tools/call`. A durable
|
||||
// Task attempt already has a PostgreSQL attempt authority around every send, so the guard is
|
||||
// skipped there: an ambiguous first response must not block the bounded durable retry. The
|
||||
// stable idempotency key is still delivered to the upstream by `prepare_idempotency` above.
|
||||
let idempotency = if idempotency_applicable && matches!(send_mode, SendMode::Legacy) {
|
||||
let idempotency_span = Stage::RuntimeIdempotency.span();
|
||||
let result = crate::idempotency::begin(
|
||||
self.coordination_store.as_deref(),
|
||||
@@ -540,6 +780,7 @@ impl RuntimeExecutor {
|
||||
idempotency_key.as_deref(),
|
||||
),
|
||||
durable_attempt_id,
|
||||
send_mode,
|
||||
)
|
||||
.await;
|
||||
if let Ok(response) = &adapter_response {
|
||||
@@ -673,6 +914,7 @@ impl RuntimeExecutor {
|
||||
.map_err(|error| map_protocol_adapter_error(operation, error))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn execute_adapter_with_retry(
|
||||
&self,
|
||||
operation: &RuntimeOperation,
|
||||
@@ -681,20 +923,32 @@ impl RuntimeExecutor {
|
||||
dispatch_started: Arc<AtomicBool>,
|
||||
verified_idempotency: bool,
|
||||
durable_attempt_id: Option<&str>,
|
||||
send_mode: SendMode,
|
||||
) -> Result<AdapterResponse, RuntimeError> {
|
||||
let max_attempts = retry_attempts(operation);
|
||||
let mut attempt = 1;
|
||||
// `max_attempts` bounds the transport loop; `reported_max_attempts` is the pinned Task budget
|
||||
// the attempt span names. A durable attempt performs exactly one send, so its transport loop
|
||||
// always has a single iteration even when the Task may retry later.
|
||||
let (max_attempts, first_attempt, reported_max_attempts) = match send_mode {
|
||||
SendMode::Single {
|
||||
attempt,
|
||||
max_attempts,
|
||||
} => (1, attempt, max_attempts),
|
||||
SendMode::Legacy => {
|
||||
let attempts = retry_attempts(operation);
|
||||
(attempts, 1, attempts)
|
||||
}
|
||||
};
|
||||
let mut attempt = first_attempt;
|
||||
loop {
|
||||
// Task dispatches reuse the durable Attempt ID committed by the dispatch checkpoint; the
|
||||
// retry index discriminates the attempts inside it. Only paths without a durable attempt
|
||||
// (synchronous tools/call) mint a synthetic per-attempt id.
|
||||
// Task dispatches reuse the durable Attempt ID committed by the dispatch checkpoint. Only
|
||||
// paths without a durable attempt (synchronous tools/call) mint a synthetic identity.
|
||||
let attempt_id = durable_attempt_id
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(|| format!("attempt-{}", Uuid::now_v7()));
|
||||
let attempt_span = tracing::info_span!(
|
||||
"adapter_attempt",
|
||||
attempt,
|
||||
max_attempts,
|
||||
max_attempts = reported_max_attempts,
|
||||
attempt_id = %attempt_id
|
||||
);
|
||||
let result = self
|
||||
@@ -846,6 +1100,22 @@ fn sanitized_request_preview(prepared: &PreparedRequest) -> Value {
|
||||
})
|
||||
}
|
||||
|
||||
/// Bounded persisted error envelope of one durable attempt: a closed code and the attempt phase.
|
||||
/// It never carries an upstream body, status text, URL or credential.
|
||||
fn bounded_attempt_error(code: &str, phase: crank_core::AttemptPhase) -> crank_core::TaskEnvelope {
|
||||
crank_core::TaskEnvelope::try_redacted(&json!({
|
||||
"code": code,
|
||||
"phase": phase.as_str(),
|
||||
}))
|
||||
.unwrap_or_else(|_| {
|
||||
crank_core::TaskEnvelope::try_redacted(&json!({
|
||||
"code": "task_error_not_recordable",
|
||||
"phase": phase.as_str(),
|
||||
}))
|
||||
.expect("bounded attempt error envelope is always valid")
|
||||
})
|
||||
}
|
||||
|
||||
fn runtime_error_may_have_dispatched(error: &RuntimeError) -> bool {
|
||||
matches!(
|
||||
error,
|
||||
|
||||
Reference in new issue
Block a user