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-индекс.
296 lines
12 KiB
Rust
296 lines
12 KiB
Rust
//! Continuation of an accepted Task through a validated additional input (Story 4.5, FR-25).
|
|
//!
|
|
//! A Task that cannot run because the pinned operation still lacks a required input item is
|
|
//! suspended as `input_required` before any outbound dispatch. The durable request keeps the exact
|
|
//! immutable schema snapshot, its JSON projection, safe prompt metadata, the absolute TTL and the
|
|
//! update fingerprint contract. A valid update moves the Task back to `working` exactly once; an
|
|
//! identical replay returns the committed outcome and a conflicting or stale reply is typed.
|
|
//!
|
|
//! Deliberately absent: raw input in the request/receipt/audit read models, a second cipher store and
|
|
//! any public transport. The regular executable-input ciphertext carries the continuation binding.
|
|
|
|
use serde_json::Value;
|
|
|
|
use crate::task::{TaskAccess, TaskError, TaskId};
|
|
|
|
/// Version of the persisted input-continuation contract. A stored snapshot always declares the
|
|
/// version it was written with, so a later binary never reinterprets it silently.
|
|
pub const TASK_INPUT_SCHEMA_FORMAT_VERSION: u32 = 1;
|
|
/// Bound of a wait identity before it is persisted.
|
|
pub const TASK_INPUT_WAIT_ID_MAX_BYTES: usize = 64;
|
|
/// Bound of the safe prompt code (never the prompt text or an input value).
|
|
pub const TASK_INPUT_PROMPT_CODE_MAX_BYTES: usize = 64;
|
|
/// Bound of the missing-field path metadata.
|
|
pub const TASK_INPUT_MAX_MISSING_FIELDS: usize = 32;
|
|
/// Bound of one missing-field path.
|
|
pub const TASK_INPUT_FIELD_PATH_MAX_BYTES: usize = 160;
|
|
|
|
/// Durable request of additional input for one suspended Task.
|
|
///
|
|
/// `schema_snapshot` is the native serialized schema subset the server validates against; the JSON
|
|
/// projection is presentation metadata only and never the validation authority. `expected_version`
|
|
/// is the Task version a caller must present with the answer.
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct TaskInputRequest {
|
|
pub wait_id: String,
|
|
pub expected_version: u32,
|
|
pub schema_revision: u32,
|
|
pub schema_format_version: u32,
|
|
pub schema_snapshot: Value,
|
|
pub projected_schema: Value,
|
|
pub prompt_code: String,
|
|
pub missing_fields: Vec<String>,
|
|
pub expires_at_unix_ms: i64,
|
|
pub fingerprint_format_version: u32,
|
|
}
|
|
|
|
impl TaskInputRequest {
|
|
pub fn validate(&self) -> Result<(), TaskError> {
|
|
if self.wait_id.is_empty()
|
|
|| self.wait_id.len() > TASK_INPUT_WAIT_ID_MAX_BYTES
|
|
|| self.wait_id.bytes().any(|byte| byte.is_ascii_control())
|
|
{
|
|
return Err(TaskError::invalid("task input wait identity is invalid"));
|
|
}
|
|
if self.expected_version == 0 || self.schema_revision == 0 {
|
|
return Err(TaskError::invalid(
|
|
"task input request generation is invalid",
|
|
));
|
|
}
|
|
if self.schema_format_version < TASK_INPUT_SCHEMA_FORMAT_VERSION
|
|
|| self.fingerprint_format_version < TASK_INPUT_SCHEMA_FORMAT_VERSION
|
|
{
|
|
return Err(TaskError::invalid(
|
|
"task input request format version is invalid",
|
|
));
|
|
}
|
|
if self.schema_snapshot.as_object().is_none() || self.projected_schema.as_object().is_none()
|
|
{
|
|
return Err(TaskError::invalid("task input schema snapshot is invalid"));
|
|
}
|
|
if self.prompt_code.is_empty() || self.prompt_code.len() > TASK_INPUT_PROMPT_CODE_MAX_BYTES
|
|
{
|
|
return Err(TaskError::invalid("task input prompt code is invalid"));
|
|
}
|
|
if self.missing_fields.len() > TASK_INPUT_MAX_MISSING_FIELDS
|
|
|| self
|
|
.missing_fields
|
|
.iter()
|
|
.any(|field| field.is_empty() || field.len() > TASK_INPUT_FIELD_PATH_MAX_BYTES)
|
|
{
|
|
return Err(TaskError::invalid(
|
|
"task input missing-field metadata is invalid",
|
|
));
|
|
}
|
|
if self.expires_at_unix_ms <= 0 {
|
|
return Err(TaskError::invalid("task input TTL is invalid"));
|
|
}
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
/// Authoritative write of one validated answer. The transaction owns schema-generation, TTL,
|
|
/// fingerprint and CAS checks; this request only carries the committed values.
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct TaskInputUpdateRequest {
|
|
pub access: TaskAccess,
|
|
pub task_id: TaskId,
|
|
pub wait_id: String,
|
|
pub expected_version: u32,
|
|
/// Digest of the scoped update key; the caller key is never persisted.
|
|
pub update_key_digest: String,
|
|
/// Canonical digest of the validated full executable input.
|
|
pub canonical_fingerprint: String,
|
|
/// Effective execution fingerprint of the resumed payload (never the acceptance fingerprint).
|
|
pub effective_input_fingerprint: String,
|
|
pub executable_input_ciphertext: String,
|
|
pub executable_input_key_version: String,
|
|
pub executable_input_master_key_epoch: i64,
|
|
}
|
|
|
|
impl TaskInputUpdateRequest {
|
|
pub fn validate(&self) -> Result<(), TaskError> {
|
|
self.access.validate()?;
|
|
if self.wait_id.is_empty() || self.wait_id.len() > TASK_INPUT_WAIT_ID_MAX_BYTES {
|
|
return Err(TaskError::invalid("task input wait identity is invalid"));
|
|
}
|
|
if self.expected_version == 0 {
|
|
return Err(TaskError::invalid("task input version is invalid"));
|
|
}
|
|
if !valid_digest(&self.update_key_digest)
|
|
|| !valid_digest(&self.canonical_fingerprint)
|
|
|| !valid_digest(&self.effective_input_fingerprint)
|
|
{
|
|
return Err(TaskError::invalid("task input digest is invalid"));
|
|
}
|
|
if self.executable_input_ciphertext.is_empty()
|
|
|| self.executable_input_ciphertext.len()
|
|
> crate::task::TASK_EXECUTABLE_INPUT_CIPHERTEXT_MAX_BYTES
|
|
{
|
|
return Err(TaskError::invalid(
|
|
"task continuation ciphertext is invalid",
|
|
));
|
|
}
|
|
if self.executable_input_key_version.is_empty()
|
|
|| self.executable_input_key_version.len() > 64
|
|
|| self.executable_input_master_key_epoch < 1
|
|
{
|
|
return Err(TaskError::invalid(
|
|
"task continuation ciphertext is invalid",
|
|
));
|
|
}
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
/// Committed outcome of one input update. An identical replay returns the same stored outcome with
|
|
/// `replayed = true` instead of repeating the CAS, audit or dispatch.
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub struct TaskInputUpdateOutcome {
|
|
pub task_id: TaskId,
|
|
pub wait_id: String,
|
|
pub state: crate::task::TaskState,
|
|
pub version: u32,
|
|
pub replayed: bool,
|
|
}
|
|
|
|
fn valid_digest(value: &str) -> bool {
|
|
value.len() == 64
|
|
&& value
|
|
.bytes()
|
|
.all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
|
|
}
|
|
|
|
/// Durable input-continuation operations of the Task store.
|
|
///
|
|
/// Split out of the general [`crate::task::TaskStore`] port so the lifecycle store stays readable and
|
|
/// the continuation contract (suspend, answer, receipt, expiry) is implemented and audited as one
|
|
/// cohesive surface. [`crate::task::TaskStore`] extends this trait, so an owned `Arc<dyn TaskStore>`
|
|
/// exposes both halves through one object.
|
|
#[async_trait::async_trait]
|
|
pub trait TaskInputStore: Send + Sync {
|
|
/// Suspends a leased Task that still lacks a required input of its pinned operation. The
|
|
/// transaction persists the immutable request and its audit row, moves `working` to
|
|
/// `input_required` exactly once, releases the worker lease and keeps the existing admission
|
|
/// permit. No outbound dispatch may have happened in this generation.
|
|
async fn suspend_for_input(
|
|
&self,
|
|
lease: &crate::task::TaskLease,
|
|
request: TaskInputRequest,
|
|
) -> Result<crate::task::TaskRecord, TaskError>;
|
|
|
|
/// Owner-scoped read of the durable input request of one Task.
|
|
async fn input_request(
|
|
&self,
|
|
access: &TaskAccess,
|
|
task_id: TaskId,
|
|
) -> Result<TaskInputRequest, TaskError>;
|
|
|
|
/// Owner-scoped read of the executable-input binding that a committed continuation may extend.
|
|
/// It is not lease-authorized: it only serves the update transaction and never dispatch.
|
|
async fn read_executable_input_for_update(
|
|
&self,
|
|
access: &TaskAccess,
|
|
task_id: TaskId,
|
|
) -> Result<(String, String, i64), TaskError>;
|
|
|
|
/// Applies exactly one validated answer under a row lock: authority recheck, receipt lookup,
|
|
/// generation/TTL check, atomic ciphertext/effective-fingerprint/receipt/`working` transition and
|
|
/// audit. An identical replay returns the stored outcome without a second transition.
|
|
async fn apply_input(
|
|
&self,
|
|
request: TaskInputUpdateRequest,
|
|
) -> Result<TaskInputUpdateOutcome, TaskError>;
|
|
|
|
/// Bounded sweep of `input_required` Tasks whose TTL elapsed: `failed` with an audit reason and
|
|
/// the release of the admission permit, without any dispatch.
|
|
async fn expire_input_waits(&self, batch: u32) -> Result<u64, TaskError>;
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use serde_json::json;
|
|
|
|
fn request() -> TaskInputRequest {
|
|
TaskInputRequest {
|
|
wait_id: "wait-1".to_owned(),
|
|
expected_version: 2,
|
|
schema_revision: 1,
|
|
schema_format_version: TASK_INPUT_SCHEMA_FORMAT_VERSION,
|
|
schema_snapshot: json!({"type": "object", "fields": {}}),
|
|
projected_schema: json!({"type": "object", "properties": {}}),
|
|
prompt_code: "required_input_missing".to_owned(),
|
|
missing_fields: vec!["$.email".to_owned()],
|
|
expires_at_unix_ms: 1_900_000_000_000,
|
|
fingerprint_format_version: TASK_INPUT_SCHEMA_FORMAT_VERSION,
|
|
}
|
|
}
|
|
|
|
fn update() -> TaskInputUpdateRequest {
|
|
TaskInputUpdateRequest {
|
|
access: crate::task::TaskAccess {
|
|
workspace_id: "ws_default".to_owned(),
|
|
owner_kind: crate::task::TaskOwnerKind::Agent,
|
|
owner_id: "agent_a".to_owned(),
|
|
authorization_scope: "credential:pk_1".to_owned(),
|
|
},
|
|
task_id: crate::task::TaskId::generate(),
|
|
wait_id: "wait-1".to_owned(),
|
|
expected_version: 2,
|
|
update_key_digest: "a".repeat(64),
|
|
canonical_fingerprint: "b".repeat(64),
|
|
effective_input_fingerprint: "c".repeat(64),
|
|
executable_input_ciphertext: "sealed".to_owned(),
|
|
executable_input_key_version: "key-v1".to_owned(),
|
|
executable_input_master_key_epoch: 1,
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn input_request_holds_generation_schema_ttl_and_bounds() {
|
|
assert!(request().validate().is_ok());
|
|
|
|
let mut no_wait = request();
|
|
no_wait.wait_id.clear();
|
|
assert!(no_wait.validate().is_err());
|
|
|
|
let mut no_generation = request();
|
|
no_generation.expected_version = 0;
|
|
assert!(no_generation.validate().is_err());
|
|
|
|
let mut bad_schema = request();
|
|
bad_schema.schema_snapshot = json!("not-an-object");
|
|
assert!(bad_schema.validate().is_err());
|
|
|
|
let mut no_ttl = request();
|
|
no_ttl.expires_at_unix_ms = 0;
|
|
assert!(no_ttl.validate().is_err());
|
|
|
|
let mut too_many_fields = request();
|
|
too_many_fields.missing_fields = vec!["$.x".to_owned(); TASK_INPUT_MAX_MISSING_FIELDS + 1];
|
|
assert!(too_many_fields.validate().is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn update_request_rejects_invalid_digests_and_ciphertext_bounds() {
|
|
assert!(update().validate().is_ok());
|
|
|
|
let mut short_digest = update();
|
|
short_digest.canonical_fingerprint = "abc".to_owned();
|
|
assert!(short_digest.validate().is_err());
|
|
|
|
let mut upper_digest = update();
|
|
upper_digest.update_key_digest = "A".repeat(64);
|
|
assert!(upper_digest.validate().is_err());
|
|
|
|
let mut no_ciphertext = update();
|
|
no_ciphertext.executable_input_ciphertext.clear();
|
|
assert!(no_ciphertext.validate().is_err());
|
|
|
|
let mut no_epoch = update();
|
|
no_epoch.executable_input_master_key_epoch = 0;
|
|
assert!(no_epoch.validate().is_err());
|
|
}
|
|
}
|