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
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:
1 parent
6df6ffac4e
commit
f9f8c625d1
52 files changed
+5142
-232
No files matched your search
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user