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
@@ -11,12 +11,14 @@ use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use crank_core::{TaskEnvelope, TaskError, TaskFinishRequest, TaskLease, TaskState, TaskStore};
|
||||
use crank_core::{TaskError, TaskLease, TaskStore};
|
||||
use tokio::sync::watch;
|
||||
use tokio::task::JoinSet;
|
||||
use tracing::{Instrument, debug, warn};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::task_attempt::{TaskAttemptContext, TaskAttemptOutcome};
|
||||
|
||||
/// Configuration for [`TaskWorker`]. Durations are capped by the caller to story timing budgets.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct TaskWorkerConfig {
|
||||
@@ -50,29 +52,16 @@ impl Default for TaskWorkerConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of one durable Task attempt produced by the application layer.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum TaskAttemptOutcome {
|
||||
Completed(serde_json::Value),
|
||||
Failed(serde_json::Value),
|
||||
OutcomeUnknown,
|
||||
}
|
||||
|
||||
/// Application-owned seam for pre-dispatch revalidation and execution.
|
||||
///
|
||||
/// The worker owns lease renewal/CAS/fencing and the dispatch checkpoint. The handler only
|
||||
/// receives the leased record and attempt identity; it must not trust `TaskRecord.input` as
|
||||
/// The worker owns lease renewal/CAS/fencing and passes a durable [`TaskAttemptContext`]. The
|
||||
/// application implements [`crate::TaskAttemptAuthority`] and drives the pinned retry budget through
|
||||
/// [`crate::RuntimeExecutor::execute_task_outcome`]; it must not trust `TaskRecord.input` as
|
||||
/// executable payload.
|
||||
#[async_trait]
|
||||
pub trait TaskHandler: Send + Sync {
|
||||
async fn revalidate(&self, lease: &TaskLease) -> Result<(), TaskWorkerError>;
|
||||
async fn execute(
|
||||
&self,
|
||||
lease: &TaskLease,
|
||||
attempt_id: &str,
|
||||
cancelled: Arc<AtomicBool>,
|
||||
permit: TaskDispatchPermit,
|
||||
) -> TaskAttemptOutcome;
|
||||
async fn execute(&self, context: TaskAttemptContext) -> TaskAttemptOutcome;
|
||||
}
|
||||
|
||||
/// Sealed, single-use trusted dispatch permit created by [`TaskWorker`] after a durable lease and
|
||||
@@ -91,6 +80,7 @@ pub struct TaskDispatchPermit {
|
||||
}
|
||||
|
||||
impl TaskDispatchPermit {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn new(
|
||||
task_id: crank_core::TaskId,
|
||||
operation_id: String,
|
||||
@@ -244,10 +234,10 @@ impl TaskWorker {
|
||||
if self.stopping.load(Ordering::Acquire) {
|
||||
break;
|
||||
}
|
||||
if let Some(rx) = shutdown.as_mut() {
|
||||
if *rx.borrow() {
|
||||
break;
|
||||
}
|
||||
if let Some(rx) = shutdown.as_mut()
|
||||
&& *rx.borrow()
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
// Reap finished attempts before claiming more.
|
||||
@@ -344,15 +334,7 @@ async fn process_lease(
|
||||
return;
|
||||
}
|
||||
debug!(task_id = %task_id, error = %error, "task revalidation failed; finishing without dispatch");
|
||||
finish_failed(
|
||||
&store,
|
||||
&owner,
|
||||
task_id,
|
||||
fence,
|
||||
&lease,
|
||||
"revalidation_failed",
|
||||
)
|
||||
.await;
|
||||
finish_failed(&store, &lease, "revalidation_failed").await;
|
||||
return;
|
||||
}
|
||||
if stopping.load(Ordering::Acquire) {
|
||||
@@ -364,49 +346,8 @@ async fn process_lease(
|
||||
|
||||
let attempt_id = format!("attempt-{}", Uuid::now_v7());
|
||||
|
||||
// Durable checkpoint before any network use.
|
||||
if store
|
||||
.checkpoint_dispatch(&owner, task_id, fence, attempt_id.clone())
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
// Lease lost or checkpoint rejected: do not dispatch.
|
||||
cancelled.store(true, Ordering::Release);
|
||||
return;
|
||||
}
|
||||
if stopping.load(Ordering::Acquire) {
|
||||
// The checkpoint is durable, but we know the outbound callback has not started.
|
||||
finish_failed(
|
||||
&store,
|
||||
&owner,
|
||||
task_id,
|
||||
fence,
|
||||
&lease,
|
||||
"shutdown_before_dispatch",
|
||||
)
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
|
||||
// Sealed single-use permit for the trusted runtime dispatch bridge. It is created only after
|
||||
// the current lease and durable checkpoint above.
|
||||
let agent_id = if lease.record.owner_kind == crank_core::TaskOwnerKind::Agent {
|
||||
Some(lease.record.owner_id.clone())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let permit = TaskDispatchPermit::new(
|
||||
lease.record.task_id,
|
||||
lease.record.operation_id.clone(),
|
||||
lease.record.pins.operation_version,
|
||||
lease.record.workspace_id.clone(),
|
||||
agent_id,
|
||||
owner.clone(),
|
||||
fence,
|
||||
attempt_id.clone(),
|
||||
);
|
||||
|
||||
// Background lease renewal while the attempt runs.
|
||||
// Background lease renewal covers the whole bounded retry budget, including the pinned backoff.
|
||||
// A durable cancellation clears the lease, so the next renewal fails and the local work stops.
|
||||
let renewal_store = store.clone();
|
||||
let renewal_owner = owner.clone();
|
||||
let renewal_cancelled = cancelled.clone();
|
||||
@@ -435,139 +376,43 @@ async fn process_lease(
|
||||
}
|
||||
});
|
||||
|
||||
// Each dispatch gets a child span carrying the durable attempt identity, rooted in the parent
|
||||
// trace persisted with the accepted Task (never a mutable queue/cache projection).
|
||||
let span = tracing::info_span!("durable_task_attempt", task_id = %task_id, attempt_id = %attempt_id, fence);
|
||||
// The parent span names the leased Task generation; every individual outbound attempt adds its own
|
||||
// `adapter_attempt` child span with the durable attempt ID committed by its checkpoint.
|
||||
let span = tracing::info_span!("durable_task_attempt", task_id = %task_id, lease_ref = %attempt_id, fence);
|
||||
if let Ok(parent) = crank_core::TraceContext::parse(&lease.record.support.traceparent) {
|
||||
crank_trace::set_parent_from_trace_context(&span, &parent);
|
||||
}
|
||||
let outcome = handler
|
||||
.execute(&lease, &attempt_id, cancelled.clone(), permit)
|
||||
.instrument(span)
|
||||
.await;
|
||||
// Every durable write of this Task (checkpoint, attempt resolution, terminal state) happens inside
|
||||
// the executor's single retry loop under this lease/fence; the worker only renews and stops.
|
||||
let context = TaskAttemptContext::new(
|
||||
store.clone(),
|
||||
lease.clone(),
|
||||
cancelled.clone(),
|
||||
stopping.clone(),
|
||||
);
|
||||
let outcome = handler.execute(context).instrument(span).await;
|
||||
|
||||
cancelled.store(true, Ordering::Release);
|
||||
renewal_handle.abort();
|
||||
|
||||
// Terminal CAS under valid lease. Only one writer wins; stale token is rejected by store.
|
||||
let access = crank_core::TaskAccess {
|
||||
workspace_id: lease.record.workspace_id.clone(),
|
||||
owner_kind: lease.record.owner_kind,
|
||||
owner_id: lease.record.owner_id.clone(),
|
||||
authorization_scope: lease.record.authorization_scope.clone(),
|
||||
};
|
||||
|
||||
match outcome {
|
||||
TaskAttemptOutcome::Completed(value) => {
|
||||
let Ok(result) = TaskEnvelope::try_redacted(&value) else {
|
||||
finish_failed(
|
||||
&store,
|
||||
&owner,
|
||||
task_id,
|
||||
fence,
|
||||
&lease,
|
||||
"result_not_redactable",
|
||||
)
|
||||
.await;
|
||||
return;
|
||||
};
|
||||
let _ = store
|
||||
.finish_leased(
|
||||
TaskFinishRequest {
|
||||
access,
|
||||
task_id,
|
||||
expected_state: leased_expected_state(&lease),
|
||||
expected_version: lease.record.version,
|
||||
target_state: TaskState::Completed,
|
||||
result: Some(result),
|
||||
error: None,
|
||||
},
|
||||
&owner,
|
||||
fence,
|
||||
)
|
||||
.await;
|
||||
TaskAttemptOutcome::Completed => {
|
||||
debug!(task_id = %task_id, "durable task completed");
|
||||
}
|
||||
TaskAttemptOutcome::Failed(value) => {
|
||||
let error = TaskEnvelope::try_redacted(&value).or_else(|_| {
|
||||
TaskEnvelope::try_redacted(&serde_json::json!({
|
||||
"code": "task_error_not_redactable"
|
||||
}))
|
||||
});
|
||||
let Ok(error) = error else {
|
||||
return;
|
||||
};
|
||||
let _ = store
|
||||
.finish_leased(
|
||||
TaskFinishRequest {
|
||||
access,
|
||||
task_id,
|
||||
expected_state: leased_expected_state(&lease),
|
||||
expected_version: lease.record.version,
|
||||
target_state: TaskState::Failed,
|
||||
result: None,
|
||||
error: Some(error),
|
||||
},
|
||||
&owner,
|
||||
fence,
|
||||
)
|
||||
.await;
|
||||
TaskAttemptOutcome::Failed { code } => {
|
||||
debug!(task_id = %task_id, code = %code, "durable task failed");
|
||||
}
|
||||
TaskAttemptOutcome::OutcomeUnknown => {
|
||||
let _ = store
|
||||
.finish_leased(
|
||||
TaskFinishRequest {
|
||||
access,
|
||||
task_id,
|
||||
expected_state: leased_expected_state(&lease),
|
||||
expected_version: lease.record.version,
|
||||
target_state: TaskState::OutcomeUnknown,
|
||||
result: None,
|
||||
error: None,
|
||||
},
|
||||
&owner,
|
||||
fence,
|
||||
)
|
||||
.await;
|
||||
warn!(task_id = %task_id, "durable task outcome is uncertain; no automatic retry");
|
||||
}
|
||||
TaskAttemptOutcome::Stopped => {
|
||||
debug!(task_id = %task_id, "durable task attempt stopped without a new outcome");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn leased_expected_state(lease: &TaskLease) -> TaskState {
|
||||
// Claimed tasks are expected to be in a non-terminal processing state.
|
||||
if lease.record.state == TaskState::Queued {
|
||||
TaskState::Queued
|
||||
} else {
|
||||
TaskState::Working
|
||||
}
|
||||
}
|
||||
|
||||
async fn finish_failed(
|
||||
store: &Arc<dyn TaskStore>,
|
||||
owner: &str,
|
||||
task_id: crank_core::TaskId,
|
||||
fence: u64,
|
||||
lease: &TaskLease,
|
||||
code: &str,
|
||||
) {
|
||||
let access = crank_core::TaskAccess {
|
||||
workspace_id: lease.record.workspace_id.clone(),
|
||||
owner_kind: lease.record.owner_kind,
|
||||
owner_id: lease.record.owner_id.clone(),
|
||||
authorization_scope: lease.record.authorization_scope.clone(),
|
||||
};
|
||||
let _ = store
|
||||
.finish_leased(
|
||||
TaskFinishRequest {
|
||||
access,
|
||||
task_id,
|
||||
expected_state: leased_expected_state(lease),
|
||||
expected_version: lease.record.version,
|
||||
target_state: TaskState::Failed,
|
||||
result: None,
|
||||
error: TaskEnvelope::try_redacted(&serde_json::json!({ "code": code })).ok(),
|
||||
},
|
||||
owner,
|
||||
fence,
|
||||
)
|
||||
.await;
|
||||
async fn finish_failed(store: &Arc<dyn TaskStore>, lease: &TaskLease, code: &str) {
|
||||
// The store owns the fate of a refused pre-dispatch attempt: a Task that already carries a proven
|
||||
// ambiguity still ends `outcome_unknown`, never a plain failure (Story 4.4).
|
||||
let _ = store.refuse_attempt(lease, code).await;
|
||||
}
|
||||
Reference in new issue
Block a user