Files
crank/crates/crank-runtime/src/task_attempt.rs
T
bsodfather 90e5357a08
CI / UI Checks (pull_request) Successful in 8s
CI / Rust Checks (pull_request) Successful in 21m42s
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
feat(epic4): продолжение ожидающей Task после ввода (Story 4.5)
Durable worker приостанавливает Task как input_required до dispatch, если
закреплённая схема требует отсутствующее поле; authorized schema-validated
update атомарно и с аудитом возобновляет тот же Task ровно один раз.
Replay/conflict/TTL безопасны, ожидание удерживает admission permit.
Additive schema v30: task_input_requests, fingerprint/version, TTL-индекс.
2026-10-30 16:24:12 +00:00

141 lines
5.5 KiB
Rust

//! Durable per-outbound attempt execution of one background Task (Story 4.4).
//!
//! The authoritative state of a Task stays in PostgreSQL. This module only carries the owned
//! execution plan of one attempt, the durable control (store + lease + cooperative stop) and the
//! bounded seam the application layer implements to revalidate authority before each attempt.
//! The single retry loop lives in [`crate::RuntimeExecutor::execute_task_outcome`]; there is no second
//! loop in the worker and no retry inside the transport adapter.
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::time::Instant;
use async_trait::async_trait;
use crank_core::{AgentId, ExecutionOrigin, TaskLease, TaskStore, WorkspaceId};
use crate::{ExecutionAuthorization, ResolvedAuth, RuntimeOperation, RuntimeRequestContext};
/// Owned execution plan of one durable attempt.
///
/// It is rebuilt by the application through [`TaskAttemptAuthority::prepare_attempt`] before every
/// attempt, so a republished catalog, a revoked key or an elapsed deadline is revalidated between two
/// attempts instead of being trusted from the first one.
pub struct TaskAttemptPlan {
pub workspace_id: WorkspaceId,
pub origin: ExecutionOrigin,
pub agent_id: Option<AgentId>,
pub operation: RuntimeOperation,
pub input: serde_json::Value,
pub authorization: ExecutionAuthorization,
pub resolved_auth: Option<ResolvedAuth>,
pub request_context: RuntimeRequestContext,
/// Absolute deadline pinned at acceptance; never re-derived from a later publication.
pub deadline: Instant,
/// Safe-to-retry decision of this attempt: a read, or a write whose upstream idempotency is
/// backed by server-owned evidence. A client-supplied key or header never makes this true.
pub retry_allowed: bool,
/// Digest of the stable upstream idempotency key (never the raw key or a header value).
pub upstream_key_digest: Option<String>,
}
/// Application-owned seam: revalidate authority and prepare exactly one durable attempt.
#[async_trait]
pub trait TaskAttemptAuthority: Send + Sync {
async fn prepare_attempt(
&self,
lease: &TaskLease,
) -> Result<PrepareAttempt, TaskAttemptRefusal>;
}
/// Typed preparation of one attempt: either it is ready to be checkpointed and dispatched, or the
/// pinned operation still lacks a required input and the Task must be suspended before any side
/// effect. The two are explicit so a real authority failure is never turned into a user question.
pub enum PrepareAttempt {
Ready(Box<TaskAttemptPlan>),
InputRequired(crank_core::TaskInputRequest),
}
/// Path of a required item the pinned schema still misses before dispatch.
///
/// This is the runtime-owned decision the application calls before checkpointing an attempt: only a
/// typed missing required field becomes a user question, every other schema violation keeps the
/// existing pre-dispatch attempt validation. Exposed as a plain value so the application layer never
/// maps execution validation itself (execution boundary).
pub fn missing_required_input(
schema: &crank_schema::Schema,
input: &serde_json::Value,
) -> Option<String> {
match schema.validate_shape(input) {
Err(crank_schema::SchemaError::MissingField { path }) => Some(path),
_ => None,
}
}
/// Typed refusal of one attempt preparation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TaskAttemptRefusal {
/// Proven refusal before any dispatch of this attempt; the bounded code is persisted.
Failed { code: String },
/// Durable control changed (cancellation, lease loss, shutdown): write nothing new from here.
Stopped,
}
/// Durable control of one leased Task: the store, the leased record and cooperative stop signals.
#[derive(Clone)]
pub struct TaskAttemptContext {
pub(crate) store: Arc<dyn TaskStore>,
pub(crate) lease: TaskLease,
pub(crate) cancelled: Arc<AtomicBool>,
pub(crate) stopping: Arc<AtomicBool>,
}
impl TaskAttemptContext {
pub(crate) fn new(
store: Arc<dyn TaskStore>,
lease: TaskLease,
cancelled: Arc<AtomicBool>,
stopping: Arc<AtomicBool>,
) -> Self {
Self {
store,
lease,
cancelled,
stopping,
}
}
pub fn store(&self) -> &Arc<dyn TaskStore> {
&self.store
}
pub fn lease(&self) -> &TaskLease {
&self.lease
}
/// Cooperative stop: the lease renewal or an observed durable cancellation set this flag.
pub fn is_cancelled(&self) -> bool {
self.cancelled.load(std::sync::atomic::Ordering::Acquire)
}
/// Process shutdown was requested: no new outbound send may start after the current checkpoint.
pub fn is_stopping(&self) -> bool {
self.stopping.load(std::sync::atomic::Ordering::Acquire)
}
}
/// Result of driving the whole pinned retry budget of one leased Task.
#[derive(Clone, Debug, PartialEq)]
pub enum TaskAttemptOutcome {
/// The Task committed `completed` (exactly one terminal write).
Completed,
/// The Task committed `failed` without dispatch or with a proven failure.
Failed { code: String },
/// The Task is non-terminal `outcome_unknown`; it is never retried or cancelled generically.
OutcomeUnknown,
/// The Task was suspended as `input_required` before its first dispatch: no side effect happened
/// and the worker future must stop; the answer is applied through the application entry.
WaitingForInput,
/// Nothing new was written by this worker: cancellation, lease loss or an unavailable store.
Stopped,
}