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

+86 -5
View File
@@ -106,6 +106,83 @@ async fn deadline_after_read_only_dispatch_remains_safe_to_retry() {
assert_eq!(failure.stage(), ExecutionStage::Upstream);
}
#[tokio::test]
async fn adapter_retry_child_spans_are_distinct_without_a_durable_attempt() {
let _tracing_test_guard = TRACING_TEST_LOCK.lock().await;
let capture = TraceCapture::default();
let subscriber = tracing_subscriber::registry().with(capture.clone());
let call_count = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let executor = RuntimeExecutorBuilder::new()
.register_adapter(Arc::new(FlakyReadAdapter {
call_count: Arc::clone(&call_count),
}))
.build();
let mut operation: crank_runtime::RuntimeOperation = operation().into();
let Target::Rest(target) = &mut operation.target;
target.method = HttpMethod::Get;
operation.execution_config.retry_policy = Some(RetryPolicy { max_attempts: 2 });
// The synchronous tools/call path has no durable Attempt: every adapter attempt gets its own
// synthetic id. A Task dispatch instead reuses the durable id (mcp-server `attempt_trace`).
let result = async {
let request_root = tracing::info_span!("request_root");
executor
.execute(&operation, &json!({"name": "retry-read"}))
.instrument(request_root)
.await
}
.with_subscriber(subscriber)
.await
.expect("read retry should recover");
assert_eq!(result, json!({"accepted": true}));
let spans = capture.snapshot();
let runtime_span = spans
.iter()
.find(|span| span.name == "runtime.execute")
.expect("runtime.execute span");
assert_eq!(
runtime_span.parent_name,
Some("request_root"),
"the execution continues the caller's trace root"
);
let attempt_spans: Vec<_> = spans
.iter()
.filter(|span| span.name == "adapter_attempt")
.collect();
assert_eq!(attempt_spans.len(), 2);
for span in &attempt_spans {
assert_eq!(span.parent_name, Some("runtime.execute"));
assert!(
!span
.fields
.get("attempt_id")
.unwrap_or(&"".to_string())
.is_empty()
);
assert!(
!span
.fields
.get("attempt_id")
.unwrap_or(&"".to_string())
.contains("traceparent")
);
}
let attempts: Vec<String> = attempt_spans
.iter()
.map(|span| span.fields.get("attempt").cloned().unwrap_or_default())
.collect();
assert!(attempts.contains(&"1".to_string()));
assert!(attempts.contains(&"2".to_string()));
let ids: Vec<String> = attempt_spans
.iter()
.map(|span| span.fields.get("attempt_id").cloned().unwrap_or_default())
.collect();
assert_ne!(ids[0], ids[1]);
}
#[tokio::test]
async fn read_retry_revalidates_adapter_attempt_and_keeps_one_success_outcome() {
let call_count = Arc::new(std::sync::atomic::AtomicUsize::new(0));
@@ -236,11 +313,7 @@ async fn successful_execution_has_real_stages_and_omits_inapplicable_ones() {
.find(|span| span.name == "runtime.execute")
.expect("runtime span");
assert_eq!(runtime.parent_name, Some("mcp.request"));
for child in [
"runtime.arguments.map",
"upstream.http",
"runtime.response.transform",
] {
for child in ["runtime.arguments.map", "runtime.response.transform"] {
assert_eq!(
spans
.iter()
@@ -250,6 +323,14 @@ async fn successful_execution_has_real_stages_and_omits_inapplicable_ones() {
"{child} must be a runtime child"
);
}
assert_eq!(
spans
.iter()
.find(|span| span.name == "upstream.http")
.and_then(|span| span.parent_name),
Some("adapter_attempt"),
"upstream.http must be an adapter child"
);
}
#[tokio::test]