feat(epic4): подтверждать durable Task после атомарного PG-commit (Story 4.2)
CI / UI Checks (pull_request) Successful in 8s
CI / Rust Checks (pull_request) Successful in 19m34s
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

Application entry выдаёт Task ID только после атомарного PostgreSQL commit
Task+intent+capacity; replay/conflict, owner scope, bounded envelope,
terminal CAS и fail-closed readiness проверены на реальном PG.

Также включён принятый план перехода на rmcp (только документ, миграция не
запускается).
This commit is contained in:
bsodfather committed 2026-10-27 00:09:36 +00:00
1 parent cc612516a2
commit 2219a7217d
37 files changed
+4028 -136

No files matched your search

+1 -1
View File
@@ -314,7 +314,7 @@ fn request_fingerprint(input: &Value) -> Result<String, RuntimeError> {
Ok(URL_SAFE_NO_PAD.encode(Sha256::digest(encoded)))
}
fn canonical_json(value: &Value) -> Value {
pub(crate) fn canonical_json(value: &Value) -> Value {
match value {
Value::Object(object) => {
let mut entries = object.iter().collect::<Vec<_>>();
+2
View File
@@ -15,6 +15,7 @@ mod rate_limit;
mod request_context;
mod request_preparation;
mod response_cache;
mod tasks;
pub fn validate_resource_template_parameter(
schema: &crank_schema::Schema,
value: &serde_json::Value,
@@ -114,3 +115,4 @@ pub use rate_limit::{
};
pub use request_context::{MeteringContext, ResponseCacheScope, RuntimeRequestContext};
pub use secret_crypto::SecretCrypto;
pub use tasks::{TaskAcceptDraft, TaskOutcome, TaskService};
+266
View File
@@ -0,0 +1,266 @@
//! Runtime application service of durable Tasks (Story 4.2, FR-22/FR-23).
//!
//! The service is the only place that turns an approved background request into the durable domain
//! request: bounded validated input, canonical input fingerprint, full-scope idempotency digest,
//! pinned Published Version/deadline/retention and the support identities of the request. It holds an
//! owned request, never `ResolvedAuth` or raw secrets, and it never dispatches: the durable store
//! commits Task + dispatch intent + queue slot in one transaction and only then produces an
//! acknowledgement.
//!
//! Reads go through the same owner-scoped access proof, so the durable row is only fetched for the
//! caller that owns it. There is no in-memory fallback: a store failure is a typed refusal.
use std::sync::Arc;
use std::time::Instant;
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,
};
use sha2::{Digest, Sha256};
/// One owned background request, already authorized by the application layer.
#[derive(Clone, Debug)]
pub struct TaskAcceptDraft {
pub workspace_id: String,
pub owner_kind: TaskOwnerKind,
pub owner_id: String,
/// Server-derived authorization scope identity of the verified principal.
pub authorization_scope: String,
pub operation_id: String,
pub operation_version: u32,
pub policy_mode: ToolExecutionMode,
/// Caller key, bounded before it becomes a full-scope digest.
pub scoped_key: String,
/// Canonical executable input; it is validated, fingerprinted, then persisted redacted.
pub input: serde_json::Value,
pub correlation: CorrelationContext,
/// Absolute execution deadline of the accepted work.
pub deadline: Instant,
/// Retention after the execution deadline.
pub retention_ms: i64,
pub approval_reference: Option<String>,
}
/// Projection of the durable status/result read. `result`/`error` are only present once a terminal
/// transition committed; a non-terminal Task reports its state and inputs without inventing output.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TaskOutcome {
pub task_id: TaskId,
pub state: crank_core::TaskState,
pub result: Option<serde_json::Value>,
pub error: Option<serde_json::Value>,
}
impl TaskOutcome {
fn from_record(record: TaskRecord) -> Self {
Self {
task_id: record.task_id,
state: record.state,
result: record.result.map(|envelope| envelope.value().clone()),
error: record.error.map(|envelope| envelope.value().clone()),
}
}
}
#[derive(Clone)]
pub struct TaskService {
store: Arc<dyn TaskStore>,
}
impl TaskService {
pub fn new(store: Arc<dyn TaskStore>) -> Self {
Self { store }
}
/// Readiness of the mandatory durable Task state.
pub async fn health(&self) -> Result<(), TaskError> {
self.store.health().await
}
/// 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)?;
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 request = TaskAcceptRequest {
task_id: TaskId::generate(),
workspace_id: draft.workspace_id,
owner_kind: draft.owner_kind,
owner_id: draft.owner_id,
authorization_scope: draft.authorization_scope,
operation_id: draft.operation_id,
pins: TaskPins {
operation_version: draft.operation_version,
policy_mode: draft.policy_mode,
execution_deadline_unix_ms,
retain_until_unix_ms: execution_deadline_unix_ms.saturating_add(retention_ms),
approval_reference: draft.approval_reference,
},
scoped_key,
input_fingerprint,
input: TaskEnvelope::try_redacted(&draft.input)?,
support: TaskSupportIds::new(
draft.correlation.request_id().clone(),
draft.correlation.trace_context(),
),
};
self.store.accept(request).await
}
/// Owner-scoped status read. A foreign or absent Task is one typed not-found.
pub async fn status(
&self,
access: &TaskAccess,
task_id: TaskId,
) -> Result<TaskRecord, TaskError> {
self.store.read(access, task_id).await
}
/// Owner-scoped result read, projected from the same authorized row.
pub async fn result(
&self,
access: &TaskAccess,
task_id: TaskId,
) -> Result<TaskOutcome, TaskError> {
Ok(TaskOutcome::from_record(
self.store.read(access, task_id).await?,
))
}
/// Default retention pinned by the application layer when it does not choose one explicitly.
pub fn default_retention_ms() -> i64 {
TASK_DEFAULT_RETENTION_MS
}
/// Scoped lookup of an already accepted Task by the same full-scope identity, used to keep a
/// retry of an explicitly pinned version from being accepted as new work.
pub async fn lookup(&self, draft: &TaskAcceptDraft) -> Result<Option<TaskRecord>, TaskError> {
let scoped_key = scoped_key_digest(draft)?;
let access = TaskAccess {
workspace_id: draft.workspace_id.clone(),
owner_kind: draft.owner_kind,
owner_id: draft.owner_id.clone(),
authorization_scope: draft.authorization_scope.clone(),
};
self.store
.find(&access, &draft.operation_id, &scoped_key)
.await
}
/// Canonical digest of a validated input, exposed so the application layer can compare a stored
/// Task against the request it is retrying without duplicating the canonicalization.
pub fn input_fingerprint(input: &serde_json::Value) -> Result<String, TaskError> {
canonical_input_fingerprint(input)
}
}
fn deadline_unix_ms(deadline: Instant) -> i64 {
let remaining = u64::try_from(
deadline
.saturating_duration_since(Instant::now())
.as_millis(),
)
.unwrap_or_default();
current_unix_ms().saturating_add(i64::try_from(remaining.max(1)).unwrap_or(i64::MAX))
}
/// Digest of the caller key over the full Task identity. The scope is never abbreviated to a
/// connection, protocol revision or raw credential, so two callers cannot collide on one key.
fn scoped_key_digest(draft: &TaskAcceptDraft) -> Result<String, TaskError> {
let key = draft.scoped_key.as_str();
if key.is_empty()
|| key.len() > TASK_SCOPED_KEY_MAX_BYTES
|| key.bytes().any(|byte| byte.is_ascii_control())
{
return Err(TaskError::invalid("task idempotency key is invalid"));
}
let material = format!(
"{}\n{}\n{}\n{}\n{}\n{}",
draft.workspace_id,
draft.owner_kind.as_str(),
draft.owner_id,
draft.authorization_scope,
draft.operation_id,
key
);
Ok(hex_digest(material.as_bytes()))
}
/// Canonical digest of the validated executable input. Object key order never changes the digest,
/// while any material business or secret value does.
fn canonical_input_fingerprint(input: &serde_json::Value) -> Result<String, TaskError> {
let canonical = crate::idempotency::canonical_json(input);
let encoded = serde_json::to_vec(&canonical)
.map_err(|_| TaskError::invalid("task input is not canonicalizable"))?;
Ok(hex_digest(&encoded))
}
fn hex_digest(bytes: &[u8]) -> String {
Sha256::digest(bytes)
.iter()
.map(|byte| format!("{byte:02x}"))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn draft(key: &str, input: serde_json::Value) -> TaskAcceptDraft {
TaskAcceptDraft {
workspace_id: "ws_default".to_owned(),
owner_kind: TaskOwnerKind::Agent,
owner_id: "agent_a".to_owned(),
authorization_scope: "credential:pk_1".to_owned(),
operation_id: "op_report".to_owned(),
operation_version: 2,
policy_mode: ToolExecutionMode::Background,
scoped_key: key.to_owned(),
input,
correlation: CorrelationContext::generate(),
deadline: Instant::now() + std::time::Duration::from_secs(30),
retention_ms: TASK_DEFAULT_RETENTION_MS,
approval_reference: None,
}
}
#[test]
fn canonical_fingerprint_ignores_key_order_and_tracks_values() {
let first = canonical_input_fingerprint(&json!({"a": 1, "b": {"c": 2}})).unwrap();
let reordered = canonical_input_fingerprint(&json!({"b": {"c": 2}, "a": 1})).unwrap();
assert_eq!(first, reordered);
assert_eq!(first.len(), 64);
let changed = canonical_input_fingerprint(&json!({"a": 1, "b": {"c": 3}})).unwrap();
assert_ne!(first, changed);
}
#[test]
fn scoped_key_digest_covers_the_whole_identity() {
let base = scoped_key_digest(&draft("key_1", json!({}))).unwrap();
let mut foreign = draft("key_1", json!({}));
foreign.owner_id = "agent_b".to_owned();
assert_ne!(base, scoped_key_digest(&foreign).unwrap());
let mut other_scope = draft("key_1", json!({}));
other_scope.authorization_scope = "credential:pk_2".to_owned();
assert_ne!(base, scoped_key_digest(&other_scope).unwrap());
assert!(scoped_key_digest(&draft("", json!({}))).is_err());
assert!(
scoped_key_digest(&draft(
&"k".repeat(TASK_SCOPED_KEY_MAX_BYTES + 1),
json!({})
))
.is_err()
);
}
}