feat(epic4): продолжение ожидающей Task после ввода (Story 4.5)
CI / UI Checks (pull_request) Successful in 8s
CI / Rust Checks (pull_request) Successful in 21m42s
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
CI / UI Checks (pull_request) Successful in 8s
CI / Rust Checks (pull_request) Successful in 21m42s
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
Durable worker приостанавливает Task как input_required до dispatch, если закреплённая схема требует отсутствующее поле; authorized schema-validated update атомарно и с аудитом возобновляет тот же Task ровно один раз. Replay/conflict/TTL безопасны, ожидание удерживает admission permit. Additive schema v30: task_input_requests, fingerprint/version, TTL-индекс.
This commit is contained in:
1 parent
d80eda7329
commit
90e5357a08
35 files changed
+3243
-91
No files matched your search
@@ -6,6 +6,7 @@ mod artifact_cleanup_indexes_v13;
|
||||
mod artifact_metadata_v12;
|
||||
mod authority;
|
||||
mod baseline_v1;
|
||||
mod durable_task_input_v30;
|
||||
mod durable_tasks_v25;
|
||||
mod durable_tasks_v26;
|
||||
mod durable_tasks_v27;
|
||||
@@ -47,6 +48,7 @@ mod schema_guard_v26;
|
||||
mod schema_guard_v27;
|
||||
mod schema_guard_v28;
|
||||
mod schema_guard_v29;
|
||||
mod schema_guard_v30;
|
||||
mod schema_guard_v7;
|
||||
mod schema_guard_v8;
|
||||
mod schema_guard_v9;
|
||||
|
||||
@@ -4,6 +4,7 @@ use super::agent_resource_bindings_v18;
|
||||
use super::approval_side_effects_v10;
|
||||
use super::artifact_cleanup_indexes_v13;
|
||||
use super::artifact_metadata_v12;
|
||||
use super::durable_task_input_v30;
|
||||
use super::durable_tasks_v25;
|
||||
use super::durable_tasks_v26;
|
||||
use super::durable_tasks_v27;
|
||||
@@ -45,10 +46,10 @@ use preflight::*;
|
||||
use contract::baseline_source_digest;
|
||||
use contract::validate_descriptors;
|
||||
const MIGRATION_LOCK_ID: i64 = 0x4352_414E_4B4D_4947;
|
||||
const CURRENT_VERSION: i64 = 29;
|
||||
const CURRENT_VERSION: i64 = 30;
|
||||
const IMPLEMENTED_VERSIONS: &[i64] = &[
|
||||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
|
||||
27, 28, 29,
|
||||
27, 28, 29, 30,
|
||||
];
|
||||
const BASELINE_SOURCE_SHA256: &str =
|
||||
"eb1656fc5b4b5be9ee390d237d1d58e4b2274ae5ba9b7ba06a2f3f860dfda675";
|
||||
@@ -373,6 +374,12 @@ impl MigrationAuthority {
|
||||
durable_tasks_v29::SOURCE_SHA256,
|
||||
28,
|
||||
),
|
||||
expand_descriptor(
|
||||
30,
|
||||
durable_task_input_v30::NAME,
|
||||
durable_task_input_v30::SOURCE_SHA256,
|
||||
29,
|
||||
),
|
||||
]
|
||||
}
|
||||
pub fn validate_sequence() -> Result<(), MigrationError> {
|
||||
@@ -550,6 +557,9 @@ impl MigrationAuthority {
|
||||
if from < 29 {
|
||||
durable_tasks_v29::apply(&mut transaction, &Self::sequence()[28]).await?;
|
||||
}
|
||||
if from < 30 {
|
||||
durable_task_input_v30::apply(&mut transaction, &Self::sequence()[29]).await?;
|
||||
}
|
||||
match inspect(&mut transaction).await? {
|
||||
MigrationPreflight::Current {
|
||||
version: CURRENT_VERSION,
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
use sqlx::{Postgres, Transaction, query};
|
||||
|
||||
use super::authority::{MigrationDescriptor, MigrationError};
|
||||
|
||||
pub(super) const NAME: &str = "durable-task-input-v30";
|
||||
pub(super) const SOURCE: &str = include_str!("durable_task_input_v30.sql");
|
||||
pub(super) const SOURCE_SHA256: &str =
|
||||
"84a51f712fd0bc439acba2ab3849232777c29e3b181586bbb4b06fd129843a38";
|
||||
|
||||
pub(super) async fn apply(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
descriptor: &MigrationDescriptor,
|
||||
) -> Result<(), MigrationError> {
|
||||
sqlx::raw_sql(SOURCE)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.durable_task_input_v30",
|
||||
Some(30),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
query(
|
||||
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
|
||||
values ($1, $2, $3, $4, $5)",
|
||||
)
|
||||
.bind(descriptor.version)
|
||||
.bind(descriptor.name)
|
||||
.bind(&descriptor.checksum)
|
||||
.bind(descriptor.phase)
|
||||
.bind(descriptor.compatibility)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.durable_task_input_v30",
|
||||
Some(30),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
-- V30: continuation through validated input (Story 4.5).
|
||||
alter table tasks add column if not exists effective_input_fingerprint text;
|
||||
update tasks set effective_input_fingerprint = input_fingerprint where effective_input_fingerprint is null;
|
||||
alter table tasks alter column effective_input_fingerprint set not null;
|
||||
alter table tasks add constraint tasks_effective_input_fingerprint_check check (
|
||||
length(effective_input_fingerprint) = 64 and effective_input_fingerprint ~ '^[0-9a-f]{64}$'
|
||||
);
|
||||
|
||||
create table if not exists task_input_requests (
|
||||
task_id uuid primary key references tasks (task_id) on delete cascade,
|
||||
wait_id text not null,
|
||||
expected_version integer not null,
|
||||
schema_revision integer not null,
|
||||
schema_format_version integer not null,
|
||||
fingerprint_format_version integer not null,
|
||||
schema_snapshot jsonb not null,
|
||||
projected_schema jsonb not null,
|
||||
prompt_code text not null,
|
||||
missing_fields jsonb not null default '[]'::jsonb,
|
||||
expires_at timestamptz not null,
|
||||
created_at timestamptz not null default now(),
|
||||
accepted_at timestamptz,
|
||||
update_key_digest text,
|
||||
canonical_fingerprint text,
|
||||
effective_input_fingerprint text,
|
||||
committed_state text,
|
||||
committed_version integer,
|
||||
constraint task_input_requests_wait_unique unique (wait_id),
|
||||
constraint task_input_requests_prompt_check check (octet_length(prompt_code) between 1 and 64),
|
||||
constraint task_input_requests_receipt_check check (
|
||||
(accepted_at is null and update_key_digest is null and canonical_fingerprint is null
|
||||
and effective_input_fingerprint is null and committed_state is null and committed_version is null)
|
||||
or (accepted_at is not null and update_key_digest is not null and canonical_fingerprint is not null
|
||||
and effective_input_fingerprint is not null and committed_state is not null and committed_version is not null)
|
||||
)
|
||||
);
|
||||
-- Not unique on purpose: several waiting Tasks may share one absolute TTL value (the same pinned
|
||||
-- policy deadline), and an expired/cancelled wait keeps its row. Per-Task uniqueness comes from the
|
||||
-- primary key and task_input_requests_wait_unique.
|
||||
create index if not exists task_input_requests_active_ttl_idx
|
||||
on task_input_requests (expires_at) where accepted_at is null;
|
||||
|
||||
create table if not exists task_input_audit (
|
||||
id bigint generated always as identity primary key,
|
||||
task_id uuid not null references tasks (task_id) on delete cascade,
|
||||
wait_id text not null,
|
||||
event text not null,
|
||||
from_state text,
|
||||
to_state text,
|
||||
from_version integer,
|
||||
to_version integer,
|
||||
actor text,
|
||||
reason_code text,
|
||||
created_at timestamptz not null default now(),
|
||||
constraint task_input_audit_event_check check (event in ('input_required','input_accepted','input_expired')),
|
||||
constraint task_input_audit_actor_check check (actor is null or octet_length(actor) between 1 and 160),
|
||||
constraint task_input_audit_reason_check check (reason_code is null or octet_length(reason_code) between 1 and 64)
|
||||
);
|
||||
create index if not exists task_input_audit_task_idx on task_input_audit (task_id, id);
|
||||
@@ -492,6 +492,9 @@ pub(super) async fn validate_schema_fingerprint(
|
||||
if !super::schema_guard_v29::validate_v29_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
if !super::schema_guard_v30::validate_v30_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
} else if current_version < 26 {
|
||||
super::schema_guard_v25::validate_v25_durable_tasks(connection).await?;
|
||||
if !super::schema_guard_v26::validate_v26_absent(connection).await? {
|
||||
@@ -503,6 +506,9 @@ pub(super) async fn validate_schema_fingerprint(
|
||||
if !super::schema_guard_v29::validate_v29_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
if !super::schema_guard_v30::validate_v30_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
} else if current_version < 27 {
|
||||
super::schema_guard_v26::validate_v26_durable_tasks(connection).await?;
|
||||
if !super::schema_guard_v27::validate_v27_absent(connection).await? {
|
||||
@@ -514,6 +520,9 @@ pub(super) async fn validate_schema_fingerprint(
|
||||
if !super::schema_guard_v29::validate_v29_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
if !super::schema_guard_v30::validate_v30_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
} else if current_version < 28 {
|
||||
super::schema_guard_v26::validate_v26_base_columns(connection).await?;
|
||||
super::schema_guard_v27::validate_v27_durable_tasks(connection).await?;
|
||||
@@ -523,15 +532,27 @@ pub(super) async fn validate_schema_fingerprint(
|
||||
if !super::schema_guard_v29::validate_v29_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
if !super::schema_guard_v30::validate_v30_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
} else if current_version < 29 {
|
||||
super::schema_guard_v26::validate_v26_base_columns(connection).await?;
|
||||
super::schema_guard_v28::validate_v28_durable_tasks(connection).await?;
|
||||
if !super::schema_guard_v29::validate_v29_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
} else {
|
||||
if !super::schema_guard_v30::validate_v30_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
} else if current_version < 30 {
|
||||
super::schema_guard_v26::validate_v26_base_columns(connection).await?;
|
||||
super::schema_guard_v29::validate_v29_durable_attempts(connection).await?;
|
||||
if !super::schema_guard_v30::validate_v30_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
} else {
|
||||
super::schema_guard_v26::validate_v26_base_columns(connection).await?;
|
||||
super::schema_guard_v30::validate_v30_input_continuation(connection).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
//! V30 schema guard: continuation through validated input (Story 4.5).
|
||||
|
||||
use sqlx::{PgConnection, Row, query};
|
||||
|
||||
use super::authority::MigrationError;
|
||||
use super::schema_guard::{column_exists, relation_exists};
|
||||
|
||||
pub(super) async fn validate_v30_absent(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<bool, MigrationError> {
|
||||
if relation_exists(connection, "tasks").await?
|
||||
&& column_exists(connection, "tasks", "effective_input_fingerprint").await?
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
if relation_exists(connection, "task_input_requests").await? {
|
||||
return Ok(false);
|
||||
}
|
||||
if relation_exists(connection, "task_input_audit").await? {
|
||||
return Ok(false);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(super) async fn validate_v30_input_continuation(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<(), MigrationError> {
|
||||
// V30 builds on the applied V29 shape. The exact V29 column count (43) no longer holds once V30
|
||||
// appends its column (44), so the V29-specific columns are re-checked here by name instead of
|
||||
// calling the exact-count V29 guard, which is only valid before V30 is applied.
|
||||
for column in [
|
||||
"platform_api_key_id",
|
||||
"max_attempts",
|
||||
"retry_backoff_step_ms",
|
||||
"next_attempt_at",
|
||||
"cancel_requested_at",
|
||||
"cancel_reason",
|
||||
] {
|
||||
if !column_exists(connection, "tasks", column).await? {
|
||||
return Err(invalid(30, "v30.columns"));
|
||||
}
|
||||
}
|
||||
|
||||
// V30 appends one column to tasks.
|
||||
if !column_exists(connection, "tasks", "effective_input_fingerprint").await? {
|
||||
return Err(invalid(30, "v30.columns"));
|
||||
}
|
||||
let count: i64 = query(
|
||||
"select count(*)::bigint as count from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = $1",
|
||||
)
|
||||
.bind("tasks")
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get("count")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
if count != 44_i64 {
|
||||
return Err(invalid(30, "v30.columns"));
|
||||
}
|
||||
|
||||
// Tables.
|
||||
for table in ["task_input_requests", "task_input_audit"] {
|
||||
if !relation_exists(connection, table).await? {
|
||||
return Err(invalid(30, "v30.tables"));
|
||||
}
|
||||
}
|
||||
|
||||
// task_input_requests columns.
|
||||
for column in [
|
||||
"task_id",
|
||||
"wait_id",
|
||||
"expected_version",
|
||||
"schema_revision",
|
||||
"schema_format_version",
|
||||
"fingerprint_format_version",
|
||||
"schema_snapshot",
|
||||
"projected_schema",
|
||||
"prompt_code",
|
||||
"missing_fields",
|
||||
"expires_at",
|
||||
"created_at",
|
||||
"accepted_at",
|
||||
"update_key_digest",
|
||||
"canonical_fingerprint",
|
||||
"effective_input_fingerprint",
|
||||
"committed_state",
|
||||
"committed_version",
|
||||
] {
|
||||
if !column_exists(connection, "task_input_requests", column).await? {
|
||||
return Err(invalid(30, "v30.task_input_requests"));
|
||||
}
|
||||
}
|
||||
|
||||
// task_input_audit columns.
|
||||
for column in [
|
||||
"id",
|
||||
"task_id",
|
||||
"wait_id",
|
||||
"event",
|
||||
"from_state",
|
||||
"to_state",
|
||||
"from_version",
|
||||
"to_version",
|
||||
"actor",
|
||||
"reason_code",
|
||||
"created_at",
|
||||
] {
|
||||
if !column_exists(connection, "task_input_audit", column).await? {
|
||||
return Err(invalid(30, "v30.task_input_audit"));
|
||||
}
|
||||
}
|
||||
|
||||
// Constraints.
|
||||
for constraint in [
|
||||
"task_input_requests_pkey",
|
||||
"task_input_requests_wait_unique",
|
||||
"task_input_requests_prompt_check",
|
||||
"task_input_requests_receipt_check",
|
||||
"task_input_audit_event_check",
|
||||
"task_input_audit_actor_check",
|
||||
"task_input_audit_reason_check",
|
||||
"tasks_effective_input_fingerprint_check",
|
||||
] {
|
||||
let table = if constraint.starts_with("task_input_audit")
|
||||
|| constraint.starts_with("task_input_audit_")
|
||||
{
|
||||
"task_input_audit"
|
||||
} else if constraint == "tasks_effective_input_fingerprint_check" {
|
||||
"tasks"
|
||||
} else {
|
||||
"task_input_requests"
|
||||
};
|
||||
if !named_constraint_exists(connection, table, constraint).await? {
|
||||
return Err(invalid(30, "v30.constraints"));
|
||||
}
|
||||
}
|
||||
|
||||
// Indexes.
|
||||
for index in [
|
||||
"task_input_requests_active_ttl_idx",
|
||||
"task_input_audit_task_idx",
|
||||
] {
|
||||
let present = query(
|
||||
"select exists (select 1 from pg_catalog.pg_indexes
|
||||
where schemaname = current_schema() and indexname = $1) as present",
|
||||
)
|
||||
.bind(index)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get::<bool, _>("present")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
if !present {
|
||||
return Err(invalid(30, "v30.indexes"));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn invalid(version: i64, stage: &'static str) -> MigrationError {
|
||||
MigrationError::new(
|
||||
"partial_sequence",
|
||||
stage,
|
||||
Some(version),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
}
|
||||
|
||||
// helper
|
||||
async fn named_constraint_exists(
|
||||
connection: &mut PgConnection,
|
||||
table: &str,
|
||||
constraint: &str,
|
||||
) -> Result<bool, MigrationError> {
|
||||
query(
|
||||
"select exists (
|
||||
select 1 from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and t.relname = $1
|
||||
and c.conname = $2
|
||||
) as present",
|
||||
)
|
||||
.bind(table)
|
||||
.bind(constraint)
|
||||
.fetch_one(connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get::<bool, _>("present")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))
|
||||
}
|
||||
@@ -57,12 +57,13 @@ impl PostgresTaskStore {
|
||||
let created_ms: i64 = sqlx::query(
|
||||
"insert into tasks (
|
||||
task_id, workspace_id, owner_kind, owner_id, authorization_scope, operation_id,
|
||||
operation_version, scoped_key, input_fingerprint, request_id, trace_id, traceparent,
|
||||
operation_version, scoped_key, input_fingerprint, effective_input_fingerprint,
|
||||
request_id, trace_id, traceparent,
|
||||
trace_sampled, policy_mode, approval_reference, state, input_envelope,
|
||||
execution_deadline, retain_until, executable_input_ciphertext, executable_input_key_version,
|
||||
executable_input_master_key_epoch, platform_api_key_id, max_attempts, retry_backoff_step_ms
|
||||
) values (
|
||||
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, 'queued', $16,
|
||||
$1, $2, $3, $4, $5, $6, $7, $8, $9, $9, $10, $11, $12, $13, $14, $15, 'queued', $16,
|
||||
to_timestamp($17::double precision / 1000.0),
|
||||
to_timestamp($18::double precision / 1000.0), $19, $20, $21, $22, $23, $24
|
||||
)
|
||||
|
||||
@@ -119,7 +119,9 @@ impl PostgresTaskStore {
|
||||
return Err(TaskError::NotFound);
|
||||
};
|
||||
let record = record_from_row(&row)?;
|
||||
if record.input_fingerprint != request.input_fingerprint {
|
||||
// The checkpoint must bind the payload this attempt actually executes: after a committed
|
||||
// input continuation that is the effective fingerprint, not the unchanged acceptance one.
|
||||
if record.effective_input_fingerprint != request.input_fingerprint {
|
||||
transaction.rollback().await.ok();
|
||||
return Err(TaskError::FingerprintConflict);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,659 @@
|
||||
//! Input-continuation half of the PostgreSQL Task store (Story 4.5, FR-25).
|
||||
//!
|
||||
//! One transaction owns each transition: suspend (`working` -> `input_required`), the committed
|
||||
//! answer (`input_required` -> `working`) and the TTL expiry (`input_required` -> `failed`). Authority,
|
||||
//! generation, TTL and receipt checks run under the same Task row lock, so a revocation, a competing
|
||||
//! answer, a sweeper or a cancellation has exactly one winner and never a duplicated side effect.
|
||||
//!
|
||||
//! Raw input never enters a request, receipt, audit row or error text: the validated payload is
|
||||
//! encrypted by the runtime service before this module sees it.
|
||||
|
||||
use crank_core::{
|
||||
TaskAccess, TaskError, TaskInputRequest, TaskInputStore, TaskInputUpdateOutcome,
|
||||
TaskInputUpdateRequest, TaskRecord, TaskState,
|
||||
};
|
||||
use sqlx::{Postgres, Row, Transaction};
|
||||
|
||||
use super::{PostgresTaskStore, TASK_PROJECTION, record_from_row};
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl TaskInputStore for PostgresTaskStore {
|
||||
async fn suspend_for_input(
|
||||
&self,
|
||||
lease: &crank_core::TaskLease,
|
||||
request: TaskInputRequest,
|
||||
) -> Result<TaskRecord, TaskError> {
|
||||
self.suspend_input_locked(lease, request).await
|
||||
}
|
||||
|
||||
async fn input_request(
|
||||
&self,
|
||||
access: &TaskAccess,
|
||||
task_id: crank_core::TaskId,
|
||||
) -> Result<TaskInputRequest, TaskError> {
|
||||
self.read_input_request(access, task_id).await
|
||||
}
|
||||
|
||||
async fn read_executable_input_for_update(
|
||||
&self,
|
||||
access: &TaskAccess,
|
||||
task_id: crank_core::TaskId,
|
||||
) -> Result<(String, String, i64), TaskError> {
|
||||
self.read_binding_for_update(access, task_id).await
|
||||
}
|
||||
|
||||
async fn apply_input(
|
||||
&self,
|
||||
request: TaskInputUpdateRequest,
|
||||
) -> Result<TaskInputUpdateOutcome, TaskError> {
|
||||
self.apply_input_locked(request).await
|
||||
}
|
||||
|
||||
async fn expire_input_waits(&self, batch: u32) -> Result<u64, TaskError> {
|
||||
self.expire_input_waits_locked(batch).await
|
||||
}
|
||||
}
|
||||
|
||||
impl PostgresTaskStore {
|
||||
/// One transactional suspend of a leased Task before any dispatch checkpoint.
|
||||
pub(super) async fn suspend_input_locked(
|
||||
&self,
|
||||
lease: &crank_core::TaskLease,
|
||||
request: TaskInputRequest,
|
||||
) -> Result<TaskRecord, TaskError> {
|
||||
request.validate()?;
|
||||
if request.expected_version != lease.record.version.saturating_add(1) {
|
||||
return Err(TaskError::StateConflict);
|
||||
}
|
||||
let mut transaction = self.start().await?;
|
||||
let row = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"select {TASK_PROJECTION} from tasks where task_id = $1 for update"
|
||||
)))
|
||||
.bind(lease.record.task_id.as_uuid())
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
let Some(row) = row else {
|
||||
transaction.rollback().await.ok();
|
||||
return Err(TaskError::NotFound);
|
||||
};
|
||||
let record = record_from_row(&row)?;
|
||||
let current = record.state == TaskState::Working
|
||||
&& record.lease_owner.as_deref() == Some(lease.owner.as_str())
|
||||
&& record.fence == lease.fence
|
||||
&& record.version == lease.record.version
|
||||
&& record.current_attempt_id.is_none()
|
||||
&& record.attempts == 0
|
||||
&& record.cancel_requested_at_unix_ms.is_none()
|
||||
&& record
|
||||
.lease_until_unix_ms
|
||||
.is_some_and(|until| until > crank_core::current_unix_ms())
|
||||
&& record.pins.execution_deadline_unix_ms > crank_core::current_unix_ms();
|
||||
// A generation that already dispatched may not be suspended: that would hide a possible side
|
||||
// effect behind an apparent "waiting for input".
|
||||
if !current {
|
||||
transaction.rollback().await.ok();
|
||||
return Err(TaskError::StateConflict);
|
||||
}
|
||||
if request.expires_at_unix_ms > record.pins.execution_deadline_unix_ms {
|
||||
transaction.rollback().await.ok();
|
||||
return Err(TaskError::invalid(
|
||||
"task input TTL exceeds the execution deadline",
|
||||
));
|
||||
}
|
||||
|
||||
sqlx::query(
|
||||
"insert into task_input_requests (
|
||||
task_id, wait_id, expected_version, schema_revision, schema_format_version,
|
||||
fingerprint_format_version, schema_snapshot, projected_schema, prompt_code,
|
||||
missing_fields, expires_at
|
||||
) values (
|
||||
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10,
|
||||
to_timestamp($11::double precision / 1000.0)
|
||||
)",
|
||||
)
|
||||
.bind(lease.record.task_id.as_uuid())
|
||||
.bind(&request.wait_id)
|
||||
.bind(i32::try_from(request.expected_version).unwrap_or(i32::MAX))
|
||||
.bind(i32::try_from(request.schema_revision).unwrap_or(i32::MAX))
|
||||
.bind(i32::try_from(request.schema_format_version).unwrap_or(i32::MAX))
|
||||
.bind(i32::try_from(request.fingerprint_format_version).unwrap_or(i32::MAX))
|
||||
.bind(request.schema_snapshot.clone())
|
||||
.bind(request.projected_schema.clone())
|
||||
.bind(&request.prompt_code)
|
||||
.bind(serde_json::Value::Array(
|
||||
request
|
||||
.missing_fields
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(serde_json::Value::String)
|
||||
.collect(),
|
||||
))
|
||||
.bind(request.expires_at_unix_ms)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| {
|
||||
match error
|
||||
.as_database_error()
|
||||
.and_then(|db| db.code())
|
||||
.as_deref()
|
||||
{
|
||||
Some("23505") => TaskError::StateConflict,
|
||||
_ => Self::unavailable(error),
|
||||
}
|
||||
})?;
|
||||
|
||||
let row = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"update tasks
|
||||
set state = 'input_required',
|
||||
lease_owner = null,
|
||||
lease_until = null,
|
||||
version = version + 1,
|
||||
updated_at = now()
|
||||
where task_id = $1 and state = 'working' and version = $2
|
||||
and lease_owner = $3 and fence = $4 and current_attempt_id is null
|
||||
and lease_until > clock_timestamp()
|
||||
returning {TASK_PROJECTION}"
|
||||
)))
|
||||
.bind(lease.record.task_id.as_uuid())
|
||||
.bind(i64::from(record.version))
|
||||
.bind(&lease.owner)
|
||||
.bind(i64::try_from(lease.fence).unwrap_or_default())
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
let Some(row) = row else {
|
||||
transaction.rollback().await.ok();
|
||||
return Err(TaskError::StateConflict);
|
||||
};
|
||||
let suspended = record_from_row(&row)?;
|
||||
insert_audit(
|
||||
&mut transaction,
|
||||
lease.record.task_id,
|
||||
&request.wait_id,
|
||||
"input_required",
|
||||
TaskState::Working,
|
||||
TaskState::InputRequired,
|
||||
record.version,
|
||||
suspended.version,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
transaction.commit().await.map_err(Self::unavailable)?;
|
||||
Ok(suspended)
|
||||
}
|
||||
|
||||
/// Owner-scoped read of the durable request; a foreign Task is one opaque not-found.
|
||||
pub(super) async fn read_input_request(
|
||||
&self,
|
||||
access: &TaskAccess,
|
||||
task_id: crank_core::TaskId,
|
||||
) -> Result<TaskInputRequest, TaskError> {
|
||||
access.validate()?;
|
||||
let row = sqlx::query(
|
||||
"select r.wait_id, r.expected_version, r.schema_revision, r.schema_format_version,
|
||||
r.fingerprint_format_version, r.schema_snapshot, r.projected_schema,
|
||||
r.prompt_code, r.missing_fields,
|
||||
(extract(epoch from r.expires_at) * 1000)::bigint as expires_at_ms
|
||||
from task_input_requests r
|
||||
join tasks t on t.task_id = r.task_id
|
||||
where r.task_id = $1 and t.workspace_id = $2 and t.owner_kind = $3
|
||||
and t.owner_id = $4 and t.authorization_scope = $5",
|
||||
)
|
||||
.bind(task_id.as_uuid())
|
||||
.bind(&access.workspace_id)
|
||||
.bind(access.owner_kind.as_str())
|
||||
.bind(&access.owner_id)
|
||||
.bind(&access.authorization_scope)
|
||||
.fetch_optional(&self.pool)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
let Some(row) = row else {
|
||||
return Err(TaskError::NotFound);
|
||||
};
|
||||
let missing_fields: Vec<String> = serde_json::from_value(
|
||||
row.try_get::<serde_json::Value, _>("missing_fields")
|
||||
.map_err(Self::unavailable)?,
|
||||
)
|
||||
.map_err(|_| TaskError::unavailable("stored input request metadata is invalid"))?;
|
||||
Ok(TaskInputRequest {
|
||||
wait_id: row.try_get("wait_id").map_err(Self::unavailable)?,
|
||||
expected_version: u32::try_from(
|
||||
row.try_get::<i32, _>("expected_version")
|
||||
.map_err(Self::unavailable)?,
|
||||
)
|
||||
.unwrap_or_default(),
|
||||
schema_revision: u32::try_from(
|
||||
row.try_get::<i32, _>("schema_revision")
|
||||
.map_err(Self::unavailable)?,
|
||||
)
|
||||
.unwrap_or_default(),
|
||||
schema_format_version: u32::try_from(
|
||||
row.try_get::<i32, _>("schema_format_version")
|
||||
.map_err(Self::unavailable)?,
|
||||
)
|
||||
.unwrap_or_default(),
|
||||
schema_snapshot: row.try_get("schema_snapshot").map_err(Self::unavailable)?,
|
||||
projected_schema: row.try_get("projected_schema").map_err(Self::unavailable)?,
|
||||
prompt_code: row.try_get("prompt_code").map_err(Self::unavailable)?,
|
||||
missing_fields,
|
||||
expires_at_unix_ms: row.try_get("expires_at_ms").map_err(Self::unavailable)?,
|
||||
fingerprint_format_version: u32::try_from(
|
||||
row.try_get::<i32, _>("fingerprint_format_version")
|
||||
.map_err(Self::unavailable)?,
|
||||
)
|
||||
.unwrap_or_default(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Owner-scoped read of the binding a continuation may extend. Never lease-authorized.
|
||||
///
|
||||
/// Deliberately not filtered by lifecycle state: an identical replay of an already committed
|
||||
/// answer (including after completion or TTL expiry) must reach the receipt lookup, which is the
|
||||
/// single authority for that outcome.
|
||||
pub(super) async fn read_binding_for_update(
|
||||
&self,
|
||||
access: &TaskAccess,
|
||||
task_id: crank_core::TaskId,
|
||||
) -> Result<(String, String, i64), TaskError> {
|
||||
access.validate()?;
|
||||
let row = sqlx::query(
|
||||
"select executable_input_ciphertext, executable_input_key_version,
|
||||
executable_input_master_key_epoch
|
||||
from tasks
|
||||
where task_id = $1 and workspace_id = $2 and owner_kind = $3
|
||||
and owner_id = $4 and authorization_scope = $5",
|
||||
)
|
||||
.bind(task_id.as_uuid())
|
||||
.bind(&access.workspace_id)
|
||||
.bind(access.owner_kind.as_str())
|
||||
.bind(&access.owner_id)
|
||||
.bind(&access.authorization_scope)
|
||||
.fetch_optional(&self.pool)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
let Some(row) = row else {
|
||||
return Err(TaskError::NotFound);
|
||||
};
|
||||
let ciphertext: Option<String> = row
|
||||
.try_get("executable_input_ciphertext")
|
||||
.map_err(Self::unavailable)?;
|
||||
let key_version: Option<String> = row
|
||||
.try_get("executable_input_key_version")
|
||||
.map_err(Self::unavailable)?;
|
||||
let epoch: Option<i64> = row
|
||||
.try_get("executable_input_master_key_epoch")
|
||||
.map_err(Self::unavailable)?;
|
||||
match (ciphertext, key_version, epoch) {
|
||||
(Some(ciphertext), Some(key_version), Some(epoch)) if !ciphertext.is_empty() => {
|
||||
Ok((ciphertext, key_version, epoch))
|
||||
}
|
||||
_ => Err(TaskError::NotFound),
|
||||
}
|
||||
}
|
||||
|
||||
/// One transactional answer application: authority, receipt, generation, TTL and CAS.
|
||||
pub(super) async fn apply_input_locked(
|
||||
&self,
|
||||
request: TaskInputUpdateRequest,
|
||||
) -> Result<TaskInputUpdateOutcome, TaskError> {
|
||||
request.validate()?;
|
||||
let access = &request.access;
|
||||
let mut transaction = self.start().await?;
|
||||
super::super::master_key::ensure_no_active_master_key_rotation(&mut transaction)
|
||||
.await
|
||||
.map_err(|error| match error {
|
||||
crate::RegistryError::Storage(_) => TaskError::unavailable(error.to_string()),
|
||||
_ => TaskError::StateConflict,
|
||||
})?;
|
||||
super::super::master_key::ensure_active_master_key_epoch(
|
||||
&mut transaction,
|
||||
request.executable_input_master_key_epoch,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| match error {
|
||||
crate::RegistryError::Storage(_) => TaskError::unavailable(error.to_string()),
|
||||
_ => TaskError::StateConflict,
|
||||
})?;
|
||||
|
||||
// Authority is revalidated inside this transaction, before any receipt lookup and under the
|
||||
// same lock order: master key check, platform key share lock, Task row lock.
|
||||
let key_row = sqlx::query(
|
||||
"select k.id from platform_api_keys k
|
||||
join tasks t on t.platform_api_key_id = k.id
|
||||
where t.task_id = $1 and t.owner_kind = 'agent'
|
||||
and k.workspace_id = $2 and k.agent_id = $3
|
||||
and k.key_kind = 'mcp_client' and k.status = 'active'
|
||||
and (k.expires_at is null or k.expires_at > clock_timestamp())
|
||||
and (k.scopes_json ? 'write' or k.scopes_json ? 'deploy')
|
||||
for share of k",
|
||||
)
|
||||
.bind(request.task_id.as_uuid())
|
||||
.bind(&access.workspace_id)
|
||||
.bind(&access.owner_id)
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
if key_row.is_none() {
|
||||
transaction.rollback().await.ok();
|
||||
// A revoked key, a foreign scope and an absent Task share one opaque answer.
|
||||
return Err(TaskError::NotFound);
|
||||
}
|
||||
|
||||
let row = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"select {TASK_PROJECTION} from tasks
|
||||
where task_id = $1 and workspace_id = $2 and owner_kind = $3
|
||||
and owner_id = $4 and authorization_scope = $5
|
||||
for update"
|
||||
)))
|
||||
.bind(request.task_id.as_uuid())
|
||||
.bind(&access.workspace_id)
|
||||
.bind(access.owner_kind.as_str())
|
||||
.bind(&access.owner_id)
|
||||
.bind(&access.authorization_scope)
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
let Some(row) = row else {
|
||||
transaction.rollback().await.ok();
|
||||
return Err(TaskError::NotFound);
|
||||
};
|
||||
let record = record_from_row(&row)?;
|
||||
|
||||
// Receipt lookup precedes the generation and TTL checks: an authorized identical replay keeps
|
||||
// returning the committed outcome even after completion, failure or TTL expiry.
|
||||
let receipt = sqlx::query(
|
||||
"select wait_id, update_key_digest, canonical_fingerprint, committed_state,
|
||||
committed_version
|
||||
from task_input_requests where task_id = $1 and accepted_at is not null",
|
||||
)
|
||||
.bind(request.task_id.as_uuid())
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
if let Some(receipt) = receipt {
|
||||
let wait_id: String = receipt.try_get("wait_id").map_err(Self::unavailable)?;
|
||||
if wait_id != request.wait_id {
|
||||
transaction.rollback().await.ok();
|
||||
return Err(TaskError::StateConflict);
|
||||
}
|
||||
let stored_key: String = receipt
|
||||
.try_get("update_key_digest")
|
||||
.map_err(Self::unavailable)?;
|
||||
if stored_key != request.update_key_digest {
|
||||
transaction.rollback().await.ok();
|
||||
return Err(TaskError::StateConflict);
|
||||
}
|
||||
let stored_fingerprint: String = receipt
|
||||
.try_get("canonical_fingerprint")
|
||||
.map_err(Self::unavailable)?;
|
||||
if stored_fingerprint != request.canonical_fingerprint {
|
||||
transaction.rollback().await.ok();
|
||||
return Err(TaskError::FingerprintConflict);
|
||||
}
|
||||
let state: String = receipt
|
||||
.try_get("committed_state")
|
||||
.map_err(Self::unavailable)?;
|
||||
let version: i32 = receipt
|
||||
.try_get("committed_version")
|
||||
.map_err(Self::unavailable)?;
|
||||
transaction.commit().await.map_err(Self::unavailable)?;
|
||||
return Ok(TaskInputUpdateOutcome {
|
||||
task_id: request.task_id,
|
||||
wait_id,
|
||||
state: TaskState::parse(&state)?,
|
||||
version: u32::try_from(version).unwrap_or_default(),
|
||||
replayed: true,
|
||||
});
|
||||
}
|
||||
|
||||
let pending = sqlx::query(
|
||||
"select wait_id, expected_version,
|
||||
(extract(epoch from expires_at) * 1000)::bigint as expires_at_ms,
|
||||
(extract(epoch from clock_timestamp()) * 1000)::bigint as now_ms
|
||||
from task_input_requests where task_id = $1 and accepted_at is null",
|
||||
)
|
||||
.bind(request.task_id.as_uuid())
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
let Some(pending) = pending else {
|
||||
transaction.rollback().await.ok();
|
||||
return Err(TaskError::StateConflict);
|
||||
};
|
||||
let wait_id: String = pending.try_get("wait_id").map_err(Self::unavailable)?;
|
||||
let expected_version: i32 = pending
|
||||
.try_get("expected_version")
|
||||
.map_err(Self::unavailable)?;
|
||||
let expires_at_ms: i64 = pending
|
||||
.try_get("expires_at_ms")
|
||||
.map_err(Self::unavailable)?;
|
||||
// PostgreSQL clock, read after the row lock was taken: never a client timestamp.
|
||||
let now_ms: i64 = pending.try_get("now_ms").map_err(Self::unavailable)?;
|
||||
if wait_id != request.wait_id
|
||||
|| u32::try_from(expected_version).unwrap_or_default() != request.expected_version
|
||||
|| record.version != request.expected_version
|
||||
|| record.state != TaskState::InputRequired
|
||||
{
|
||||
transaction.rollback().await.ok();
|
||||
return Err(TaskError::StateConflict);
|
||||
}
|
||||
if record.cancel_requested_at_unix_ms.is_some() {
|
||||
transaction.rollback().await.ok();
|
||||
return Err(TaskError::StateConflict);
|
||||
}
|
||||
if now_ms >= expires_at_ms {
|
||||
// The same transactional helper the sweeper uses: the Task ends failed with an audit
|
||||
// reason and no dispatch. The update never revives it.
|
||||
expire_locked(&mut transaction, &record, &wait_id, now_ms).await?;
|
||||
transaction.commit().await.map_err(Self::unavailable)?;
|
||||
return Err(TaskError::InputExpired);
|
||||
}
|
||||
|
||||
let row = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"update tasks
|
||||
set state = 'working',
|
||||
effective_input_fingerprint = $1,
|
||||
executable_input_ciphertext = $2,
|
||||
executable_input_key_version = $3,
|
||||
executable_input_master_key_epoch = $4,
|
||||
lease_owner = null,
|
||||
lease_until = null,
|
||||
version = version + 1,
|
||||
updated_at = now()
|
||||
where task_id = $5 and state = 'input_required' and version = $6
|
||||
returning {TASK_PROJECTION}"
|
||||
)))
|
||||
.bind(&request.effective_input_fingerprint)
|
||||
.bind(&request.executable_input_ciphertext)
|
||||
.bind(&request.executable_input_key_version)
|
||||
.bind(request.executable_input_master_key_epoch)
|
||||
.bind(request.task_id.as_uuid())
|
||||
.bind(i64::from(record.version))
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
let Some(row) = row else {
|
||||
transaction.rollback().await.ok();
|
||||
return Err(TaskError::StateConflict);
|
||||
};
|
||||
let accepted = record_from_row(&row)?;
|
||||
let updated = sqlx::query(
|
||||
"update task_input_requests
|
||||
set accepted_at = now(),
|
||||
update_key_digest = $1,
|
||||
canonical_fingerprint = $2,
|
||||
effective_input_fingerprint = $3,
|
||||
committed_state = 'working',
|
||||
committed_version = $4
|
||||
where task_id = $5 and wait_id = $6 and accepted_at is null",
|
||||
)
|
||||
.bind(&request.update_key_digest)
|
||||
.bind(&request.canonical_fingerprint)
|
||||
.bind(&request.effective_input_fingerprint)
|
||||
.bind(i64::from(accepted.version))
|
||||
.bind(request.task_id.as_uuid())
|
||||
.bind(&request.wait_id)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
if updated.rows_affected() != 1 {
|
||||
transaction.rollback().await.ok();
|
||||
return Err(TaskError::StateConflict);
|
||||
}
|
||||
insert_audit(
|
||||
&mut transaction,
|
||||
request.task_id,
|
||||
&request.wait_id,
|
||||
"input_accepted",
|
||||
TaskState::InputRequired,
|
||||
TaskState::Working,
|
||||
record.version,
|
||||
accepted.version,
|
||||
Some(access.owner_id.as_str()),
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
transaction.commit().await.map_err(Self::unavailable)?;
|
||||
Ok(TaskInputUpdateOutcome {
|
||||
task_id: request.task_id,
|
||||
wait_id: request.wait_id,
|
||||
state: TaskState::Working,
|
||||
version: accepted.version,
|
||||
replayed: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Bounded TTL sweep, safe to call on every poll while all worker slots are busy.
|
||||
pub(super) async fn expire_input_waits_locked(&self, batch: u32) -> Result<u64, TaskError> {
|
||||
let batch = i64::from(batch.clamp(1, crank_core::TASK_PURGE_BATCH_LIMIT));
|
||||
let mut transaction = self.start().await?;
|
||||
let rows = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"select {TASK_PROJECTION} from tasks t
|
||||
where t.state = 'input_required'
|
||||
and exists (
|
||||
select 1 from task_input_requests r
|
||||
where r.task_id = t.task_id and r.accepted_at is null
|
||||
and r.expires_at <= clock_timestamp()
|
||||
)
|
||||
order by t.task_id
|
||||
limit $1
|
||||
for update of t skip locked"
|
||||
)))
|
||||
.bind(batch)
|
||||
.fetch_all(&mut *transaction)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
let mut expired = 0u64;
|
||||
for row in rows {
|
||||
let record = record_from_row(&row)?;
|
||||
let Some(wait_id) = sqlx::query_scalar::<_, String>(
|
||||
"select wait_id from task_input_requests
|
||||
where task_id = $1 and accepted_at is null and expires_at <= clock_timestamp()",
|
||||
)
|
||||
.bind(record.task_id.as_uuid())
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(Self::unavailable)?
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if expire_locked(
|
||||
&mut transaction,
|
||||
&record,
|
||||
&wait_id,
|
||||
crank_core::current_unix_ms(),
|
||||
)
|
||||
.await?
|
||||
{
|
||||
expired += 1;
|
||||
}
|
||||
}
|
||||
transaction.commit().await.map_err(Self::unavailable)?;
|
||||
Ok(expired)
|
||||
}
|
||||
}
|
||||
|
||||
/// Marks one locked `input_required` Task failed, releases its admission permit and writes the audit
|
||||
/// reason. Returns whether this call performed the transition.
|
||||
async fn expire_locked(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
record: &TaskRecord,
|
||||
wait_id: &str,
|
||||
_now_ms: i64,
|
||||
) -> Result<bool, TaskError> {
|
||||
let row = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"update tasks
|
||||
set state = 'failed',
|
||||
error_envelope = jsonb_build_object('reason', 'input_ttl_expired'),
|
||||
lease_owner = null,
|
||||
lease_until = null,
|
||||
version = version + 1,
|
||||
updated_at = now()
|
||||
where task_id = $1 and state = 'input_required' and version = $2
|
||||
returning {TASK_PROJECTION}"
|
||||
)))
|
||||
.bind(record.task_id.as_uuid())
|
||||
.bind(i64::from(record.version))
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await
|
||||
.map_err(PostgresTaskStore::unavailable)?;
|
||||
let Some(row) = row else {
|
||||
return Ok(false);
|
||||
};
|
||||
let failed = record_from_row(&row)?;
|
||||
sqlx::query("delete from execution_admission_entries where task_id = $1")
|
||||
.bind(record.task_id.as_uuid())
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(PostgresTaskStore::unavailable)?;
|
||||
insert_audit(
|
||||
transaction,
|
||||
record.task_id,
|
||||
wait_id,
|
||||
"input_expired",
|
||||
TaskState::InputRequired,
|
||||
TaskState::Failed,
|
||||
record.version,
|
||||
failed.version,
|
||||
None,
|
||||
Some("input_ttl_expired"),
|
||||
)
|
||||
.await?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn insert_audit(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
task_id: crank_core::TaskId,
|
||||
wait_id: &str,
|
||||
event: &str,
|
||||
from_state: TaskState,
|
||||
to_state: TaskState,
|
||||
from_version: u32,
|
||||
to_version: u32,
|
||||
actor: Option<&str>,
|
||||
reason_code: Option<&str>,
|
||||
) -> Result<(), TaskError> {
|
||||
sqlx::query(
|
||||
"insert into task_input_audit (
|
||||
task_id, wait_id, event, from_state, to_state, from_version, to_version, actor,
|
||||
reason_code
|
||||
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9)",
|
||||
)
|
||||
.bind(task_id.as_uuid())
|
||||
.bind(wait_id)
|
||||
.bind(event)
|
||||
.bind(from_state.as_str())
|
||||
.bind(to_state.as_str())
|
||||
.bind(i32::try_from(from_version).unwrap_or(i32::MAX))
|
||||
.bind(i32::try_from(to_version).unwrap_or(i32::MAX))
|
||||
.bind(actor)
|
||||
.bind(reason_code)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(PostgresTaskStore::unavailable)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -26,9 +26,11 @@ use super::admission::{AdmissionLimits, AttemptError};
|
||||
|
||||
mod acceptance;
|
||||
mod attempts;
|
||||
mod input;
|
||||
|
||||
const TASK_PROJECTION: &str = "task_id, state, workspace_id, owner_kind, owner_id,
|
||||
authorization_scope, platform_api_key_id, operation_id, input_fingerprint, operation_version,
|
||||
authorization_scope, platform_api_key_id, operation_id, input_fingerprint,
|
||||
effective_input_fingerprint, operation_version,
|
||||
policy_mode,
|
||||
approval_reference,
|
||||
request_id, trace_id, traceparent, trace_sampled, input_envelope, progress_envelope,
|
||||
@@ -521,7 +523,49 @@ and lease_owner is null
|
||||
transaction.commit().await.map_err(Self::unavailable)?;
|
||||
|
||||
let mut leases = Vec::new();
|
||||
for _ in 0..batch {
|
||||
// Continuation claim: after a committed answer the Task is `working` without a lease and still
|
||||
// owns its executing admission permit. It is handed to exactly one new fence here, without a
|
||||
// second admission grant, so waiting capacity is never double-counted.
|
||||
let mut transaction = self.start().await?;
|
||||
let resumed = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"update tasks
|
||||
set lease_owner = $1,
|
||||
lease_until = clock_timestamp() + ($2::bigint || ' milliseconds')::interval,
|
||||
fence = fence + 1,
|
||||
updated_at = now()
|
||||
where task_id in (
|
||||
select t.task_id
|
||||
from tasks t
|
||||
join task_input_requests r on r.task_id = t.task_id and r.accepted_at is not null
|
||||
join execution_admission_entries e
|
||||
on e.task_id = t.task_id and e.state = 'executing'
|
||||
where t.state = 'working' and t.lease_owner is null
|
||||
and t.current_attempt_id is null
|
||||
order by t.task_id
|
||||
limit $3
|
||||
for update of t skip locked
|
||||
)
|
||||
returning {TASK_PROJECTION}"
|
||||
)))
|
||||
.bind(owner)
|
||||
.bind(lease_ms)
|
||||
.bind(i64::try_from(batch.clamp(1, 64)).unwrap_or(64))
|
||||
.fetch_all(&mut *transaction)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
transaction.commit().await.map_err(Self::unavailable)?;
|
||||
for row in resumed {
|
||||
let record = record_from_row(&row).map_err(Self::unavailable)?;
|
||||
leases.push(TaskLease {
|
||||
owner: owner.to_owned(),
|
||||
fence: record.fence,
|
||||
lease_until: record.lease_until_unix_ms.unwrap_or_default(),
|
||||
record,
|
||||
});
|
||||
}
|
||||
|
||||
let remaining = batch.saturating_sub(leases.len());
|
||||
for _ in 0..remaining {
|
||||
let mut transaction = self.start().await?;
|
||||
let workspace_cursor =
|
||||
match super::admission::lock_admission_in_tx(&mut transaction, "*").await {
|
||||
@@ -840,6 +884,9 @@ fn record_from_row(row: &sqlx::postgres::PgRow) -> Result<TaskRecord, TaskError>
|
||||
.map(PlatformApiKeyId::new),
|
||||
operation_id: row.try_get("operation_id").map_err(unavailable_row)?,
|
||||
input_fingerprint: row.try_get("input_fingerprint").map_err(unavailable_row)?,
|
||||
effective_input_fingerprint: row
|
||||
.try_get("effective_input_fingerprint")
|
||||
.map_err(unavailable_row)?,
|
||||
pins: TaskPins {
|
||||
operation_version: u32::try_from(
|
||||
row.try_get::<i32, _>("operation_version")
|
||||
|
||||
Reference in new issue
Block a user