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
@@ -577,6 +577,145 @@ pub(super) async fn insert_admission_entry(
|
||||
Ok(u64::try_from(ticket_id).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Shared grant step used by the durable Task store: grants one reserved Task intent if capacity allows,
|
||||
/// marks it `executing`, persists the weighted round-robin cursor, and returns its Task id. It reuses
|
||||
/// the same selector/capacity logic as synchronous admission so no second policy exists.
|
||||
pub(super) async fn grant_next_task(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &str,
|
||||
cursor: &AdmissionCursor,
|
||||
limits: &AdmissionLimits,
|
||||
scheduler: AdmissionSchedulerConfig,
|
||||
) -> Result<(Option<Uuid>, AdmissionCursor), AttemptError> {
|
||||
let rows = sqlx::query(
|
||||
"select ticket_id, agent_key, operation_id, task_id
|
||||
from execution_admission_entries
|
||||
where state = 'reserved' and task_id is not null
|
||||
order by ticket_id
|
||||
limit $1
|
||||
for update skip locked",
|
||||
)
|
||||
.bind(QUEUE_READ_LIMIT)
|
||||
.fetch_all(&mut **transaction)
|
||||
.await
|
||||
.map_err(AttemptError::from_sql)?;
|
||||
if rows.is_empty() {
|
||||
return Ok((None, cursor.clone()));
|
||||
}
|
||||
struct Candidate {
|
||||
entry: AdmissionQueueEntry,
|
||||
task_id: Uuid,
|
||||
}
|
||||
let mut candidates = Vec::with_capacity(rows.len());
|
||||
for row in rows {
|
||||
let ticket_id: i64 = row.try_get("ticket_id").map_err(AttemptError::from_sql)?;
|
||||
let task_id: Uuid = row.try_get("task_id").map_err(AttemptError::from_sql)?;
|
||||
candidates.push(Candidate {
|
||||
entry: AdmissionQueueEntry {
|
||||
ticket_id: u64::try_from(ticket_id).unwrap_or_default(),
|
||||
sequence: 0,
|
||||
agent_key: row.try_get("agent_key").map_err(AttemptError::from_sql)?,
|
||||
operation_id: row
|
||||
.try_get("operation_id")
|
||||
.map_err(AttemptError::from_sql)?,
|
||||
},
|
||||
task_id,
|
||||
});
|
||||
}
|
||||
let queue: Vec<AdmissionQueueEntry> = candidates.iter().map(|c| c.entry.clone()).collect();
|
||||
let Some(selection) = select_next_grant(&queue, cursor, scheduler) else {
|
||||
return Ok((None, cursor.clone()));
|
||||
};
|
||||
let head_index = selection.index;
|
||||
let head = &candidates[head_index];
|
||||
|
||||
let global_executing: i64 = sqlx::query(
|
||||
"select count(*)::bigint as count from execution_admission_entries where state = 'executing'",
|
||||
)
|
||||
.fetch_one(&mut **transaction)
|
||||
.await
|
||||
.map_err(AttemptError::from_sql)?
|
||||
.try_get("count")
|
||||
.map_err(AttemptError::from_sql)?;
|
||||
let agent_counts = sqlx::query(
|
||||
"select agent_key as key, count(*)::bigint as count
|
||||
from execution_admission_entries where state = 'executing' group by agent_key",
|
||||
)
|
||||
.fetch_all(&mut **transaction)
|
||||
.await
|
||||
.map_err(AttemptError::from_sql)?;
|
||||
let mut agent_map = std::collections::BTreeMap::new();
|
||||
for row in agent_counts {
|
||||
let key: String = row.try_get("key").map_err(AttemptError::from_sql)?;
|
||||
let count: i64 = row.try_get("count").map_err(AttemptError::from_sql)?;
|
||||
agent_map.insert(key, u64::try_from(count).unwrap_or_default());
|
||||
}
|
||||
let tool_counts = sqlx::query(
|
||||
"select operation_id as key, count(*)::bigint as count
|
||||
from execution_admission_entries where state = 'executing' group by operation_id",
|
||||
)
|
||||
.fetch_all(&mut **transaction)
|
||||
.await
|
||||
.map_err(AttemptError::from_sql)?;
|
||||
let mut tool_map = std::collections::BTreeMap::new();
|
||||
for row in tool_counts {
|
||||
let key: String = row.try_get("key").map_err(AttemptError::from_sql)?;
|
||||
let count: i64 = row.try_get("count").map_err(AttemptError::from_sql)?;
|
||||
tool_map.insert(key, u64::try_from(count).unwrap_or_default());
|
||||
}
|
||||
|
||||
if u64::try_from(global_executing).unwrap_or(u64::MAX)
|
||||
>= u64::try_from(limits.global_limit).unwrap_or(u64::MAX)
|
||||
{
|
||||
return Ok((None, cursor.clone()));
|
||||
}
|
||||
let agent_executing = agent_map
|
||||
.get(head.entry.agent_key.as_str())
|
||||
.copied()
|
||||
.unwrap_or_default();
|
||||
if agent_executing >= u64::try_from(limits.agent_limit).unwrap_or(u64::MAX) {
|
||||
return Ok((None, cursor.clone()));
|
||||
}
|
||||
let tool_executing = tool_map
|
||||
.get(head.entry.operation_id.as_str())
|
||||
.copied()
|
||||
.unwrap_or_default();
|
||||
if tool_executing >= u64::try_from(limits.tool_limit).unwrap_or(u64::MAX) {
|
||||
return Ok((None, cursor.clone()));
|
||||
}
|
||||
|
||||
sqlx::query(
|
||||
"update execution_admission_entries
|
||||
set state = 'executing', granted_at = clock_timestamp()
|
||||
where ticket_id = $1 and state = 'reserved'",
|
||||
)
|
||||
.bind(i64::try_from(head.entry.ticket_id).unwrap_or(i64::MAX))
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(AttemptError::from_sql)?;
|
||||
|
||||
sqlx::query(
|
||||
"update execution_admission_controllers
|
||||
set cursor_agent = $2,
|
||||
cursor_agent_credit = $3,
|
||||
cursor_tool = $4,
|
||||
cursor_tool_credit = $5,
|
||||
updated_at = now()
|
||||
where workspace_id = $1",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(selection.cursor.agent.as_deref())
|
||||
.bind(i32::try_from(selection.cursor.agent_credit).unwrap_or_default())
|
||||
.bind(selection.cursor.tool.as_deref())
|
||||
.bind(i32::try_from(selection.cursor.tool_credit).unwrap_or_default())
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(AttemptError::from_sql)?;
|
||||
|
||||
Ok((Some(head.task_id), selection.cursor))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) enum AttemptError {
|
||||
/// Lock or statement timeout: the transaction made no decision and the waiter retries.
|
||||
Contended,
|
||||
|
||||
Reference in new issue
Block a user