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),