feat(epic4): исполнять durable Task через PG lease/fence и восстанавливать после сбоев (Story 4.3)
CI / UI Checks (pull_request) Successful in 15s
CI / Rust Checks (pull_request) Failing after 4m58s
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) Failing after 1s
CI / Deploy (pull_request) Skipped

mcp-server запускает сохранённые фоновые задачи: захват по PostgreSQL lease с
fence-токеном, зашифрованный input и повторная проверка доступа до сетевого
вызова, checkpoint с AttemptID до dispatch и восстановление только по PG.
Устаревший worker не может зафиксировать результат.

Добавлены миграции v26–v28 (V25 не меняется), guard их отсутствия в старой
схеме, метрики/трассы попыток (attempt_trace) и остановка до отправки запроса:
стоп в окне после checkpoint и до permit завершает задачу как
failed(shutdown_before_dispatch) без сетевых вызовов, соседние queued-задачи
остаются доступными. Retry-попытки получают отдельные дочерние spans с durable
current_attempt_id. Shared admission/fairness из Story 4.1 сохранены.

Проверки: durable_tasks 13/13, stages 11/11 (retry 5), runtime lib 47,
bin shutdown 1, registry tasks 16, admission 11, migrations 58 (независимая QA
и исходный runtime-прогон), точный exact-head CI остаётся обязательным.
This commit is contained in:
bsodfather committed 2026-10-29 22:26:52 +00:00
1 parent 6df6ffac4e
commit f9f8c625d1
52 files changed
+5142 -232

No files matched your search

+99 -9
View File
@@ -22,7 +22,9 @@ use serde_json::{Map, Value, json};
use time::OffsetDateTime;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
use tracing::{Instrument, Span, debug, warn};
use uuid::Uuid;
use crate::task_worker::TaskDispatchPermit;
use crate::{
AdapterResponse, ExecutionAuthorization, PreparedRequest, RuntimeError,
RuntimeExecutionRequest, RuntimeLimits, RuntimeOperation, RuntimeRequestContext,
@@ -178,8 +180,72 @@ impl RuntimeExecutor {
pub(crate) async fn execute_request(
&self,
request: RuntimeExecutionRequest<'_>,
) -> Result<(Value, Value), RuntimeError> {
self.execute_request_impl(request, None).await
}
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(),
);
// 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,
));
}
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,
)),
}
}
pub(crate) async fn execute_request_impl(
&self,
request: RuntimeExecutionRequest<'_>,
permit: Option<TaskDispatchPermit>,
) -> Result<(Value, Value), RuntimeError> {
let operation = request.operation();
// Derive trusted dispatch from a present permit; a missing permit always uses ordinary admission.
let trusted_task_dispatch = permit.is_some();
// The durable Attempt ID written by the dispatch checkpoint travels with the permit, so the
// trace names the real persisted attempt instead of inventing one (Story 4.3 AC).
let durable_attempt_id = permit.as_ref().map(|permit| permit.attempt_id().to_owned());
let input = request.input();
let request_context = request.request_context();
debug_assert_eq!(request.authorization(), ExecutionAuthorization::Authorized);
@@ -205,7 +271,9 @@ impl RuntimeExecutor {
let dispatch_started = Arc::new(AtomicBool::new(false));
// True until the admission gate answered. A deadline that fires while the request is still
// waiting for a permit is an admission refusal with zero dispatch, never an upstream timeout.
let admission_pending = Arc::new(AtomicBool::new(self.admission.is_some()));
let admission_pending = Arc::new(AtomicBool::new(
!trusted_task_dispatch && self.admission.is_some(),
));
let invocation_metrics = ToolInvocationMetrics::start_with_exemplar(
metric_invocation_source(Some(request_context)),
request_context
@@ -222,14 +290,19 @@ impl RuntimeExecutor {
// One admission gate for every executable path (Story 4.1): the published policy decides
// the effective mode, the absolute deadline includes queue waiting and the scoped permit
// is held for the whole local execution future, including retries.
let mut lease = crate::admission::acquire(
self.admission.as_ref(),
self.coordination_store.as_deref(),
&request,
execution_deadline,
)
.await?;
admission_pending.store(false, Ordering::Release);
let mut lease = if trusted_task_dispatch {
None
} else {
let result = crate::admission::acquire(
self.admission.as_ref(),
self.coordination_store.as_deref(),
&request,
execution_deadline,
)
.await?;
admission_pending.store(false, Ordering::Release);
result
};
let _permit = self.acquire_unary_permit(operation)?;
let _inflight = InFlightGuard::runtime();
let mapping_span = Stage::RuntimeArgumentsMap.span();
@@ -246,6 +319,7 @@ impl RuntimeExecutor {
prepared_request,
Some(request_context),
Arc::clone(&dispatch_started),
durable_attempt_id.as_deref(),
)
.await;
if let Some(lease) = lease.as_mut() {
@@ -348,6 +422,7 @@ impl RuntimeExecutor {
prepared_request: PreparedRequest,
request_context: Option<&RuntimeRequestContext>,
dispatch_started: Arc<AtomicBool>,
durable_attempt_id: Option<&str>,
) -> Result<Value, RuntimeError> {
let mut prepared_request = prepared_request;
let idempotency_applicable = crate::idempotency::policy(operation).is_some();
@@ -464,6 +539,7 @@ impl RuntimeExecutor {
operation,
idempotency_key.as_deref(),
),
durable_attempt_id,
)
.await;
if let Ok(response) = &adapter_response {
@@ -604,10 +680,23 @@ impl RuntimeExecutor {
request_context: Option<&RuntimeRequestContext>,
dispatch_started: Arc<AtomicBool>,
verified_idempotency: bool,
durable_attempt_id: Option<&str>,
) -> Result<AdapterResponse, RuntimeError> {
let max_attempts = retry_attempts(operation);
let mut attempt = 1;
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.
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,
attempt_id = %attempt_id
);
let result = self
.execute_adapter(
operation,
@@ -615,6 +704,7 @@ impl RuntimeExecutor {
request_context,
Arc::clone(&dispatch_started),
)
.instrument(attempt_span)
.await;
match result {
Ok(response) => return Ok(response),
+5
View File
@@ -15,6 +15,7 @@ mod rate_limit;
mod request_context;
mod request_preparation;
mod response_cache;
mod task_worker;
mod tasks;
pub fn validate_resource_template_parameter(
schema: &crank_schema::Schema,
@@ -115,4 +116,8 @@ pub use rate_limit::{
};
pub use request_context::{MeteringContext, ResponseCacheScope, RuntimeRequestContext};
pub use secret_crypto::SecretCrypto;
pub use task_worker::{
TaskAttemptOutcome, TaskDispatchPermit, TaskHandler, TaskWorker, TaskWorkerConfig,
TaskWorkerError,
};
pub use tasks::{TaskAcceptDraft, TaskOutcome, TaskService};
+573
View File
@@ -0,0 +1,573 @@
//! Fenced durable Task worker loop for Story 4.3.
//!
//! The worker is intentionally scheduler-ish: PostgreSQL is authoritative, polling is bounded,
//! Valkey may only wake it up (never represented here as correctness), and every lease-protected
//! write goes through CAS using owner + fencing token. The actual executable input and revalidation
//! policy arrive via [`TaskHandler`] implemented by the application layer; `TaskRecord.input` is a
//! redacted projection and is never dispatched.
use std::sync::Arc;
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 tokio::sync::watch;
use tokio::task::JoinSet;
use tracing::{Instrument, debug, warn};
use uuid::Uuid;
/// Configuration for [`TaskWorker`]. Durations are capped by the caller to story timing budgets.
#[derive(Clone, Debug)]
pub struct TaskWorkerConfig {
/// Stable random-ish owner identity for this process instance. Required lease owner.
pub owner: String,
/// Maximum number of Tasks claimed in one bounded PG scan.
pub batch_limit: u32,
/// Lease length in milliseconds. Recovery stays within 60s when <= 30s is used.
pub lease_ms: i64,
/// Authoritative PG polling interval when no wake-up hint is available.
pub poll_interval: Duration,
/// Renewal cadence while processing a lease.
pub renewal_interval: Duration,
/// Concurrent in-flight Tasks for this worker.
pub max_inflight: usize,
/// Maximum time to wait for active work during graceful shutdown.
pub shutdown_timeout: Duration,
}
impl Default for TaskWorkerConfig {
fn default() -> Self {
Self {
owner: format!("task-worker-{}", Uuid::now_v7()),
batch_limit: 8,
lease_ms: 30_000,
poll_interval: Duration::from_millis(250),
renewal_interval: Duration::from_millis(5_000),
max_inflight: 4,
shutdown_timeout: Duration::from_secs(30),
}
}
}
/// 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
/// 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;
}
/// Sealed, single-use trusted dispatch permit created by [`TaskWorker`] after a durable lease and
/// successful `checkpoint_dispatch`. It is neither `Clone` nor constructible outside this crate, and
/// it binds one durable Task attempt to its execution request.
pub struct TaskDispatchPermit {
task_id: crank_core::TaskId,
operation_id: String,
operation_version: u32,
workspace_id: String,
agent_id: Option<String>,
owner: String,
fence: u64,
attempt_id: String,
consumed: std::sync::atomic::AtomicBool,
}
impl TaskDispatchPermit {
pub(crate) fn new(
task_id: crank_core::TaskId,
operation_id: String,
operation_version: u32,
workspace_id: String,
agent_id: Option<String>,
owner: String,
fence: u64,
attempt_id: String,
) -> Self {
Self {
task_id,
operation_id,
operation_version,
workspace_id,
agent_id,
owner,
fence,
attempt_id,
consumed: std::sync::atomic::AtomicBool::new(false),
}
}
pub fn task_id(&self) -> crank_core::TaskId {
self.task_id
}
pub fn operation_id(&self) -> &str {
&self.operation_id
}
pub fn operation_version(&self) -> u32 {
self.operation_version
}
pub fn workspace_id(&self) -> &str {
&self.workspace_id
}
pub fn agent_id(&self) -> Option<&str> {
self.agent_id.as_deref()
}
pub fn owner(&self) -> &str {
&self.owner
}
pub fn fence(&self) -> u64 {
self.fence
}
pub fn attempt_id(&self) -> &str {
&self.attempt_id
}
pub fn is_consumed(&self) -> bool {
self.consumed.load(std::sync::atomic::Ordering::Acquire)
}
pub fn consume(&self) -> bool {
!self
.consumed
.swap(true, std::sync::atomic::Ordering::AcqRel)
}
}
#[derive(thiserror::Error, Debug)]
pub enum TaskWorkerError {
#[error("task store error: {0}")]
Store(#[from] TaskError),
#[error("invalid worker configuration: {0}")]
Config(String),
#[error("task terminal transition CAS failed")]
CasRejected,
}
pub struct TaskWorker {
store: Arc<dyn TaskStore>,
handler: Arc<dyn TaskHandler>,
config: TaskWorkerConfig,
stopping: Arc<AtomicBool>,
}
impl TaskWorker {
pub fn new(
store: Arc<dyn TaskStore>,
handler: Arc<dyn TaskHandler>,
config: TaskWorkerConfig,
) -> Result<Self, TaskWorkerError> {
if config.owner.is_empty() {
return Err(TaskWorkerError::Config(
"owner must not be empty".to_owned(),
));
}
if config.batch_limit == 0 || config.batch_limit > 64 || config.lease_ms <= 0 {
return Err(TaskWorkerError::Config(
"batch_limit must be 1..=64 and lease_ms must be positive".to_owned(),
));
}
if config.lease_ms > 30_000
|| config.poll_interval.is_zero()
|| config.poll_interval > Duration::from_secs(30)
|| config.renewal_interval.is_zero()
|| config.renewal_interval >= Duration::from_millis(config.lease_ms as u64)
|| config.max_inflight == 0
|| config.shutdown_timeout.is_zero()
|| config.shutdown_timeout > Duration::from_secs(30)
{
return Err(TaskWorkerError::Config(
"lease, polling, renewal, concurrency, or shutdown exceeds story timing bounds"
.to_owned(),
));
}
Ok(Self {
store,
handler,
config,
stopping: Arc::new(AtomicBool::new(false)),
})
}
/// Signal graceful shutdown. New claims stop; active handlers are cooperatively cancelled.
pub fn stop(&self) {
self.stopping.store(true, Ordering::Release);
}
/// Returns a handle whose drop does not stop the worker; call `stop()` on the worker.
pub fn stop_flag(&self) -> Arc<AtomicBool> {
self.stopping.clone()
}
/// Run until `stop()` is called. Uses PostgreSQL as the authoritative bounded scan.
pub async fn run(&self) -> Result<(), TaskWorkerError> {
self.run_inner(None).await
}
/// Run until either `stop()` or the provided shutdown receiver becomes true.
pub async fn run_until_shutdown(
&self,
mut shutdown: watch::Receiver<bool>,
) -> Result<(), TaskWorkerError> {
self.run_inner(Some(&mut shutdown)).await
}
async fn run_inner(
&self,
mut shutdown: Option<&mut watch::Receiver<bool>>,
) -> Result<(), TaskWorkerError> {
let mut active: JoinSet<()> = JoinSet::new();
loop {
if self.stopping.load(Ordering::Acquire) {
break;
}
if let Some(rx) = shutdown.as_mut() {
if *rx.borrow() {
break;
}
}
// Reap finished attempts before claiming more.
while active.try_join_next().is_some() {}
let available = self.config.max_inflight.saturating_sub(active.len());
if available > 0 {
let batch_limit = self
.config
.batch_limit
.min(u32::try_from(available).unwrap_or(u32::MAX));
match self
.store
.claim_batch(&self.config.owner, batch_limit, self.config.lease_ms)
.await
{
Ok(leases) => {
for lease in leases {
let store = self.store.clone();
let handler = self.handler.clone();
let owner = self.config.owner.clone();
let lease_ms = self.config.lease_ms;
let renewal_interval = self.config.renewal_interval;
let stopping = self.stopping.clone();
active.spawn(async move {
process_lease(
store,
handler,
owner,
lease,
lease_ms,
renewal_interval,
stopping,
)
.await;
});
}
}
Err(error) => {
warn!(error = %error, "bounded task claim failed; retrying on next scan");
}
}
}
tokio::select! {
_ = tokio::time::sleep(self.config.poll_interval) => {}
_ = async {
if let Some(rx) = shutdown.as_mut() { let _ = rx.changed().await; } else { std::future::pending::<()>().await }
} => {}
}
}
// Graceful shutdown: stop claims (already) and let active work finish/checkpoint, bounded.
// The same stop flag reaches cooperative cancellation and lease-renewal loops.
self.stopping.store(true, Ordering::Release);
let deadline = Instant::now() + self.config.shutdown_timeout;
while !active.is_empty() {
if Instant::now() >= deadline {
warn!("graceful shutdown timeout reached; aborting remaining task attempts");
active.abort_all();
break;
}
tokio::select! {
_ = active.join_next() => {}
_ = tokio::time::sleep(Duration::from_millis(50)) => {}
}
}
Ok(())
}
}
async fn process_lease(
store: Arc<dyn TaskStore>,
handler: Arc<dyn TaskHandler>,
owner: String,
lease: TaskLease,
lease_ms: i64,
renewal_interval: Duration,
stopping: Arc<AtomicBool>,
) {
let task_id = lease.record.task_id;
let fence = lease.fence;
let cancelled = Arc::new(AtomicBool::new(false));
// Pre-dispatch revalidation under the fresh lease.
if let Err(error) = handler.revalidate(&lease).await {
// A transient authority-store outage is not evidence that the work is invalid: leave the
// lease to expire so the bounded recovery scan can retry it without dispatching now.
if matches!(
&error,
TaskWorkerError::Store(TaskError::Unavailable { .. })
) {
debug!(task_id = %task_id, error = %error, "transient revalidation failure; leaving work for recovery");
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;
return;
}
if stopping.load(Ordering::Acquire) {
// Graceful shutdown before the durable dispatch checkpoint: no outbound call can have
// happened, so the Task is left leased. The bounded recovery scan requeues it after the
// lease expires instead of turning a never-started attempt into a user-visible failure.
return;
}
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.
let renewal_store = store.clone();
let renewal_owner = owner.clone();
let renewal_cancelled = cancelled.clone();
let renewal_stopping = stopping.clone();
let renewal_task_id = task_id;
let renewal_handle = tokio::spawn(async move {
let mut interval = tokio::time::interval(renewal_interval);
interval.tick().await;
loop {
interval.tick().await;
if renewal_cancelled.load(Ordering::Acquire) {
break;
}
if renewal_stopping.load(Ordering::Acquire) {
renewal_cancelled.store(true, Ordering::Release);
break;
}
if renewal_store
.renew_lease(&renewal_owner, renewal_task_id, fence, lease_ms)
.await
.is_err()
{
renewal_cancelled.store(true, Ordering::Release);
break;
}
}
});
// 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);
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;
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::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::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;
}
}
}
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;
}
+160 -6
View File
@@ -13,11 +13,13 @@
use std::sync::Arc;
use std::time::Instant;
use crank_core::PlatformApiKeyId;
use crank_core::{
CorrelationContext, TASK_DEFAULT_RETENTION_MS, TASK_MAX_RETENTION_MS,
TASK_SCOPED_KEY_MAX_BYTES, TaskAcceptRequest, TaskAcceptance, TaskAccess, TaskEnvelope,
TaskError, TaskId, TaskOwnerKind, TaskPins, TaskRecord, TaskStore, TaskSupportIds,
ToolExecutionMode, current_unix_ms, validate_task_envelope,
CorrelationContext, TASK_DEFAULT_RETENTION_MS, TASK_EXECUTABLE_INPUT_CIPHERTEXT_MAX_BYTES,
TASK_EXECUTABLE_INPUT_MAX_BYTES, TASK_MAX_RETENTION_MS, TASK_SCOPED_KEY_MAX_BYTES,
TaskAcceptRequest, TaskAcceptance, TaskAccess, TaskEnvelope, TaskError, TaskId, TaskLease,
TaskOwnerKind, TaskPins, TaskRecord, TaskStore, TaskSupportIds, ToolExecutionMode,
contains_sensitive_task_keys, current_unix_ms, validate_task_envelope,
};
use sha2::{Digest, Sha256};
@@ -29,6 +31,9 @@ pub struct TaskAcceptDraft {
pub owner_id: String,
/// Server-derived authorization scope identity of the verified principal.
pub authorization_scope: String,
/// Typed immutable Platform API key identity of the verified machine credential. It is sealed
/// into the executable-input binding and revalidated authoritatively by the worker.
pub platform_api_key_id: Option<PlatformApiKeyId>,
pub operation_id: String,
pub operation_version: u32,
pub policy_mode: ToolExecutionMode,
@@ -68,11 +73,22 @@ impl TaskOutcome {
#[derive(Clone)]
pub struct TaskService {
store: Arc<dyn TaskStore>,
crypto: Option<Arc<crate::SecretCrypto>>,
}
impl TaskService {
pub fn new(store: Arc<dyn TaskStore>) -> Self {
Self { store }
Self {
store,
crypto: None,
}
}
pub fn with_secret_crypto(store: Arc<dyn TaskStore>, crypto: Arc<crate::SecretCrypto>) -> Self {
Self {
store,
crypto: Some(crypto),
}
}
/// Readiness of the mandatory durable Task state.
@@ -83,18 +99,61 @@ impl TaskService {
/// Durable acceptance: the returned identity exists only after the store committed it.
pub async fn accept(&self, draft: TaskAcceptDraft) -> Result<TaskAcceptance, TaskError> {
validate_task_envelope(&draft.input)?;
if contains_sensitive_task_keys(&draft.input) {
return Err(TaskError::invalid(
"task executable input contains sensitive fields",
));
}
let (scoped_key, input_fingerprint) = (
scoped_key_digest(&draft)?,
canonical_input_fingerprint(&draft.input)?,
);
let execution_deadline_unix_ms = deadline_unix_ms(draft.deadline);
let retention_ms = draft.retention_ms.clamp(0, TASK_MAX_RETENTION_MS);
let task_id = TaskId::generate();
let crypto = self.crypto.as_ref().ok_or_else(|| {
TaskError::invalid("secret crypto is required for durable Task acceptance")
})?;
let binding = serde_json::json!({
"task_id": task_id.to_string(),
"workspace_id": draft.workspace_id,
"owner_kind": draft.owner_kind.as_str(),
"owner_id": draft.owner_id,
"authorization_scope": draft.authorization_scope,
"platform_api_key_id": draft
.platform_api_key_id
.as_ref()
.map(PlatformApiKeyId::as_str),
"operation_id": draft.operation_id,
"operation_version": draft.operation_version,
"policy_mode": draft.policy_mode,
"input_fingerprint": input_fingerprint,
"input": draft.input,
});
let ciphertext = crypto
.encrypt(&binding)
.map_err(|error| TaskError::invalid(error.to_string()))?;
if ciphertext.len() > TASK_EXECUTABLE_INPUT_CIPHERTEXT_MAX_BYTES {
return Err(TaskError::invalid(
"encrypted task input exceeds its byte budget",
));
}
let (
executable_input_ciphertext,
executable_input_key_version,
executable_input_master_key_epoch,
) = (
Some(ciphertext),
Some(crypto.key_version().to_owned()),
Some(crypto.master_key_epoch()),
);
let request = TaskAcceptRequest {
task_id: TaskId::generate(),
task_id,
workspace_id: draft.workspace_id,
owner_kind: draft.owner_kind,
owner_id: draft.owner_id,
authorization_scope: draft.authorization_scope,
platform_api_key_id: draft.platform_api_key_id,
operation_id: draft.operation_id,
pins: TaskPins {
operation_version: draft.operation_version,
@@ -110,6 +169,9 @@ impl TaskService {
draft.correlation.request_id().clone(),
draft.correlation.trace_context(),
),
executable_input_ciphertext,
executable_input_key_version,
executable_input_master_key_epoch,
};
self.store.accept(request).await
}
@@ -134,6 +196,97 @@ impl TaskService {
))
}
/// Decrypts and validates the executable input bound to a valid current lease.
pub async fn executable_input(
&self,
lease: &TaskLease,
) -> Result<serde_json::Value, TaskError> {
let crypto = self.crypto.as_ref().ok_or_else(|| {
TaskError::invalid("secret crypto is required for durable Task execution")
})?;
let (ciphertext, key_version, epoch) = self
.store
.read_executable_input(&lease.owner, lease.record.task_id, lease.fence)
.await?;
if ciphertext.len() > TASK_EXECUTABLE_INPUT_CIPHERTEXT_MAX_BYTES {
return Err(TaskError::invalid(
"task executable input ciphertext is invalid",
));
}
let binding = crypto
.decrypt_for_epoch(&key_version, epoch, &ciphertext)
.map_err(|error| TaskError::invalid(error.to_string()))?;
let object = binding
.as_object()
.ok_or_else(|| TaskError::invalid("task executable input binding is invalid"))?;
let check_string = |field: &str, expected: &str| -> Result<(), TaskError> {
match object.get(field).and_then(|value| value.as_str()) {
Some(actual) if actual == expected => Ok(()),
_ => Err(TaskError::invalid("task executable input binding mismatch")),
}
};
check_string("task_id", &lease.record.task_id.to_string())?;
check_string("workspace_id", &lease.record.workspace_id)?;
check_string("owner_id", &lease.record.owner_id)?;
check_string("authorization_scope", &lease.record.authorization_scope)?;
let expected_key = lease
.record
.platform_api_key_id
.as_ref()
.map(PlatformApiKeyId::as_str);
match (object.get("platform_api_key_id"), expected_key) {
(None | Some(serde_json::Value::Null), None) => {}
(Some(serde_json::Value::String(actual)), Some(expected)) if actual == expected => {}
_ => {
return Err(TaskError::invalid("task executable input binding mismatch"));
}
}
check_string("operation_id", &lease.record.operation_id)?;
match object.get("owner_kind").and_then(|value| value.as_str()) {
Some(actual) if actual == lease.record.owner_kind.as_str() => {}
_ => return Err(TaskError::invalid("task executable input binding mismatch")),
}
match object
.get("operation_version")
.and_then(|value| value.as_u64())
{
Some(actual) if actual == u64::from(lease.record.pins.operation_version) => {}
_ => return Err(TaskError::invalid("task executable input binding mismatch")),
}
let expected_policy = match lease.record.pins.policy_mode {
ToolExecutionMode::Synchronous => "synchronous",
ToolExecutionMode::Background => "background",
ToolExecutionMode::Adaptive => "adaptive",
};
match object.get("policy_mode").and_then(|value| value.as_str()) {
Some(actual) if actual == expected_policy => {}
_ => return Err(TaskError::invalid("task executable input binding mismatch")),
}
check_string("input_fingerprint", &lease.record.input_fingerprint)?;
let input = object
.get("input")
.cloned()
.ok_or_else(|| TaskError::invalid("task executable input binding is missing input"))?;
let canonical = canonical_input_fingerprint(&input)?;
if canonical != lease.record.input_fingerprint {
return Err(TaskError::invalid("task executable input binding mismatch"));
}
validate_task_envelope(&input)?;
let encoded = serde_json::to_vec(&input)
.map_err(|_| TaskError::invalid("task executable input is not serializable"))?;
if encoded.len() > TASK_EXECUTABLE_INPUT_MAX_BYTES {
return Err(TaskError::invalid(
"task executable input exceeds its byte budget",
));
}
if contains_sensitive_task_keys(&input) {
return Err(TaskError::invalid(
"task executable input contains sensitive fields",
));
}
Ok(input)
}
/// Default retention pinned by the application layer when it does not choose one explicitly.
pub fn default_retention_ms() -> i64 {
TASK_DEFAULT_RETENTION_MS
@@ -220,6 +373,7 @@ mod tests {
owner_kind: TaskOwnerKind::Agent,
owner_id: "agent_a".to_owned(),
authorization_scope: "credential:pk_1".to_owned(),
platform_api_key_id: Some(PlatformApiKeyId::new("pk_1")),
operation_id: "op_report".to_owned(),
operation_version: 2,
policy_mode: ToolExecutionMode::Background,