feat(epic4): продолжение ожидающей Task после ввода (Story 4.5)
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

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-индекс.
This commit is contained in:
bsodfather committed 2026-10-30 16:24:12 +00:00
1 parent d80eda7329
commit 90e5357a08
35 files changed
+3243 -91

No files matched your search

+19 -3
View File
@@ -25,7 +25,7 @@ use tracing::{Instrument, Span, debug, warn};
use uuid::Uuid;
use crate::task_attempt::{
TaskAttemptAuthority, TaskAttemptContext, TaskAttemptOutcome, TaskAttemptPlan,
PrepareAttempt, TaskAttemptAuthority, TaskAttemptContext, TaskAttemptOutcome, TaskAttemptPlan,
TaskAttemptRefusal,
};
use crate::task_worker::TaskDispatchPermit;
@@ -225,7 +225,23 @@ impl RuntimeExecutor {
lease_until: lease.lease_until,
};
let plan = match authority.prepare_attempt(&current_lease).await {
Ok(plan) => plan,
Ok(PrepareAttempt::Ready(plan)) => *plan,
Ok(PrepareAttempt::InputRequired(request)) => {
// A missing required input is suspended before the dispatch checkpoint, so this
// generation provably produced no outbound side effect. A CAS/store failure stops
// without writing anything new; the lease expiry recovery makes it retryable.
return match store.suspend_for_input(&current_lease, request).await {
Ok(_) => TaskAttemptOutcome::WaitingForInput,
Err(crank_core::TaskError::StateConflict)
| Err(crank_core::TaskError::NotFound)
| Err(crank_core::TaskError::FingerprintConflict)
| Err(crank_core::TaskError::InputExpired) => TaskAttemptOutcome::Stopped,
Err(error) => {
warn!(error = %error, "input suspension failed; no outbound call");
TaskAttemptOutcome::Stopped
}
};
}
Err(TaskAttemptRefusal::Stopped) => return TaskAttemptOutcome::Stopped,
Err(TaskAttemptRefusal::Failed { code }) => {
// A refused attempt never erases a proven ambiguity: if an earlier attempt of this
@@ -246,7 +262,7 @@ impl RuntimeExecutor {
fence: lease.fence,
expected_version: record.version,
attempt_id: attempt_id.clone(),
input_fingerprint: record.input_fingerprint.clone(),
input_fingerprint: record.effective_input_fingerprint.clone(),
upstream_key_digest: plan.upstream_key_digest.clone(),
retry_allowed: plan.retry_allowed,
};
+2 -2
View File
@@ -118,8 +118,8 @@ pub use rate_limit::{
pub use request_context::{MeteringContext, ResponseCacheScope, RuntimeRequestContext};
pub use secret_crypto::SecretCrypto;
pub use task_attempt::{
TaskAttemptAuthority, TaskAttemptContext, TaskAttemptOutcome, TaskAttemptPlan,
TaskAttemptRefusal,
PrepareAttempt, TaskAttemptAuthority, TaskAttemptContext, TaskAttemptOutcome, TaskAttemptPlan,
TaskAttemptRefusal, missing_required_input,
};
pub use task_worker::{
TaskDispatchPermit, TaskHandler, TaskWorker, TaskWorkerConfig, TaskWorkerError,
+28 -1
View File
@@ -44,7 +44,31 @@ pub trait TaskAttemptAuthority: Send + Sync {
async fn prepare_attempt(
&self,
lease: &TaskLease,
) -> Result<TaskAttemptPlan, TaskAttemptRefusal>;
) -> 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.
@@ -108,6 +132,9 @@ pub enum TaskAttemptOutcome {
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,
}
+15
View File
@@ -243,6 +243,18 @@ impl TaskWorker {
// Reap finished attempts before claiming more.
while active.try_join_next().is_some() {}
// The bounded TTL sweep runs on every poll, including when all local slots are busy: an
// expired input wait must end `failed` with an audit reason even without free capacity.
match self.store.expire_input_waits(self.config.batch_limit).await {
Ok(expired) if expired > 0 => {
debug!(expired, "expired input waits were failed")
}
Ok(_) => {}
Err(error) => {
warn!(error = %error, "input TTL sweep failed; retrying on next scan")
}
}
let available = self.config.max_inflight.saturating_sub(active.len());
if available > 0 {
let batch_limit = self
@@ -405,6 +417,9 @@ async fn process_lease(
TaskAttemptOutcome::OutcomeUnknown => {
warn!(task_id = %task_id, "durable task outcome is uncertain; no automatic retry");
}
TaskAttemptOutcome::WaitingForInput => {
debug!(task_id = %task_id, "durable task suspended until validated input arrives");
}
TaskAttemptOutcome::Stopped => {
debug!(task_id = %task_id, "durable task attempt stopped without a new outcome");
}
+193 -20
View File
@@ -17,9 +17,10 @@ use crank_core::PlatformApiKeyId;
use crank_core::{
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,
TaskAcceptRequest, TaskAcceptance, TaskAccess, TaskEnvelope, TaskError, TaskId,
TaskInputUpdateOutcome, TaskInputUpdateRequest, TaskLease, TaskOwnerKind, TaskPins, TaskRecord,
TaskStore, TaskSupportIds, ToolExecutionMode, contains_sensitive_task_keys, current_unix_ms,
validate_task_envelope,
};
use sha2::{Digest, Sha256};
@@ -295,28 +296,46 @@ impl TaskService {
_ => return Err(TaskError::invalid("task executable input binding mismatch")),
}
check_string("input_fingerprint", &lease.record.input_fingerprint)?;
let input = object
let base_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 {
if canonical_input_fingerprint(&base_input)? != 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)
// A committed continuation replaces only the effective payload. The acceptance fingerprint and
// the original input stay in the binding, so an original accept replay is still a replay.
let effective_input = match object.get("continuation") {
Some(continuation) => {
let continuation = continuation
.as_object()
.ok_or_else(|| TaskError::invalid("task input continuation is invalid"))?;
let effective = continuation
.get("effective_input_fingerprint")
.and_then(|value| value.as_str())
.ok_or_else(|| TaskError::invalid("task input continuation is invalid"))?;
if effective != lease.record.effective_input_fingerprint {
return Err(TaskError::invalid(
"task input continuation fingerprint mismatch",
));
}
let input = continuation.get("input").cloned().ok_or_else(|| {
TaskError::invalid("task input continuation is missing input")
})?;
if canonical_input_fingerprint(&input)? != effective {
return Err(TaskError::invalid("task input continuation is invalid"));
}
input
}
None => {
if lease.record.effective_input_fingerprint != lease.record.input_fingerprint {
return Err(TaskError::invalid("task input continuation is missing"));
}
base_input
}
};
validate_executable_payload(&effective_input)?;
Ok(effective_input)
}
/// Default retention pinned by the application layer when it does not choose one explicitly.
@@ -344,6 +363,105 @@ impl TaskService {
pub fn input_fingerprint(input: &serde_json::Value) -> Result<String, TaskError> {
canonical_input_fingerprint(input)
}
/// Applies one additional validated input to a suspended Task (Story 4.5).
///
/// The stored native schema snapshot is the only validation authority; the canonical digest binds
/// the effective payload, and the existing encrypted executable-input binding is extended with a
/// continuation segment instead of a second cipher store. The store transaction owns authority,
/// receipt, generation, TTL and CAS, so an identical replay returns the committed outcome.
pub async fn update_input(
&self,
access: &TaskAccess,
task_id: TaskId,
wait_id: &str,
expected_version: u32,
update_key: &str,
input: &serde_json::Value,
) -> Result<TaskInputUpdateOutcome, TaskError> {
access.validate()?;
validate_task_envelope(input)?;
if contains_sensitive_task_keys(input) {
return Err(TaskError::invalid(
"task executable input contains sensitive fields",
));
}
let canonical_fingerprint = canonical_input_fingerprint(input)?;
let pending = self.store.input_request(access, task_id).await?;
if pending.wait_id != wait_id {
return Err(TaskError::StateConflict);
}
// The immutable snapshot, never the current publication, is the schema authority.
let schema: crank_schema::Schema = serde_json::from_value(pending.schema_snapshot.clone())
.map_err(|_| TaskError::unavailable("stored task input schema is invalid"))?;
schema
.validate_shape(input)
.map_err(|_| TaskError::invalid("task input does not match the pinned input schema"))?;
let update_key_digest = input_update_key_digest(access, task_id, wait_id, update_key)?;
let crypto = self.crypto.as_ref().ok_or_else(|| {
TaskError::invalid("secret crypto is required for durable Task continuation")
})?;
let (ciphertext, key_version, epoch) = self
.store
.read_executable_input_for_update(access, task_id)
.await?;
let binding = crypto
.decrypt_for_epoch(&key_version, epoch, &ciphertext)
.map_err(|error| TaskError::invalid(error.to_string()))?;
let mut object = binding
.as_object()
.cloned()
.ok_or_else(|| TaskError::invalid("task executable input binding is invalid"))?;
check_binding_string(&object, "task_id", &task_id.to_string())?;
check_binding_string(&object, "workspace_id", &access.workspace_id)?;
check_binding_string(&object, "owner_id", &access.owner_id)?;
check_binding_string(&object, "authorization_scope", &access.authorization_scope)?;
let base_input = object
.get("input")
.cloned()
.ok_or_else(|| TaskError::invalid("task executable input binding is missing input"))?;
let base_fingerprint = object
.get("input_fingerprint")
.and_then(|value| value.as_str())
.ok_or_else(|| TaskError::invalid("task executable input binding is invalid"))?;
if canonical_input_fingerprint(&base_input)? != base_fingerprint {
return Err(TaskError::invalid("task executable input binding mismatch"));
}
object.insert(
"binding_format_version".to_owned(),
serde_json::json!(2_u32),
);
object.insert(
"continuation".to_owned(),
serde_json::json!({
"wait_id": wait_id,
"schema_revision": pending.schema_revision,
"effective_input_fingerprint": canonical_fingerprint,
"input": input,
}),
);
let continuation = crypto
.encrypt(&serde_json::Value::Object(object))
.map_err(|error| TaskError::invalid(error.to_string()))?;
if continuation.len() > TASK_EXECUTABLE_INPUT_CIPHERTEXT_MAX_BYTES {
return Err(TaskError::invalid(
"encrypted task input exceeds its byte budget",
));
}
let request = TaskInputUpdateRequest {
access: access.clone(),
task_id,
wait_id: wait_id.to_owned(),
expected_version,
update_key_digest,
effective_input_fingerprint: canonical_fingerprint.clone(),
canonical_fingerprint,
executable_input_ciphertext: continuation,
executable_input_key_version: crypto.key_version().to_owned(),
executable_input_master_key_epoch: crypto.master_key_epoch(),
};
self.store.apply_input(request).await
}
}
fn deadline_unix_ms(deadline: Instant) -> i64 {
@@ -394,6 +512,61 @@ fn hex_digest(bytes: &[u8]) -> String {
.collect()
}
fn check_binding_string(
object: &serde_json::Map<String, serde_json::Value>,
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")),
}
}
fn validate_executable_payload(input: &serde_json::Value) -> Result<(), TaskError> {
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(())
}
/// Digest of the scoped update key. The key itself never leaves the caller, and the scope covers the
/// exact Task generation so one key cannot be replayed across Tasks or waits.
fn input_update_key_digest(
access: &TaskAccess,
task_id: TaskId,
wait_id: &str,
key: &str,
) -> Result<String, TaskError> {
if key.is_empty()
|| key.len() > TASK_SCOPED_KEY_MAX_BYTES
|| key.bytes().any(|byte| byte.is_ascii_control())
{
return Err(TaskError::invalid("task input update key is invalid"));
}
let material = format!(
"{}\n{}\n{}\n{}\n{}\n{}\n{}",
access.workspace_id,
access.owner_kind.as_str(),
access.owner_id,
access.authorization_scope,
task_id,
wait_id,
key
);
Ok(hex_digest(material.as_bytes()))
}
#[cfg(test)]
mod tests {
use super::*;