blob: b8a95352d21afe441ea2aa04f269fde97fba0825 [file]
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
//! Agent-owned SQL. All mutations execute synchronously in the Root writer transaction.
#[path = "sql_compaction.rs"]
pub(crate) mod compaction;
#[path = "sql_model_evidence.rs"]
mod model_evidence;
use crate::{
fold::{self, Approval, Attempt, Blocker, RunView, Tool, Wait},
store::{Admission, Change, Commit, ContentBlob, Head, Mode, invalid},
};
use maka_agent_facts::{durable::*, model::ModelPart};
use maka_event_log::{StoreError, content};
pub(crate) use model_evidence::validate_envelope as validate_private_partial_envelope;
use rusqlite::{Connection, OptionalExtension, params};
use serde::{Serialize, de::DeserializeOwned};
use std::{
collections::{BTreeSet, HashMap, VecDeque},
hash::Hash,
sync::{Arc, Mutex, OnceLock},
};
// Process-wide shared bounded caches across writer + SQLite reader threads so
// identical immutable RunSpec / CompositionSurface blobs are deserialized once
// and total cross-thread memory stays strictly bounded.
const SPEC_CACHE_CAPACITY: usize = 512;
const SURFACE_CACHE_CAPACITY: usize = 128;
struct BoundedCache<K, V> {
entries: HashMap<K, V>,
order: VecDeque<K>,
capacity: usize,
}
impl<K: Eq + Hash + Clone, V> BoundedCache<K, V> {
fn new(capacity: usize) -> Self {
Self {
entries: HashMap::new(),
order: VecDeque::new(),
capacity,
}
}
fn get(&self, key: &K) -> Option<&V> {
self.entries.get(key)
}
fn insert(&mut self, key: K, value: V) {
if let Some(existing) = self.entries.get_mut(&key) {
*existing = value;
return;
}
while self.entries.len() >= self.capacity {
let Some(oldest) = self.order.pop_front() else {
break;
};
self.entries.remove(&oldest);
}
self.order.push_back(key.clone());
self.entries.insert(key, value);
}
}
type SharedBlobCache<V> = Mutex<BoundedCache<(String, u64), Arc<V>>>;
fn spec_cache() -> &'static SharedBlobCache<RunSpec> {
static CACHE: OnceLock<SharedBlobCache<RunSpec>> = OnceLock::new();
CACHE.get_or_init(|| Mutex::new(BoundedCache::new(SPEC_CACHE_CAPACITY)))
}
fn surface_cache() -> &'static SharedBlobCache<maka_agent_facts::composition::CompositionSurface> {
static CACHE: OnceLock<SharedBlobCache<maka_agent_facts::composition::CompositionSurface>> =
OnceLock::new();
CACHE.get_or_init(|| Mutex::new(BoundedCache::new(SURFACE_CACHE_CAPACITY)))
}
pub(crate) const HEADER_SCHEMA_VERSION: u32 = 2;
const AUTHORITY_BLOCKED: &str = "EXISTS(SELECT 1 FROM agent_blockers authority WHERE authority.run=r.run AND authority.pending=1
AND json_extract(authority.body,'$.decision') IS NULL AND json_extract(authority.body,'$.resolvedBy') IS NULL
AND json_extract(authority.body,'$.reason.kind')='current_authority_unavailable')";
// Correlated to the pending wait `w` in both ready and next_due.
const RECONCILABLE_WAIT: &str = "
(json_extract(w.body,'$.reason.kind') IS 'approval' AND (
EXISTS(SELECT 1 FROM agent_approvals a WHERE a.run=w.run AND a.key=json_extract(w.body,'$.reason.approval'))
OR EXISTS(SELECT 1 FROM agent_tools t WHERE t.run=w.run AND t.pending=1 AND json_extract(t.body,'$.approvalRefusal.approval')=json_extract(w.body,'$.reason.approval'))))
OR (w.due_at IS NULL AND json_extract(w.body,'$.reason.kind') IS 'model' AND EXISTS(
SELECT 1 FROM agent_attempts a WHERE a.run=w.run AND a.key=json_extract(w.body,'$.reason.attempt')
AND json_extract(a.body,'$.admission') IS NOT NULL
AND json_extract(a.body,'$.cleanup.kind') IS 'confirmed'))
OR (w.due_at IS NULL AND json_extract(w.body,'$.reason.kind') IS 'cell' AND EXISTS(
SELECT 1 FROM (
SELECT c.cell, c.run, jsonb(maka_content_text(c.body,c.body_encoding)) AS doc
FROM agent_cells c WHERE c.cell=json_extract(w.body,'$.reason.cell') AND c.run=w.run
) c
WHERE json_extract(c.doc,'$.status.kind') IN ('completed','interrupted')
AND json_extract(c.doc,'$.vmUncertainty') IS NULL
AND NOT EXISTS(SELECT 1 FROM json_each(c.doc,'$.children') child WHERE NOT (
json_extract(child.value,'$.rejected') IS NOT NULL
OR (json_extract(child.value,'$.localResult') IS NOT NULL AND json_extract(child.value,'$.localResult.settlement') IS NOT 'unknown')
OR (json_extract(child.value,'$.reply.receipt.kind') IS 'recorded' AND json_extract(child.value,'$.reply.receipt.cleanup.kind') IS 'confirmed')))))
OR (w.due_at IS NULL AND json_extract(w.body,'$.reason.kind') IS 'operation' AND EXISTS(
SELECT 1 FROM agent_tools t WHERE t.run=w.run
AND t.key=json_extract(w.body,'$.reason.tool.attempt')||':'||json_extract(w.body,'$.reason.tool.call')
AND json_extract(t.body,'$.original') IS NOT NULL
AND json_extract(t.body,'$.receipt.kind') IS 'recorded'
AND (json_extract(t.body,'$.receipt.outcome.kind') IN ('returned','not_executed')
OR (json_extract(t.body,'$.receipt.outcome.kind') IS 'unknown'
AND json_extract(t.body,'$.accepted.outcome.kind') IS 'risk_adjudicated'
AND EXISTS(SELECT 1 FROM agent_blockers b WHERE b.run=t.run
AND b.key=json_extract(t.body,'$.accepted.outcome.blocker')
AND json_extract(b.body,'$.decision') IS NOT NULL
AND json_extract(b.body,'$.decision.scope.kind') IN ('tool','model_replan'))))
AND json_extract(t.body,'$.receipt.cleanup.kind') IS 'confirmed'))";
fn signed(value: u64) -> Result<i64, StoreError> {
i64::try_from(value).map_err(|_| invalid("Agent integer exceeds SQLite range"))
}
fn column_u64(row: &rusqlite::Row<'_>, index: usize) -> rusqlite::Result<u64> {
let value: i64 = row.get(index)?;
u64::try_from(value).map_err(|_| rusqlite::Error::IntegralValueOutOfRange(index, value))
}
fn now() -> Result<UnixMillis, StoreError> {
let value = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_err(|_| invalid("clock precedes epoch"))?
.as_millis();
Ok(UnixMillis(
i64::try_from(value).map_err(|_| invalid("clock exceeds supported range"))?,
))
}
fn version(version: u32) -> Result<(), StoreError> {
if version != SCHEMA_VERSION {
return Err(invalid(format!(
"unsupported Agent schema version: {version}"
)));
}
Ok(())
}
pub(crate) fn identity<T: DeserializeOwned>(value: String) -> Result<T, StoreError> {
Ok(serde_json::from_value(serde_json::Value::String(value))?)
}
fn limit(limit: u32) -> Result<u32, StoreError> {
if !(1..=1024).contains(&limit) {
return Err(invalid("page size must be in 1..=1024"));
}
Ok(limit)
}
type BatchBlobs = HashMap<String, (i64, u64, Option<Arc<[u8]>>)>;
fn put(c: &Connection, blob: &ContentBlob) -> Result<i64, StoreError> {
blob.store(c)
}
fn content_id(c: &Connection, reference: &ContentRef) -> Result<i64, StoreError> {
reference.validate().map_err(invalid)?;
c.prepare_cached("SELECT id FROM contents WHERE content_sha256=? AND COALESCE(logical_bytes,length(payload))=?")?
.query_row(params![reference.digest, signed(reference.bytes)?], |row| {
row.get(0)
})
.optional()?
.ok_or_else(|| invalid("missing canonical content"))
}
fn content_id_cached(
c: &Connection,
batch: &BatchBlobs,
reference: &ContentRef,
) -> Result<i64, StoreError> {
reference.validate().map_err(invalid)?;
if let Some(&(id, bytes, _)) = batch.get(&reference.digest)
&& bytes == reference.bytes
{
return Ok(id);
}
content_id(c, reference)
}
fn pin_id(c: &Connection, run: RunId, id: i64) -> Result<(), StoreError> {
c.prepare_cached(
"INSERT INTO agent_content_pins(run,content_id) VALUES(?,?) ON CONFLICT DO NOTHING",
)?
.execute(params![run.to_string(), id])?;
Ok(())
}
pub(crate) fn pin(c: &Connection, run: RunId, reference: &ContentRef) -> Result<(), StoreError> {
pin_id(c, run, content_id(c, reference)?)
}
fn pin_cached(
c: &Connection,
batch: &BatchBlobs,
run: RunId,
reference: &ContentRef,
) -> Result<(), StoreError> {
pin_id(c, run, content_id_cached(c, batch, reference)?)
}
fn insert_blobs(c: &Connection, blobs: &[ContentBlob]) -> Result<BatchBlobs, StoreError> {
let mut inserted = HashMap::with_capacity(blobs.len());
for blob in blobs {
let id = put(c, blob)?;
let raw = blob.memory_arc();
inserted.insert(
blob.reference.digest.clone(),
(id, blob.reference.bytes, raw),
);
}
Ok(inserted)
}
pub(super) fn decode<T: DeserializeOwned>(
c: &Connection,
reference: &ContentRef,
) -> Result<T, StoreError> {
content_id(c, reference)?;
let bytes =
content::read(c, &reference.digest)?.ok_or_else(|| invalid("missing canonical bytes"))?;
Ok(serde_json::from_slice(&bytes)?)
}
fn decode_cached<T: DeserializeOwned>(
c: &Connection,
batch: &BatchBlobs,
reference: &ContentRef,
) -> Result<T, StoreError> {
reference.validate().map_err(invalid)?;
if let Some((_, bytes, Some(raw))) = batch.get(&reference.digest)
&& *bytes == reference.bytes
{
return Ok(serde_json::from_slice(raw)?);
}
decode(c, reference)
}
fn decode_surface_cached(
c: &Connection,
batch: &BatchBlobs,
reference: &ContentRef,
) -> Result<Arc<maka_agent_facts::composition::CompositionSurface>, StoreError> {
content_id_cached(c, batch, reference)?;
let key = (reference.digest.clone(), reference.bytes);
if let Some(cached) = surface_cache()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.get(&key)
.cloned()
{
return Ok(cached);
}
let value: maka_agent_facts::composition::CompositionSurface =
decode_cached(c, batch, reference)?;
let value = Arc::new(value);
surface_cache()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.insert(key, Arc::clone(&value));
Ok(value)
}
/// Fail-closed extraction of `payload.instructionsRef` from an owned external task descriptor.
/// Absent or `null` `payload` / `instructionsRef` returns `Ok(None)`; malformed JSON or a
/// malformed `instructionsRef` returns an error instead of silently dropping pinning/custody.
pub(crate) fn external_task_instructions_ref(
c: &Connection,
run: RunId,
descriptor: &ContentRef,
) -> Result<Option<ContentRef>, StoreError> {
let raw = owned_content(c, run, descriptor)?;
let val: serde_json::Value = serde_json::from_slice(&raw)?;
let Some(instr) = val.pointer("/payload/instructionsRef") else {
return Ok(None);
};
if instr.is_null() {
return Ok(None);
}
let instr_ref: ContentRef = serde_json::from_value(instr.clone())
.map_err(|e| invalid(format!("invalid external task instructionsRef: {e}")))?;
instr_ref.validate().map_err(invalid)?;
Ok(Some(instr_ref))
}
pub(crate) fn owned_content(
c: &Connection,
run: RunId,
reference: &ContentRef,
) -> Result<Vec<u8>, StoreError> {
with_owned_content(c, run, reference, |bytes| Ok(bytes.to_vec()))
}
pub(crate) fn verify_owned_content(
c: &Connection,
run: RunId,
reference: &ContentRef,
) -> Result<(), StoreError> {
reference.validate().map_err(invalid)?;
let owns: bool = c
.prepare_cached(
"SELECT EXISTS(SELECT 1 FROM agent_run_content p JOIN contents c ON c.id=p.content_id WHERE p.run=? AND c.content_sha256=? AND COALESCE(c.logical_bytes,length(c.payload))=?)",
)?
.query_row(
params![run.to_string(), reference.digest, signed(reference.bytes)?],
|r| r.get(0),
)?;
if !owns {
return Err(invalid("content is not retained by this Run"));
}
Ok(())
}
pub(crate) fn with_owned_content<T>(
c: &Connection,
run: RunId,
reference: &ContentRef,
consume: impl FnOnce(&[u8]) -> Result<T, StoreError>,
) -> Result<T, StoreError> {
with_owned_content_sql(
c,
run,
reference,
"SELECT maka_content_bytes(c.payload,c.encoding) FROM agent_run_content p JOIN contents c ON c.id=p.content_id WHERE p.run=? AND c.content_sha256=? AND COALESCE(c.logical_bytes,length(c.payload))=?",
consume,
)
}
pub(crate) fn with_owned_content_legacy<T>(
c: &Connection,
run: RunId,
reference: &ContentRef,
consume: impl FnOnce(&[u8]) -> Result<T, StoreError>,
) -> Result<T, StoreError> {
with_owned_content_sql(
c,
run,
reference,
"SELECT c.payload FROM agent_run_content p JOIN contents c ON c.id=p.content_id WHERE p.run=? AND c.content_sha256=? AND length(c.payload)=?",
consume,
)
}
fn with_owned_content_sql<T>(
c: &Connection,
run: RunId,
reference: &ContentRef,
sql: &str,
consume: impl FnOnce(&[u8]) -> Result<T, StoreError>,
) -> Result<T, StoreError> {
reference.validate().map_err(invalid)?;
let mut statement = c.prepare_cached(sql)?;
let mut rows = statement.query(params![
run.to_string(),
reference.digest,
signed(reference.bytes)?
])?;
let row = rows
.next()?
.ok_or_else(|| invalid("content is not retained by this Run"))?;
let value = row.get_ref(0)?;
let bytes = value.as_blob().map_err(|cause| {
rusqlite::Error::FromSqlConversionFailure(0, value.data_type(), Box::new(cause))
})?;
consume(bytes)
}
pub(crate) fn spec(c: &Connection, run: RunId) -> Result<(RunSpec, ContentRef), StoreError> {
let run_str = run.to_string();
let (v, digest, logical_bytes): (u32, String, i64) = c
.prepare_cached(
"SELECT r.schema_version,c.content_sha256,COALESCE(c.logical_bytes,length(c.payload))
FROM agent_run_specs r JOIN contents c ON c.id=r.spec_content_id WHERE r.run=?",
)?
.query_row([&run_str], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))
.optional()?
.ok_or_else(|| invalid("Run not found"))?;
version(v)?;
let bytes_len = u64::try_from(logical_bytes)
.map_err(|_| invalid("canonical content length exceeds u64"))?;
let key = (digest.clone(), bytes_len);
if let Some(cached) = spec_cache()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.get(&key)
.cloned()
{
return Ok((
(*cached).clone(),
ContentRef {
digest,
bytes: bytes_len,
},
));
}
let bytes: Vec<u8> = c
.prepare_cached(
"SELECT maka_content_bytes(c.payload,c.encoding)
FROM agent_run_specs r JOIN contents c ON c.id=r.spec_content_id WHERE r.run=?",
)?
.query_row([&run_str], |r| r.get(0))
.optional()?
.ok_or_else(|| invalid("Run not found"))?;
let actual_len =
u64::try_from(bytes.len()).map_err(|_| invalid("canonical content length exceeds u64"))?;
if actual_len != bytes_len {
return Err(invalid("canonical spec byte length mismatch"));
}
let value: RunSpec = serde_json::from_slice(&bytes)?;
version(value.schema_version)?;
spec_cache()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.insert(key, Arc::new(value.clone()));
Ok((
value,
ContentRef {
digest,
bytes: actual_len,
},
))
}
pub(crate) fn check_live_header(
c: &Connection,
run: RunId,
allow_stopped: bool,
expected_spec: Option<&ContentRef>,
) -> Result<Option<(RunSpec, ContentRef)>, StoreError> {
let run_str = run.to_string();
let header: Option<(u32, bool, bool, Option<String>)> = c
.prepare_cached(
"SELECT schema_version, local, stopped, terminal FROM agent_runs WHERE run=?",
)?
.query_row([&run_str], |r| {
Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?))
})
.optional()?;
let (schema_version, local, stopped, terminal) =
header.ok_or_else(|| invalid("Run indexes are absent; explicit rebuild required"))?;
if schema_version != HEADER_SCHEMA_VERSION {
return Err(invalid(
"Run indexes have an old projection schema; rebuild required",
));
}
if !local || (!allow_stopped && stopped) || terminal.is_some() {
return Err(invalid("Run is no longer executable"));
}
if let Some(expected) = expected_spec {
let meta: Option<(u32, String, u64)> = c
.prepare_cached(
"SELECT r.schema_version, c.content_sha256, COALESCE(c.logical_bytes, length(c.payload))
FROM agent_run_specs r JOIN contents c ON c.id=r.spec_content_id WHERE r.run=?",
)?
.query_row([&run_str], |r| Ok((r.get(0)?, r.get(1)?, column_u64(r, 2)?)))
.optional()?;
let (v, digest, bytes) = meta.ok_or_else(|| invalid("Run not found"))?;
version(v)?;
if digest == expected.digest && bytes == expected.bytes {
return Ok(None);
}
}
let (loaded_spec, spec_ref) = spec(c, run)?;
if !matches!(loaded_spec.origin, RunOrigin::Local) {
return Err(invalid("Run is no longer executable"));
}
Ok(Some((loaded_spec, spec_ref)))
}
pub(crate) fn read_provider_tool_state(
c: &Connection,
run: RunId,
attempt: ModelAttemptId,
call_id: &str,
) -> Result<(Option<Attempt>, Option<Tool>), StoreError> {
let run_str = run.to_string();
let attempt_body: Option<String> = c
.prepare_cached("SELECT body FROM agent_attempts WHERE run=? AND key=?")?
.query_row(params![&run_str, attempt.to_string()], |row| row.get(0))
.optional()?;
let loaded_attempt = attempt_body
.map(|body| serde_json::from_str::<Attempt>(&body))
.transpose()?;
let tool_key = format!("{attempt}:{call_id}");
let tool_body: Option<String> = c
.prepare_cached("SELECT body FROM agent_tools WHERE run=? AND key=?")?
.query_row(params![&run_str, tool_key], |row| row.get(0))
.optional()?;
let loaded_tool = tool_body
.map(|body| serde_json::from_str::<Tool>(&body))
.transpose()?;
Ok((loaded_attempt, loaded_tool))
}
pub(crate) fn read_tool_state(
c: &Connection,
run: RunId,
key: &ToolKey,
) -> Result<Option<Tool>, StoreError> {
let tool_body: Option<String> = c
.prepare_cached("SELECT body FROM agent_tools WHERE run=? AND key=?")?
.query_row(params![run.to_string(), fold::tool_key(key)], |row| {
row.get(0)
})
.optional()?;
tool_body
.map(|body| serde_json::from_str::<Tool>(&body))
.transpose()
.map_err(Into::into)
}
pub(crate) fn exists(c: &Connection, run: RunId) -> Result<bool, StoreError> {
Ok(
c.prepare_cached("SELECT 1 FROM agent_run_specs WHERE run=?")?
.query_row([run.to_string()], |r| r.get::<_, i64>(0))
.optional()?
.is_some(),
)
}
pub(crate) fn model_attempt(
c: &Connection,
run: RunId,
attempt: ModelAttemptId,
) -> Result<Attempt, StoreError> {
let body: String = c
.prepare_cached("SELECT body FROM agent_attempts WHERE run=? AND key=?")?
.query_row(params![run.to_string(), attempt.to_string()], |row| {
row.get(0)
})?;
Ok(serde_json::from_str(&body)?)
}
fn projection_rows<T: DeserializeOwned>(
c: &Connection,
table: &str,
run: RunId,
keys: &BTreeSet<String>,
all: bool,
) -> Result<Vec<(String, T)>, StoreError> {
let run_str = run.to_string();
let mut result = Vec::new();
if all {
let query = format!("SELECT key,body FROM {table} WHERE run=?1");
let mut statement = c.prepare_cached(&query)?;
let mut rows = statement.query(params![run_str])?;
while let Some(row) = rows.next()? {
result.push((
row.get(0)?,
serde_json::from_str(&row.get::<_, String>(1)?)?,
));
}
} else if keys.is_empty() {
let query = format!("SELECT key,body FROM {table} WHERE run=?1 AND pending=1");
let mut statement = c.prepare_cached(&query)?;
let mut rows = statement.query(params![run_str])?;
while let Some(row) = rows.next()? {
result.push((
row.get(0)?,
serde_json::from_str(&row.get::<_, String>(1)?)?,
));
}
} else if keys.len() == 1 {
let only = keys.iter().next().expect("single key");
let query = format!(
"SELECT key,body FROM {table} WHERE run=?1 AND pending=1 UNION ALL SELECT key,body FROM {table} WHERE run=?1 AND key=?2 AND pending=0"
);
let mut statement = c.prepare_cached(&query)?;
let mut rows = statement.query(params![run_str, only])?;
while let Some(row) = rows.next()? {
result.push((
row.get(0)?,
serde_json::from_str(&row.get::<_, String>(1)?)?,
));
}
} else {
let query = format!(
"SELECT key,body FROM {table} WHERE run=?1 AND pending=1 UNION ALL SELECT key,body FROM {table} WHERE run=?1 AND key IN (SELECT value FROM json_each(?2)) AND pending=0"
);
let mut statement = c.prepare_cached(&query)?;
let keys = serde_json::to_string(keys)?;
let mut rows = statement.query(params![run_str, keys])?;
while let Some(row) = rows.next()? {
result.push((
row.get(0)?,
serde_json::from_str(&row.get::<_, String>(1)?)?,
));
}
}
Ok(result)
}
#[derive(Default)]
struct Targets {
steps: BTreeSet<String>,
attempts: BTreeSet<String>,
tools: BTreeSet<String>,
approvals: BTreeSet<String>,
blockers: BTreeSet<String>,
waits: BTreeSet<String>,
}
impl Targets {
fn tool(&mut self, tool: &ToolKey) {
self.tools.insert(fold::tool_key(tool));
self.attempts.insert(tool.attempt.to_string());
}
fn blocker(&mut self, reason: &BlockerKind) {
match reason {
BlockerKind::ModelCleanupUnconfirmed { attempt, .. } => {
self.attempts.insert(attempt.to_string());
}
BlockerKind::OperationUnknown { tool, .. }
| BlockerKind::OriginalAdmissionUnknown { tool }
| BlockerKind::ToolCleanupUnconfirmed { tool, .. }
| BlockerKind::ResourcesUnavailable { tool } => self.tool(tool),
BlockerKind::ProviderEffectUnknown { attempt, call } => self.tool(&ToolKey {
attempt: *attempt,
call: call.clone(),
}),
_ => {}
}
}
fn risk_scope(&mut self, scope: &RiskActionScope) {
match scope {
RiskActionScope::Tool { tool } => self.tool(tool),
RiskActionScope::ModelReplan { attempt, base_step } => {
self.attempts.insert(attempt.to_string());
self.steps.insert(base_step.to_string());
}
RiskActionScope::RunCancellation => {}
}
}
fn fact(&mut self, fact: &Fact) {
match fact {
Fact::StepPrepared {
step,
adjudications,
..
} => {
self.steps.insert(step.to_string());
self.blockers
.extend(adjudications.iter().map(ToString::to_string));
}
Fact::ModelAttemptPrepared { attempt, step }
| Fact::ProactiveSummaryPrepared { attempt, step, .. } => {
self.attempts.insert(attempt.to_string());
self.steps.insert(step.to_string());
}
Fact::ModelSourceFailureCaptured { attempt, .. }
| Fact::ModelTransportSelected { attempt, .. }
| Fact::ModelPrivatePartialCaptured { attempt, .. }
| Fact::ModelInterrupted { attempt, .. }
| Fact::ModelAttemptAdmitted { attempt, .. }
| Fact::ModelFirstTokenObserved { attempt }
| Fact::ModelClosed { attempt, .. }
| Fact::ModelCleanupObserved { attempt, .. }
| Fact::AttemptRecoveryRecorded { attempt, .. }
| Fact::RetryCharged { attempt, .. } => {
self.attempts.insert(attempt.to_string());
}
Fact::ModelObserved { attempt, part, .. } => {
self.attempts.insert(attempt.to_string());
match part {
ModelPart::ToolCall { call } => self.tool(&ToolKey {
attempt: *attempt,
call: call.id.clone(),
}),
ModelPart::ToolResult { id, .. } => self.tool(&ToolKey {
attempt: *attempt,
call: id.clone(),
}),
_ => {}
}
}
Fact::ToolDecided { tool, decision } => {
self.tool(tool);
if let ToolDecision::Approved {
approval: Some(approval),
..
} = decision
{
self.approvals.insert(approval.to_string());
}
}
Fact::ToolOriginalBound { tool, .. }
| Fact::ToolAdmitted { tool }
| Fact::ToolPreventedBeforeHostAdmission { tool, .. }
| Fact::LocalToolReturned { tool, .. }
| Fact::HostToolResultRecorded { tool, .. }
| Fact::ToolsLoaded { tool, .. }
| Fact::OperationObserved { tool, .. } => self.tool(tool),
Fact::ToolResultAccepted { tool, outcome, .. } => {
self.tool(tool);
if let AcceptedResult::RiskAdjudicated { blocker } = outcome {
self.blockers.insert(blocker.to_string());
}
}
Fact::ApprovalRecorded { approval, tool, .. }
| Fact::ApprovalRefused { approval, tool, .. }
| Fact::ApprovalConsumed { approval, tool } => {
self.tool(tool);
self.approvals.insert(approval.to_string());
}
Fact::Blocked { blocker, reason } => {
self.blockers.insert(blocker.to_string());
self.blocker(reason);
}
Fact::RiskAdjudicated { blocker, scope, .. } => {
self.blockers.insert(blocker.to_string());
self.risk_scope(scope);
}
Fact::BlockerResolved { blocker, .. } => {
self.blockers.insert(blocker.to_string());
}
Fact::WaitRegistered { wait, reason, .. } => {
self.waits.insert(wait.to_string());
match reason {
WaitReason::Approval { approval } => {
self.approvals.insert(approval.to_string());
}
WaitReason::Retry { attempt }
| WaitReason::Model { attempt }
| WaitReason::ProviderBackoff { attempt } => {
self.attempts.insert(attempt.to_string());
}
WaitReason::Operation { tool } => self.tool(tool),
WaitReason::Blocker { blocker } => {
self.blockers.insert(blocker.to_string());
}
_ => {}
}
}
Fact::WaitSatisfied { wait, .. } | Fact::WaitCancelled { wait, .. } => {
self.waits.insert(wait.to_string());
}
_ => {}
}
}
}
/// Only open obligations and explicitly referenced settled entities enter the
/// mutation working set. Closed history is not scanned/copied on each callback.
pub(crate) fn load(
c: &Connection,
run: RunId,
facts: &[&Fact],
all: bool,
) -> Result<RunView, StoreError> {
load_with_admission(c, run, facts, all).map(|(view, _)| view)
}
fn load_with_admission(
c: &Connection,
run: RunId,
facts: &[&Fact],
all: bool,
) -> Result<(RunView, u64), StoreError> {
let (spec, spec_ref) = spec(c, run)?;
let mut view = RunView::admitted(run, spec)?;
view.spec_ref = Some(spec_ref);
struct HeaderRow {
schema_version: u32,
admission_sequence: u64,
revision: u64,
control_version: u64,
stopped: bool,
terminal: Option<String>,
tokens: u64,
retries: u32,
retry_due_at: Option<i64>,
retry_pending: Option<String>,
current_step: Option<String>,
current_attempt: Option<String>,
cancelled_by_risk: bool,
replans: String,
baseline: Option<String>,
external: Option<String>,
stop_request: Option<String>,
stop_assessed: Option<String>,
retry_phase: String,
finish_requested: bool,
proactive_summary: Option<String>,
output_limit_continuations: u32,
retry_streak: String,
}
let raw = c
.prepare_cached(
"SELECT schema_version,admission_sequence,revision,control_version,stopped,terminal,tokens,retries,retry_due_at,retry_pending,current_step,current_attempt,cancelled_by_risk,replans,baseline,external,stop_request,stop_assessed,retry_phase,finish_requested,proactive_summary,output_limit_continuations,retry_streak FROM agent_runs WHERE run=?",
)?
.query_row([run.to_string()], |r| {
Ok(HeaderRow {
schema_version: r.get(0)?,
admission_sequence: column_u64(r, 1)?,
revision: column_u64(r, 2)?,
control_version: column_u64(r, 3)?,
stopped: r.get(4)?,
terminal: r.get(5)?,
tokens: column_u64(r, 6)?,
retries: r.get(7)?,
retry_due_at: r.get(8)?,
retry_pending: r.get(9)?,
current_step: r.get(10)?,
current_attempt: r.get(11)?,
cancelled_by_risk: r.get(12)?,
replans: r.get(13)?,
baseline: r.get(14)?,
external: r.get(15)?,
stop_request: r.get(16)?,
stop_assessed: r.get(17)?,
retry_phase: r.get(18)?,
finish_requested: r.get(19)?,
proactive_summary: r.get(20)?,
output_limit_continuations: r.get(21)?,
retry_streak: r.get(22)?,
})
})
.optional()?
.ok_or_else(|| invalid("Run indexes are absent; explicit rebuild required"))?;
if raw.schema_version != HEADER_SCHEMA_VERSION {
return Err(invalid(
"Run indexes have an old projection schema; rebuild required",
));
}
view.retry_phase = identity(raw.retry_phase)?;
view.finish_requested = raw.finish_requested;
view.proactive_summary = raw.proactive_summary.map(identity).transpose()?;
view.output_limit_continuations = raw.output_limit_continuations;
view.retry_streak = serde_json::from_str(&raw.retry_streak)?;
view.revision = raw.revision;
view.control_version = raw.control_version;
view.stopped = raw.stopped;
view.terminal = raw.terminal.map(|v| serde_json::from_str(&v)).transpose()?;
view.tokens = raw.tokens;
view.retries = raw.retries;
view.retry_due_at = raw.retry_due_at.map(UnixMillis);
view.retry_pending = raw.retry_pending.map(identity).transpose()?;
view.current_step = raw.current_step.map(identity).transpose()?;
view.current_attempt = raw.current_attempt.map(identity).transpose()?;
view.cancelled_by_risk = raw.cancelled_by_risk;
view.replans = serde_json::from_str(&raw.replans)?;
view.baseline = raw
.baseline
.map(|body| serde_json::from_str(&body))
.transpose()?;
view.external = raw
.external
.map(|body| serde_json::from_str(&body))
.transpose()?;
view.stop_request = raw.stop_request.map(identity).transpose()?;
view.stop_assessed = raw.stop_assessed.map(identity).transpose()?;
if !all
&& !facts.is_empty()
&& facts.iter().all(|fact| {
matches!(
fact,
Fact::ExternalTaskCleanupObserved { .. } | Fact::ExternalTaskCleanupDeferred { .. }
)
})
{
for (key, value) in
projection_rows::<Blocker>(c, "agent_blockers", run, &BTreeSet::new(), false)?
{
view.blockers.insert(identity(key)?, value);
}
return Ok((view, raw.admission_sequence));
}
if let Some(task) = &mut view.external {
task.effects = crate::external_effects::load_run(c, run, facts, all)?;
task.publication = crate::external_publication::load_run(c, run, facts, all)?;
}
let mut targets = Targets::default();
for fact in facts {
targets.fact(fact);
}
// Late server calls need the actual decision/id, not just the sticky logical fence.
if !all
&& view.cancelled_by_risk
&& facts.iter().any(|fact| {
matches!(fact,
Fact::ModelObserved { part: ModelPart::ToolCall { call }, .. } if call.provider_executed)
})
{
let retired = c
.prepare_cached(
"SELECT key FROM agent_blockers WHERE run=? AND pending=0
AND json_extract(body,'$.decision.scope.kind')='run_cancellation'",
)?
.query_map([run.to_string()], |row| row.get::<_, String>(0))?
.collect::<Result<Vec<_>, _>>()?;
targets.blockers.extend(retired);
}
if let Some(step) = view.current_step {
targets.steps.insert(step.to_string());
}
for attempt in [
view.current_attempt,
view.retry_pending,
view.proactive_summary,
]
.into_iter()
.flatten()
{
targets.attempts.insert(attempt.to_string());
}
let charged: Vec<String> = if view.retries == 0 {
Vec::new()
} else {
match crate::namespace::find_owner_id(c, &view.spec.owner, &view.spec.session_id)? {
Some(namespace_id) => c
.prepare_cached("SELECT attempt FROM agent_session_history INDEXED BY agent_session_history_kind WHERE namespace_id=? AND kind='retry_charged' AND run=? AND sequence>=? AND sequence<=(SELECT sequence FROM agent_facts WHERE run=? AND revision=?) ORDER BY sequence")?
.query_map(
params![
namespace_id,
run.to_string(),
signed(raw.admission_sequence)?,
run.to_string(),
signed(view.revision)?
],
|r| r.get(0),
)?
.collect::<Result<_, _>>()?,
None => Vec::new(),
}
};
targets.attempts.extend(charged);
for (id, replan) in &view.replans {
targets.blockers.insert(id.to_string());
targets.risk_scope(&replan.scope);
}
for (key, value) in
projection_rows::<Blocker>(c, "agent_blockers", run, &targets.blockers, all)?
{
targets.blocker(&value.reason);
view.blockers.insert(identity(key)?, value);
}
for (key, value) in projection_rows::<Wait>(c, "agent_waits", run, &targets.waits, all)? {
view.waits.insert(identity(key)?, value);
}
for (key, value) in projection_rows::<Tool>(c, "agent_tools", run, &targets.tools, all)? {
targets.attempts.insert(value.key.attempt.to_string());
if let Some(ToolDecision::Approved {
approval: Some(approval),
..
}) = &value.decision
{
targets.approvals.insert(approval.to_string());
}
view.tools.insert(key, value);
}
for (key, value) in
projection_rows::<Attempt>(c, "agent_attempts", run, &targets.attempts, all)?
{
targets.steps.insert(value.step.to_string());
view.attempts.insert(identity(key)?, value);
}
if view
.proactive_summary
.is_some_and(|id| !view.attempts.contains_key(&id))
{
return Err(invalid("proactive Summary attempt projection is missing"));
}
let blocked_cells = view.recovery_failures().filter_map(|reason| match reason {
BlockerKind::CodeCellRecoveryUnavailable { cell } => Some(cell.clone()),
BlockerKind::OriginalAdmissionUnknown { tool } => view
.tools
.get(&fold::tool_key(tool))
.and_then(|tool| view.original_cell_id(tool))
.map(|cell| cell.to_string()),
_ => None,
});
view.cells = crate::cells::load_run(c, run, facts, blocked_cells, all)?;
if view
.attempts
.values()
.filter(|attempt| attempt.retry.is_some())
.count() as u64
!= u64::from(view.retries)
{
return Err(invalid("canonical retry charge projection is incomplete"));
}
for (key, value) in projection_rows::<ContentRef>(c, "agent_steps", run, &targets.steps, all)? {
view.steps.insert(identity(key)?, value);
}
for (key, value) in
projection_rows::<Approval>(c, "agent_approvals", run, &targets.approvals, all)?
{
view.approvals.insert(identity(key)?, value);
}
Ok((view, raw.admission_sequence))
}
fn upsert<T: Serialize>(
c: &Connection,
table: &str,
run: RunId,
key: impl ToString,
pending: bool,
value: &T,
) -> Result<(), StoreError> {
c.prepare_cached(&format!("INSERT INTO {table}(run,key,pending,body) VALUES(?,?,?,?) ON CONFLICT(run,key) DO UPDATE SET pending=excluded.pending,body=excluded.body WHERE body<>excluded.body OR pending<>excluded.pending"))?.execute(params![run.to_string(),key.to_string(),pending,serde_json::to_string(value)?])?;
Ok(())
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct ExternalHeader<'a> {
task: ExternalTaskId,
descriptor: &'a ContentRef,
#[serde(skip_serializing_if = "std::ops::Not::not")]
live_workspace: bool,
admitted: bool,
binding: &'a Option<ContentRef>,
observed: u64,
#[serde(skip_serializing_if = "Option::is_none")]
session_title: &'a Option<String>,
closed: &'a Option<fold::ExternalClosure>,
cleanup: &'a maka_plugin_core::operation::OperationCleanup,
cleanup_not_before: Option<UnixMillis>,
steering: &'a Option<crate::external_steering::ExternalSteering>,
}
fn external_header(task: &fold::ExternalTask) -> Result<String, serde_json::Error> {
serde_json::to_string(&ExternalHeader {
task: task.task,
descriptor: &task.descriptor,
live_workspace: task.live_workspace,
admitted: task.admitted,
binding: &task.binding,
observed: task.observed,
session_title: &task.session_title,
closed: &task.closed,
cleanup: &task.cleanup,
cleanup_not_before: task.cleanup_not_before,
steering: &task.steering,
})
}
fn persist(c: &Connection, view: &RunView) -> Result<(), StoreError> {
let admission_sequence: u64 = c
.prepare_cached("SELECT sequence FROM agent_facts WHERE run=? AND revision=1")?
.query_row([view.run.to_string()], |r| column_u64(r, 0))?;
let owner_json = serde_json::to_string(&view.spec.owner)?;
persist_known(c, view, admission_sequence, &owner_json)
}
fn persist_known(
c: &Connection,
view: &RunView,
admission_sequence: u64,
owner_json: &str,
) -> Result<(), StoreError> {
let run_str = view.run.to_string();
let retry_phase = match view.retry_phase {
maka_agent_facts::model::retry_transport::RetryTransportPhase::Primary => "primary",
maka_agent_facts::model::retry_transport::RetryTransportPhase::Fallback => "fallback",
};
c.prepare_cached(
"INSERT INTO agent_runs(run,schema_version,owner,session,admission_sequence,local,revision,control_version,stopped,terminal,tokens,retries,retry_due_at,retry_pending,current_step,current_attempt,cancelled_by_risk,replans,baseline,external,stop_request,stop_assessed,retry_phase,finish_requested,proactive_summary,output_limit_continuations,retry_streak)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
ON CONFLICT(run) DO UPDATE SET
schema_version=excluded.schema_version,
revision=excluded.revision,
control_version=excluded.control_version,
stopped=excluded.stopped,
terminal=excluded.terminal,
tokens=excluded.tokens,
retries=excluded.retries,
retry_due_at=excluded.retry_due_at,
retry_pending=excluded.retry_pending,
current_step=excluded.current_step,
current_attempt=excluded.current_attempt,
cancelled_by_risk=excluded.cancelled_by_risk,
replans=excluded.replans,
baseline=excluded.baseline,
external=excluded.external,
stop_request=excluded.stop_request,
stop_assessed=excluded.stop_assessed,
retry_phase=excluded.retry_phase,
finish_requested=excluded.finish_requested,
proactive_summary=excluded.proactive_summary,
output_limit_continuations=excluded.output_limit_continuations,
retry_streak=excluded.retry_streak",
)?
.execute(params![
run_str,
HEADER_SCHEMA_VERSION,
owner_json,
view.spec.session_id,
signed(admission_sequence)?,
matches!(view.spec.origin, RunOrigin::Local),
signed(view.revision)?,
signed(view.control_version)?,
view.stopped,
view.terminal.as_ref().map(serde_json::to_string).transpose()?,
signed(view.tokens)?,
view.retries,
view.retry_due_at.map(|t| t.0),
view.retry_pending.map(|v| v.to_string()),
view.current_step.map(|v| v.to_string()),
view.current_attempt.map(|v| v.to_string()),
view.cancelled_by_risk,
serde_json::to_string(&view.replans)?,
view.baseline.as_ref().map(serde_json::to_string).transpose()?,
view.external.as_ref().map(external_header).transpose()?,
view.stop_request.map(|id| id.to_string()),
view.stop_assessed.map(|id| id.to_string()),
retry_phase,
view.finish_requested(),
view.proactive_summary.map(|attempt| attempt.to_string()),
view.output_limit_continuations,
serde_json::to_string(&view.retry_streak)?,
])?;
for (key, value) in &view.steps {
upsert(c, "agent_steps", view.run, key, false, value)?;
}
let failed = view.terminal == Some(Terminal::Failed);
for (key, value) in &view.attempts {
upsert(
c,
"agent_attempts",
view.run,
key,
fold::attempt_unsettled(value)
|| (!failed && value.closed.is_none() && value.interrupted.is_none()),
value,
)?;
}
for (key, value) in &view.tools {
upsert(
c,
"agent_tools",
view.run,
key,
if failed {
view.tool_unsettled(value)
} else {
fold::tool_pending(value)
},
value,
)?;
}
for (key, value) in &view.approvals {
upsert(c, "agent_approvals", view.run, key, !value.consumed, value)?;
}
for (key, value) in &view.blockers {
let needed = view.tools.values().any(|tool| {
fold::tool_pending(tool)
&& (value.decision.as_ref().is_some_and(|decision| {
matches!(decision.scope, RiskActionScope::RunCancellation)
}) || fold::blocker_covers(&value.reason, tool))
});
upsert(
c,
"agent_blockers",
view.run,
key,
(value.decision.is_none() && value.resolved_by.is_none()) || needed,
value,
)?;
}
for (key, value) in &view.waits {
c.prepare_cached("INSERT INTO agent_waits(run,key,pending,due_at,body) VALUES(?,?,?,?,?) ON CONFLICT(run,key) DO UPDATE SET pending=excluded.pending,due_at=excluded.due_at,body=excluded.body WHERE body<>excluded.body")?.execute(params![view.run.to_string(),key.to_string(),value.satisfied.is_none()&&value.cancelled.is_none(),value.due_at.map(|t|t.0),serde_json::to_string(value)?])?;
}
crate::session_catalog::index_run(c, view)?;
Ok(())
}
fn validate_request(
c: &Connection,
batch: &BatchBlobs,
view: &RunView,
step: StepId,
reference: &ContentRef,
adjudications: &[BlockerId],
proactive: bool,
) -> Result<(RequestSpec, Option<StepId>), StoreError> {
let existing: Option<(String, i64)> = c
.prepare_cached("SELECT run,content_id FROM agent_request_specs WHERE step=?")?
.query_row([step.to_string()], |r| Ok((r.get(0)?, r.get(1)?)))
.optional()?;
let id = content_id_cached(c, batch, reference)?;
if existing
.as_ref()
.is_some_and(|(run, content)| *run != view.run.to_string() || *content != id)
{
return Err(StoreError::EventConflict);
}
let request: RequestSpec = decode_cached(c, batch, reference)?;
version(request.schema_version)?;
request.accounting.validate().map_err(invalid)?;
let surface = decode_surface_cached(c, batch, &request.composition.surface)?;
request.composition.validate(&surface).map_err(invalid)?;
let fallback = if proactive {
compaction::validate_proactive_request(c, view, &request, &surface)?;
None
} else {
validate_request_lineage(c, view, &request)?
};
if request.step != step {
return Err(invalid("request belongs to another logical Step"));
}
if request.protocol.is_empty() || request.protocol_version == 0 {
return Err(invalid("request protocol descriptor is absent"));
}
if !maka_agent_facts::archive::valid_projection_digest(&request.source_digest)
|| !maka_agent_facts::archive::valid_projection_digest(&request.effective_source_digest)
{
return Err(invalid("invalid frozen source digest"));
}
if request
.adjudications
.iter()
.map(|basis| basis.blocker)
.ne(adjudications.iter().copied())
{
return Err(invalid(
"request adjudication list differs from the frozen Step choice",
));
}
for basis in &request.adjudications {
let scoped = view
.replans
.get(&basis.blocker)
.ok_or_else(|| invalid("request has no active scoped human replan basis"))?;
let RiskActionScope::ModelReplan { attempt, base_step } = &scoped.scope else {
return Err(invalid(
"non-model risk scope cannot authorize a prepared model request",
));
};
let original = view
.attempts
.get(attempt)
.ok_or_else(|| invalid("request replan scope names an unknown original attempt"))?;
if original.step != *base_step || view.current_step != Some(*base_step) {
return Err(invalid(
"request replan scope differs from the original attempt and base Step",
));
}
let evidence = match &scoped.decision {
RiskDecision::AuthorizeReplan { evidence }
| RiskDecision::RecordExternalObservation { evidence } => evidence,
RiskDecision::CancelBlockedRun { .. } => {
return Err(invalid("cancellation is not a replan basis"));
}
};
if &basis.evidence != evidence || request.projection.is_some() {
return Err(invalid(
"human replan cannot masquerade as protocol prefix proof",
));
}
}
for reference in request.content_refs() {
pin_cached(c, batch, view.run, reference)?;
}
if !proactive
&& adjudications.is_empty()
&& let Some(pending) = view.retry_pending
&& let Some(AttemptRecovery::ProjectPrefixSafe { prefix, .. }) = view
.attempts
.get(&pending)
.and_then(|attempt| attempt.recovery.as_ref())
&& request.projection.as_ref() != Some(prefix)
{
return Err(invalid(
"projected request is not bound to the original safe prefix",
));
}
Ok((request, fallback))
}
fn validate_external_final_message(
c: &Connection,
view: &RunView,
incoming: &Fact,
) -> Result<(), StoreError> {
let Fact::ExternalTaskClosed {
task,
outcome,
final_message: Some(final_message),
..
} = incoming
else {
return Ok(());
};
if *outcome != Terminal::Completed {
return Err(invalid(
"only a completed original task may identify a final message",
));
}
let external = view
.external
.as_ref()
.filter(|external| external.task == *task)
.ok_or_else(|| invalid("final message has no original external task"))?;
let original = fact(c, view.run, final_message.end)?
.ok_or_else(|| invalid("final message has no original canonical MessageEnd"))?;
if original.revision == 0 || original.revision > view.revision {
return Err(invalid(
"final MessageEnd is outside the original task prefix",
));
}
match original.fact {
Fact::ExternalTaskObserved {
task: observed_task,
index,
output: maka_agent_facts::executor::Output::MessageEnd { message_id },
..
} if observed_task == *task
&& index < external.observed
&& message_id == final_message.message_id =>
{
Ok(())
}
_ => Err(invalid(
"final message differs from its exact original task MessageEnd",
)),
}
}
fn validate_private_provider_effect(
c: &Connection,
view: &RunView,
incoming: &Fact,
) -> Result<(), StoreError> {
let Fact::Blocked {
reason: BlockerKind::ProviderEffectUnknown { attempt, call },
..
} = incoming
else {
return Ok(());
};
let tool = ToolKey {
attempt: *attempt,
call: call.clone(),
};
if view.tools.contains_key(&fold::tool_key(&tool)) {
return Ok(());
}
let original = view
.attempts
.get(attempt)
.ok_or_else(|| invalid("private provider effect has no original model attempt"))?;
let (schema,step,purpose): (u32,String,String) = c.query_row(
"SELECT json_extract(maka_content_text(b.payload,b.encoding),'$.schemaVersion'),json_extract(maka_content_text(b.payload,b.encoding),'$.step'),json_extract(maka_content_text(b.payload,b.encoding),'$.accounting.purpose') FROM agent_request_specs r JOIN contents b ON b.id=r.content_id WHERE r.run=? AND r.step=?",
params![view.run.to_string(),original.step.to_string()],|row| Ok((row.get(0)?,row.get(1)?,row.get(2)?)),
)?;
version(schema)?;
if identity::<StepId>(step)? != original.step
|| identity::<maka_agent_facts::context::ModelPurpose>(purpose)?
!= maka_agent_facts::context::ModelPurpose::Summary
{
return Err(invalid(
"private provider effect requires an original Summary request",
));
}
Ok(())
}
fn validate_request_lineage(
c: &Connection,
view: &RunView,
incoming: &RequestSpec,
) -> Result<Option<StepId>, StoreError> {
use maka_agent_facts::context::ModelPurpose;
crate::store::fallback::validate_codex_fallback(c, view, incoming)?;
let previous = view.current_step.map(|step| {
let (schema, original, purpose, recovery): (u32, String, String, Option<String>) = c
.prepare_cached(
"SELECT json_extract(maka_content_text(b.payload,b.encoding),'$.schemaVersion'),json_extract(maka_content_text(b.payload,b.encoding),'$.step'),json_extract(maka_content_text(b.payload,b.encoding),'$.accounting.purpose'),json_extract(maka_content_text(b.payload,b.encoding),'$.compactionRecovery') FROM agent_request_specs r JOIN contents b ON b.id=r.content_id WHERE r.run=? AND r.step=?",
)?
.query_row(params![view.run.to_string(), step.to_string()], |row| {
Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
})?;
version(schema)?;
if identity::<StepId>(original)? != step { return Err(invalid("current request belongs to another Step")); }
let purpose: ModelPurpose = identity(purpose)?;
let recovery: Option<ModelAttemptId> = recovery.map(identity).transpose()?;
Ok::<_,StoreError>((step, purpose, recovery))
}).transpose()?;
let fallback = if previous.is_some_and(|(_, purpose, _)| purpose == ModelPurpose::Summary)
&& incoming.accounting.purpose == ModelPurpose::Main
{
crate::store::fallback::validate_resume(c, view, incoming)?
} else {
None
};
let previous_recovery = previous.and_then(|(_, _, source)| source);
match (previous_recovery, incoming.compaction_recovery) {
(Some(_), None)
if incoming.accounting.purpose == ModelPurpose::Summary
&& incoming.summary_repair_of.is_none()
&& previous.is_some_and(|(_, purpose, _)| purpose == ModelPurpose::Main)
&& crate::store::fallback::rearm_in_snapshot(
c,
view,
previous.expect("checked current Main").0,
)? => {}
(Some(previous_source), Some(source))
if source != previous_source
&& incoming.accounting.purpose == ModelPurpose::Summary
&& incoming.summary_repair_of.is_none()
&& previous.is_some_and(|(_, purpose, _)| purpose == ModelPurpose::Main)
&& view.current_attempt == Some(source)
&& crate::store::fallback::rearm_in_snapshot(
c,
view,
previous.expect("checked current Main").0,
)? => {}
(Some(source), current) if current != Some(source) => {
return Err(invalid(
"compaction recovery lineage cannot be replaced or cleared",
));
}
(None, Some(source)) => {
let original = view
.current_attempt
.filter(|attempt| *attempt == source)
.and_then(|attempt| view.attempts.get(&attempt))
.ok_or_else(|| invalid("compaction recovery has no current original attempt"))?;
let resumed_summary = previous == Some((original.step, ModelPurpose::Summary, None))
&& incoming.accounting.purpose == ModelPurpose::Main;
if !resumed_summary
&& (previous != Some((original.step, ModelPurpose::Main, None))
|| incoming.accounting.purpose != ModelPurpose::Summary
|| !original.compactable_overflow())
{
return Err(invalid(
"compaction recovery requires the original compactable Main overflow",
));
}
}
_ => {}
}
if let Some(source) = incoming.summary_repair_of {
let original = view
.current_attempt
.filter(|attempt| *attempt == source)
.and_then(|attempt| view.attempts.get(&attempt))
.ok_or_else(|| invalid("summary repair has no current original attempt"))?;
if view.current_step != Some(original.step)
|| !original.closed.as_ref().is_some_and(|closed| {
closed.outcome == maka_agent_facts::accounting::Outcome::Success
&& closed.diagnostic.is_none()
})
{
return Err(invalid(
"summary repair requires the current successful Summary closure",
));
}
let protocol: maka_agent_facts::context::ModelClosureProtocol = serde_json::from_value(
original
.closed
.as_ref()
.expect("validated closure")
.protocol
.clone(),
)?;
if !matches!(
protocol.summary,
Some(maka_agent_facts::context::SummaryResult::RejectedToolContent)
) {
return Err(invalid(
"summary repair requires original rejected tool content",
));
}
let frozen = self::request(c, view.run, original.step)?;
if frozen.accounting.purpose != ModelPurpose::Summary
|| frozen.summary_repair_of.is_some()
|| incoming.accounting.purpose != ModelPurpose::Summary
|| incoming.source_capture != frozen.source_capture
|| incoming.source_digest != frozen.source_digest
|| incoming.effective_source_digest != frozen.effective_source_digest
|| incoming.composition != frozen.composition
|| incoming.provenance != frozen.provenance
|| incoming.tool_contracts != frozen.tool_contracts
|| incoming.projection != frozen.projection
|| incoming.adjudications != frozen.adjudications
|| incoming.steering != frozen.steering
{
return Err(invalid(
"summary repair must preserve its one original frozen source cut",
));
}
}
Ok(fallback)
}
fn validate_cell_recovery(
c: &Connection,
view: &RunView,
cell: maka_agent_facts::cells::CellId,
result: &ContentRef,
) -> Result<(), StoreError> {
use maka_agent_facts::{
cells::CellStatus,
tool_output::{AcceptedToolResult, CellFinalEvidence},
};
pin(c, view.run, result)?;
let accepted: AcceptedToolResult = decode(c, result)?;
let AcceptedToolResult::RecoveredCell {
cell: original,
evidence,
} = accepted
else {
return Err(invalid(
"Cell recovery acceptance requires the shared recovered-Cell result codec",
));
};
if original != cell {
return Err(invalid("Cell recovery result belongs to another Cell"));
}
let source = view
.cells
.get(&cell)
.ok_or_else(|| invalid("Cell recovery has no original terminal Cell source"))?;
let matches_source = match (&source.status, &evidence) {
(
CellStatus::Completed {
result: original, ..
},
CellFinalEvidence::Completed { result },
) => original == result,
(
CellStatus::Interrupted { report: original },
CellFinalEvidence::Interrupted { report },
) => original == report,
_ => false,
};
if !matches_source {
return Err(invalid(
"Cell recovery result differs from the original canonical terminal evidence",
));
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn record_known(
c: &Connection,
batch: &BatchBlobs,
spec: &RunSpec,
owner_json: &str,
admission_sequence: Option<u64>,
fact: &RecordedFact,
precomputed: Option<&ContentBlob>,
attempts: Option<&std::collections::BTreeMap<ModelAttemptId, Attempt>>,
cells: Option<
&std::collections::BTreeMap<
maka_agent_facts::cells::CellId,
maka_agent_facts::cells::CellView,
>,
>,
history_cursor: &mut Option<crate::session_history::HistoryBatchCursor>,
) -> Result<u64, StoreError> {
let owned_body;
let body = match precomputed {
Some(blob) => blob,
None => {
owned_body = ContentBlob::json(fact)?;
&owned_body
}
};
let id = put(c, body)?;
c.prepare_cached("INSERT INTO agent_facts(id,run,revision,schema_version,at,body_content_id) VALUES(?,?,?,?,?,?)")?.execute(params![fact.id.to_string(),fact.run.to_string(),signed(fact.revision)?,fact.schema_version,fact.at.0,id])?;
let sequence = u64::try_from(c.last_insert_rowid())
.map_err(|_| invalid("canonical fact sequence exceeds u64"))?;
let admission_seq = admission_sequence.unwrap_or(sequence);
pin_id(c, fact.run, id)?;
for reference in fact.fact.content_refs() {
pin_cached(c, batch, fact.run, reference)?;
}
if let Fact::ExternalTaskPrepared { descriptor, .. }
| Fact::ExternalTaskBound { descriptor, .. } = &fact.fact
&& let Some(instr_ref) = external_task_instructions_ref(c, fact.run, descriptor)?
{
pin_cached(c, batch, fact.run, &instr_ref)?;
}
if let Fact::StepPrepared { step, request, .. }
| Fact::ProactiveSummaryPrepared { step, request, .. } = &fact.fact
{
c.prepare_cached("INSERT INTO agent_request_specs(step,run,content_id) VALUES(?,?,?) ON CONFLICT(step) DO NOTHING")?.execute(params![step.to_string(),fact.run.to_string(),content_id_cached(c,batch,request)?])?;
}
if let Fact::ModelAttemptPrepared { attempt, step }
| Fact::ProactiveSummaryPrepared { attempt, step, .. } = &fact.fact
{
c.prepare_cached("INSERT INTO agent_attempt_ids(attempt,run,step) VALUES(?,?,?)")?
.execute(params![
attempt.to_string(),
fact.run.to_string(),
step.to_string()
])?;
}
model_item(c, fact)?;
answer_part(c, fact)?;
if let Fact::ToolOriginalBound { tool, reference }
| Fact::HostToolResultRecorded {
tool, reference, ..
} = &fact.fact
{
let key = fold::tool_key(tool);
let encoded = serde_json::to_string(reference)?;
let previous: Option<String> = c
.prepare_cached(
"SELECT reference_json FROM agent_operation_pins WHERE run=? AND tool=?",
)?
.query_row(params![fact.run.to_string(), key], |r| r.get(0))
.optional()?;
if previous.as_ref().is_some_and(|old| old != &encoded) {
return Err(StoreError::EventConflict);
}
c.prepare_cached("INSERT INTO agent_operation_pins(run,tool,reference_json) VALUES(?,?,?) ON CONFLICT DO NOTHING")?.execute(params![fact.run.to_string(),key,encoded])?;
}
crate::session_history::index_new_fact(
c,
spec,
owner_json,
admission_seq,
sequence,
&body.reference.digest,
fact,
attempts,
cells,
history_cursor,
)?;
Ok(sequence)
}
fn fact_sequence(c: &Connection, fact: &RecordedFact) -> Result<u64, StoreError> {
c.prepare_cached("SELECT sequence FROM agent_facts WHERE id=? AND run=?")?
.query_row(params![fact.id.to_string(), fact.run.to_string()], |row| {
column_u64(row, 0)
})
.map_err(StoreError::from)
}
fn index_non_recall(
c: &Connection,
spec: &RunSpec,
fact: &RecordedFact,
sequence: u64,
) -> Result<(), StoreError> {
crate::session_catalog::index_fact(c, spec, fact, sequence)?;
crate::diagnostics::index_fact(c, spec, fact, sequence)?;
Ok(())
}
fn tool_write_after_model_cleanup(
c: &Connection,
run: RunId,
expected: Head,
actual: Head,
changes: &[Change],
) -> Result<bool, StoreError> {
if expected.control_version != actual.control_version
|| actual.revision.checked_sub(1) != Some(expected.revision)
{
return Ok(false);
}
let attempt = match changes {
[
Change {
fact:
Fact::ToolDecided {
tool,
decision: ToolDecision::Approved { .. },
}
| Fact::ToolAdmitted { tool },
..
},
] => tool.attempt,
[
Change {
fact: Fact::ApprovalConsumed { tool, .. },
..
},
Change {
fact: Fact::ToolAdmitted { tool: admitted },
..
},
] if tool == admitted => tool.attempt,
pair_changes if !pair_changes.is_empty() && pair_changes.len().is_multiple_of(2) => {
let mut batch_attempt = None;
for pair in pair_changes.as_chunks::<2>().0 {
let [
Change {
fact:
Fact::ToolDecided {
tool,
decision: ToolDecision::Approved { approval: None, .. },
},
..
},
Change {
fact: Fact::ToolAdmitted { tool: admitted },
..
},
] = pair
else {
return Ok(false);
};
if tool != admitted {
return Ok(false);
}
match batch_attempt {
None => batch_attempt = Some(tool.attempt),
Some(prev) if prev != tool.attempt => return Ok(false),
_ => {}
}
}
batch_attempt.expect("non-empty paired tool admission")
}
_ => return Ok(false),
};
// Confirmed cleanup can resolve an old obligation, but cannot revoke a
// tool's authority. Any other intervening fact still invalidates the plan.
Ok(matches!(
history(c, run, expected.revision, 1)?.as_slice(),
[RecordedFact {
revision,
fact: Fact::ModelCleanupObserved {
attempt: cleaned,
cleanup: maka_plugin_core::operation::OperationCleanup::Confirmed,
},
..
}] if *revision == actual.revision && *cleaned == attempt
))
}
pub(crate) fn fact(
c: &Connection,
run: RunId,
id: FactId,
) -> Result<Option<RecordedFact>, StoreError> {
let raw:Option<(u32,Vec<u8>)>=c.prepare_cached("SELECT f.schema_version,maka_content_bytes(c.payload,c.encoding) FROM agent_facts f JOIN contents c ON c.id=f.body_content_id WHERE f.id=? AND f.run=?")?.query_row(params![id.to_string(),run.to_string()],|r|Ok((r.get(0)?,r.get(1)?))).optional()?;
raw.map(|(v, bytes)| {
version(v)?;
let fact: RecordedFact = serde_json::from_slice(&bytes)?;
version(fact.schema_version)?;
if fact.id != id || fact.run != run {
return Err(invalid("canonical fact identity mismatch"));
}
Ok(fact)
})
.transpose()
}
pub(crate) fn admit(c: &Connection, admission: Admission) -> Result<(Commit, bool), StoreError> {
let blob = ContentBlob::json(&admission.spec)?;
let expected = Fact::RunAdmitted {
spec: blob.reference.clone(),
};
if let Some(original) = fact(c, admission.run, admission.id)? {
if original.fact != expected {
return Err(StoreError::EventConflict);
}
let view = load(c, admission.run, &[], false)?;
if let Some(consume) = &admission.queue {
crate::queue::consume(
c,
consume,
&view.spec,
admission.run,
original.id,
original.at,
)?;
}
return Ok((
Commit {
head: Head::from(&view),
facts: vec![original],
},
false,
));
}
let mut view = RunView::admitted(admission.run, admission.spec)?;
view.spec.permission_basis.validate().map_err(invalid)?;
if view.spec.session_id.is_empty()
|| view.spec.turn_id.is_empty()
|| view.spec.workspace.is_empty()
{
return Err(invalid("missing immutable Run admission basis"));
}
if matches!(view.spec.origin, RunOrigin::Local)
&& view.spec.budget_basis.is_some()
&& admission.guard.is_none()
{
return Err(invalid(
"native budget admission basis requires its live admission guard",
));
}
if matches!(view.spec.origin, RunOrigin::Local) {
// Late receipts and a successor admission share the same Root transaction.
let prior: Option<String> = c.prepare_cached(
"SELECT run FROM (SELECT run,terminal,cancelled_by_risk FROM agent_runs WHERE session=? ORDER BY admission_sequence DESC LIMIT 1)
WHERE terminal=json_quote('failed') OR cancelled_by_risk=1",
)?.query_row([&view.spec.session_id], |row| row.get(0)).optional()?;
if let Some(prior) = prior
&& load(c, identity(prior)?, &[], false)?.blocks_followup()
{
return Err(invalid("previous Run has unsettled original operations"));
}
}
if let Some(guard) = &admission.guard {
guard.validate(c, admission.run, &view.spec)?;
}
let batch_blobs = insert_blobs(c, &admission.contents)?;
let id = put(c, &blob)?;
let owner_json = serde_json::to_string(&view.spec.owner)?;
c.prepare_cached("INSERT INTO agent_run_specs(run,schema_version,owner,session,spec_content_id) VALUES(?,?,?,?,?)")?.execute(params![admission.run.to_string(),SCHEMA_VERSION,&owner_json,view.spec.session_id,id])?;
for reference in view.spec.content_refs() {
pin_cached(c, &batch_blobs, view.run, reference)?;
}
let recorded = RecordedFact {
schema_version: SCHEMA_VERSION,
id: admission.id,
run: admission.run,
revision: 1,
at: admission.at,
fact: expected,
};
view.apply(&recorded)?;
let mut history_cursor = None;
let sequence = record_known(
c,
&batch_blobs,
&view.spec,
&owner_json,
None,
&recorded,
None,
Some(&view.attempts),
Some(&view.cells),
&mut history_cursor,
)?;
crate::artifacts::admit(c, view.run, &view.spec, recorded.id)?;
crate::session_history::index_retained_known(
c,
&view.spec.owner,
&view.spec.session_id,
&recorded,
sequence,
None,
)?;
crate::session_history::admit_continuation(c, &view, &recorded)?;
if let Some(consume) = &admission.queue {
crate::queue::consume(
c,
consume,
&view.spec,
admission.run,
admission.id,
admission.at,
)?;
}
crate::session_catalog::index_batch(
c,
&view.spec,
&owner_json,
sequence,
&[(&recorded, sequence)],
)?;
persist_known(c, &view, sequence, &owner_json)?;
crate::usage::index_fact(c, &view.spec, &recorded, sequence)?;
// A compaction or handoff continues earlier work; what waits after a user
// Stop waits for a Run that starts new work.
if matches!(view.spec.origin, RunOrigin::Local)
&& matches!(
view.spec.trigger,
Trigger::Message { .. }
| Trigger::Goal { .. }
| Trigger::Schedule { .. }
| Trigger::Continuation { .. }
)
{
crate::queue::deliver_held(c, &view, admission.id, admission.at)?;
}
Ok((
Commit {
head: Head::from(&view),
facts: vec![recorded],
},
true,
))
}
pub(crate) struct AppendMaterial<'a> {
pub contents: &'a [ContentBlob],
pub precomputed_facts: &'a [(u64, ContentBlob)],
pub artifacts: &'a crate::artifacts::ArtifactBatch,
}
pub(crate) fn append(
c: &Connection,
run: RunId,
expected: Option<Head>,
changes: &[Change],
material: AppendMaterial<'_>,
mode: &Mode,
steering: Option<&crate::queue::Consume>,
) -> Result<(Commit, bool), StoreError> {
let AppendMaterial {
contents,
precomputed_facts,
artifacts,
} = material;
if changes.is_empty() {
return Err(invalid("empty canonical batch"));
}
if let Mode::Driver(claim) = mode {
if claim.purpose() == crate::store::DriverPurpose::LateModelCleanup {
let empty_artifacts = match artifacts {
crate::artifacts::ArtifactBatch::Pending(items) => items.is_empty(),
crate::artifacts::ArtifactBatch::Prepared(items) => items.is_empty(),
};
if !empty_artifacts || !contents.is_empty() || steering.is_some() {
return Err(invalid(
"model cleanup claim cannot publish material or steering",
));
}
for change in changes {
let Fact::ModelCleanupObserved {
attempt,
cleanup: maka_plugin_core::operation::OperationCleanup::Confirmed,
} = &change.fact
else {
return Err(invalid(
"model cleanup claim accepts only original admitted cleanup proof",
));
};
let admitted = c.prepare_cached("SELECT 1 FROM agent_attempts WHERE run=? AND key=? AND json_extract(body,'$.admission') IS NOT NULL")?
.query_row(params![run.to_string(), attempt.to_string()], |_| Ok(())).optional()?.is_some();
if !admitted {
return Err(invalid("model cleanup has no original admission"));
}
}
}
if let crate::store::DriverPurpose::LateExternalCleanup { task } = claim.purpose() {
let empty_artifacts = match artifacts {
crate::artifacts::ArtifactBatch::Pending(items) => items.is_empty(),
crate::artifacts::ArtifactBatch::Prepared(items) => items.is_empty(),
};
if !empty_artifacts {
return Err(invalid("cleanup claim cannot publish artifacts"));
}
if !contents.is_empty() || steering.is_some() || changes.iter().any(|change| !matches!(&change.fact,
Fact::ExternalTaskCleanupObserved { task: actual, cleanup: maka_plugin_core::operation::OperationCleanup::Confirmed } if *actual == task
) && !matches!(&change.fact, Fact::ExternalTaskCleanupDeferred { task: actual, .. } if *actual == task)) {
return Err(invalid("cleanup claim accepts only its original task proof or defer"));
}
}
}
if matches!(mode, Mode::Historical)
&& (changes.len() != 1
|| !matches!(
changes[0].fact,
Fact::RunTerminated {
terminal: Terminal::Completed,
..
}
))
{
return Err(invalid(
"historical ingress only completes one installed snapshot",
));
}
let mut seen = BTreeSet::new();
let mut originals = Vec::new();
for change in changes {
if !seen.insert(change.id) {
return Err(StoreError::EventConflict);
}
match mode {
Mode::Control
if !matches!(
change.fact,
Fact::StopRequested { .. }
| Fact::ApprovalRecorded { .. }
| Fact::ApprovalRefused { .. }
| Fact::Cell {
event: maka_agent_facts::cells::CellEvent::ChildApprovalRecorded { .. }
}
) =>
{
return Err(invalid("control ingress cannot admit or advance work"));
}
Mode::Late if !change.fact.is_late() => {
return Err(invalid("observation ingress cannot admit or advance work"));
}
_ => {}
}
if let Some(original) = fact(c, run, change.id)? {
if original.fact != change.fact {
return Err(StoreError::EventConflict);
}
originals.push(original);
}
}
for change in changes {
if let Fact::ApprovalConsumed { approval: _, tool } = &change.fact
&& !changes.iter().any(|change| matches!(&change.fact,Fact::ToolAdmitted { tool:admitted } if admitted==tool)) {
return Err(invalid("single-use approval consumption requires same-batch tool admission"));
}
}
let targets: Vec<_> = changes.iter().map(|c| &c.fact).collect();
let (view, admission_sequence) = load_with_admission(c, run, &targets, false)?;
if matches!(mode, Mode::Historical)
&& (matches!(view.spec.origin, RunOrigin::Local)
|| !matches!(view.spec.backend, BackendSpec::Historical { .. }))
{
return Err(invalid(
"historical ingress requires an imported or forked snapshot backend",
));
}
if originals.len() == changes.len() {
if let Some(consume) = steering {
let steps: Vec<_> = originals
.iter()
.filter_map(|recorded| match &recorded.fact {
Fact::StepPrepared { step, request, .. } => Some((recorded, *step, request)),
_ => None,
})
.collect();
if steps.len() != 1 {
return Err(invalid(
"steering replay requires one original StepPrepared",
));
}
let (recorded, step, request) = steps[0];
crate::queue::consume_steering(
c,
consume,
run,
step,
request,
recorded.id,
recorded.at,
)?;
}
return Ok((
Commit {
head: Head::from(&view),
facts: originals,
},
false,
));
}
if !originals.is_empty() {
return Err(StoreError::EventConflict);
}
if let Some(expected) = expected {
let actual = Head::from(&view);
if actual != expected
&& !(matches!(mode, Mode::Driver(claim) if claim.purpose() == crate::store::DriverPurpose::Business)
&& tool_write_after_model_cleanup(c, run, expected, actual, changes)?)
{
return Err(StoreError::RevisionConflict {
expected: serde_json::to_string(&expected)?,
actual: serde_json::to_string(&actual)?,
});
}
}
if matches!(mode, Mode::Driver(_)) && !matches!(view.spec.origin, RunOrigin::Local) {
return Err(invalid(
"historical provenance cannot claim local execution",
));
}
if view.terminal.is_some()
&& matches!(mode, Mode::Driver(claim) if claim.purpose() == crate::store::DriverPurpose::Business)
{
return Err(invalid("terminal run has no business driver authority"));
}
if expected.is_none()
&& matches!(mode, Mode::Driver(_))
&& changes
.iter()
.any(|change| matches!(change.fact, Fact::ToolResultAccepted { .. }))
{
let fenced = view.stopped
|| view.cancelled_by_risk
|| view.finish_requested()
|| view.recovery_failure().is_some()
|| !view.blockers.is_empty()
|| changes.iter().any(|change| match &change.fact {
Fact::ToolResultAccepted { tool, .. } => view.model_steered(tool.attempt),
_ => false,
});
if fenced {
return Err(invalid(
"coalesced tool acceptance fenced by live control state",
));
}
}
crate::external_publication::validate_batch(&view, changes)?;
commit_changes(
c,
run,
view,
admission_sequence,
changes,
AppendMaterial {
contents,
precomputed_facts,
artifacts,
},
steering,
crate::cells::CellApprovalValidation::Check,
)
}
pub(crate) fn append_cell_child_admission(
c: &Connection,
run: RunId,
admission: &crate::store::CellChildAdmission,
changes: &[Change],
material: AppendMaterial<'_>,
) -> Result<(crate::store::CellChildAdmissionOutcome, bool), StoreError> {
use maka_agent_facts::cells::{CellEvent, CellStatus};
let is_prepare = match changes {
[] => return Err(invalid("empty canonical batch")),
[change] => match &change.fact {
Fact::Cell {
event:
CellEvent::ChildPrepared {
cell,
operation,
input,
..
},
} if *cell == admission.cell
&& *operation == admission.operation
&& *input == admission.input =>
{
true
}
_ => {
return Err(invalid(
"narrow Cell child admission accepts only matching ChildPrepared or ChildAdmitted batches",
));
}
},
[first, middle @ .., last] => {
let valid_first = matches!(
&first.fact,
Fact::Cell {
event: CellEvent::ChildDisplayRecorded { cell, operation, .. }
} if *cell == admission.cell && *operation == admission.operation
);
let valid_middle = middle.iter().all(|change| {
matches!(
&change.fact,
Fact::Cell {
event: CellEvent::ChildApprovalConsumed { cell, operation, .. }
} if *cell == admission.cell && *operation == admission.operation
)
});
let valid_last = matches!(
&last.fact,
Fact::Cell {
event: CellEvent::ChildAdmitted { cell, operation }
} if *cell == admission.cell && *operation == admission.operation
);
if !(valid_first && valid_middle && valid_last) {
return Err(invalid(
"narrow Cell child admission accepts only matching ChildPrepared or ChildAdmitted batches",
));
}
false
}
};
let mut seen = BTreeSet::new();
let mut originals = Vec::new();
for change in changes {
if !seen.insert(change.id) {
return Err(StoreError::EventConflict);
}
if let Some(original) = fact(c, run, change.id)? {
if original.fact != change.fact {
return Err(StoreError::EventConflict);
}
originals.push(original);
}
}
let targets: Vec<_> = changes.iter().map(|c| &c.fact).collect();
let (view, admission_sequence) = load_with_admission(c, run, &targets, false)?;
if originals.len() == changes.len() {
return Ok((
crate::store::CellChildAdmissionOutcome::Committed(Commit {
head: Head::from(&view),
facts: originals,
}),
false,
));
}
if !originals.is_empty() {
return Err(StoreError::EventConflict);
}
if !matches!(view.spec.origin, RunOrigin::Local) {
return Err(invalid(
"historical provenance cannot claim local execution",
));
}
if view.stopped || view.terminal.is_some() {
return Ok((
crate::store::CellChildAdmissionOutcome::Rejected("Cell admission is stopped".into()),
false,
));
}
match view.check_effect_admission() {
Ok(()) => {}
Err(StoreError::InvalidTransition(reason)) => {
return Ok((
crate::store::CellChildAdmissionOutcome::Rejected(format!(
"Cell admission is quarantined: {reason}"
)),
false,
));
}
Err(error) => return Err(error),
}
let cell_view = view
.cells
.get(&admission.cell)
.ok_or_else(|| invalid("Cell has not started"))?;
if cell_view.owner != admission.owner {
return Err(invalid(
"Cell belongs to a different original provider call",
));
}
if !matches!(cell_view.status, CellStatus::Running) {
return Ok((
crate::store::CellChildAdmissionOutcome::Rejected(
"Cell child admission is closed".into(),
),
false,
));
}
if cell_view.finish_requested() {
return Ok((
crate::store::CellChildAdmissionOutcome::Rejected(
"Cell finish outcome prevents fresh child admission".into(),
),
false,
));
}
if !is_prepare {
let child = cell_view
.children
.get(&admission.operation)
.ok_or_else(|| invalid("Cell child not prepared"))?;
if child.input != admission.input {
return Err(invalid("Cell child original input changed"));
}
if child.admitted || child.rejected.is_some() {
return Ok((
crate::store::CellChildAdmissionOutcome::Rejected(
"Cell child is no longer awaiting admission".into(),
),
false,
));
}
let consumed: BTreeSet<_> = changes
.iter()
.filter_map(|change| match &change.fact {
Fact::Cell {
event: CellEvent::ChildApprovalConsumed { approval, .. },
} => Some(*approval),
_ => None,
})
.collect();
for approval in child.approvals.keys() {
if !consumed.contains(approval) {
return Ok((
crate::store::CellChildAdmissionOutcome::Rejected(
"Cell child admission requires same-batch consumption of every original approval"
.into(),
),
false,
));
}
}
for approval in &consumed {
match crate::interactions::check_cell_approval_with_view(
c,
run,
&view,
cell_view,
admission.operation,
*approval,
)? {
crate::interactions::CellApprovalDecision::Authorized => {}
crate::interactions::CellApprovalDecision::Refused(reason) => {
return Ok((
crate::store::CellChildAdmissionOutcome::Rejected(reason),
false,
));
}
}
}
}
let (commit, changed) = commit_changes(
c,
run,
view,
admission_sequence,
changes,
material,
None,
crate::cells::CellApprovalValidation::AlreadyVerified,
)?;
Ok((
crate::store::CellChildAdmissionOutcome::Committed(commit),
changed,
))
}
#[expect(
clippy::too_many_arguments,
reason = "Canonical commit helper threads precomputed batch material, optional steering consumption, and approval validation mode"
)]
fn commit_changes(
c: &Connection,
run: RunId,
mut view: RunView,
admission_sequence: u64,
changes: &[Change],
material: AppendMaterial<'_>,
steering: Option<&crate::queue::Consume>,
cell_approval_validation: crate::cells::CellApprovalValidation,
) -> Result<(Commit, bool), StoreError> {
let AppendMaterial {
contents,
precomputed_facts,
artifacts,
} = material;
let batch_blobs = insert_blobs(c, contents)?;
let owner_json = serde_json::to_string(&view.spec.owner)?;
let mut facts = Vec::with_capacity(changes.len());
let mut sequences = Vec::with_capacity(changes.len());
let mut persisted_external = Vec::with_capacity(changes.len());
let mut dirty_cells = BTreeSet::new();
let mut consumed_steering = None;
let mut history_cursor = None;
for (index, change) in changes.iter().enumerate() {
if change.fact.is_admission() {
view.check_effect_admission()?;
}
model_evidence::validate_control(c, &view, &change.fact)?;
if let Fact::BlockerResolved { blocker, .. } = &change.fact {
view.validate_blocker_resolution(*blocker)?;
}
if let Fact::ContextCompacted { baseline } = &change.fact {
// A deferred checkpoint can become visible to the next Run once
// this same commit closes the current Run.
let saving_for_next_run = matches!(
&changes[index + 1..],
[next] if next.at == change.at && compaction::ends_run(&next.fact)
);
compaction::validate(c, &view, baseline, change.at, saving_for_next_run)?;
}
if let Fact::ApprovalRecorded {
approval,
tool,
input_digest,
..
} = &change.fact
{
crate::interactions::validate_approval(c, run, *approval, tool, input_digest)?;
}
if let Fact::ApprovalRefused {
approval,
tool,
outcome,
} = &change.fact
{
crate::interactions::validate_approval_refusal(c, run, *approval, tool, outcome)?;
}
if matches!(
change.fact,
Fact::ApprovalConsumed { .. } | Fact::ToolAdmitted { .. }
) {
let check = now()?;
let approval = match &change.fact {
Fact::ApprovalConsumed { approval, .. } => Some(*approval),
Fact::ToolAdmitted { tool } => {
view.tools
.get(&fold::tool_key(tool))
.and_then(|tool| match &tool.decision {
Some(ToolDecision::Approved { approval, .. }) => *approval,
_ => None,
})
}
_ => None,
};
if approval
.and_then(|id| view.approvals.get(&id))
.is_some_and(|grant| grant.expires_at.is_some_and(|expiry| check >= expiry))
{
return Err(invalid("single-use approval expired at SQL admission"));
}
}
if let Fact::ToolAdmitted { tool } = &change.fact
&& let Some(ToolDecision::Approved {
input,
resources,
approval: Some(approval),
..
}) = view
.tools
.get(&fold::tool_key(tool))
.and_then(|tool| tool.decision.as_ref())
{
if !changes.iter().any(|change|matches!(&change.fact,Fact::ApprovalConsumed{approval:consumed,tool:target} if consumed==approval && target==tool)){
return Err(invalid("approved tool requires its exact same-batch consumption"));
}
crate::interactions::consume(c, run, tool, *approval, input, resources)?;
}
if let Fact::ModelAttemptPrepared { attempt, .. }
| Fact::ProactiveSummaryPrepared { attempt, .. } = &change.fact
&& c.prepare_cached("SELECT 1 FROM agent_attempt_ids WHERE attempt=?")?
.query_row([attempt.to_string()], |r| r.get::<_, i64>(0))
.optional()?
.is_some()
{
return Err(StoreError::EventConflict);
}
if matches!(change.fact, Fact::RunAdmitted { .. }) {
return Err(invalid("Run admission is immutable"));
}
if let Fact::StepPrepared {
step,
request,
adjudications,
} = &change.fact
{
let (prepared, fallback) =
validate_request(c, &batch_blobs, &view, *step, request, adjudications, false)?;
if let Some(consume) = steering {
if prepared.summary_repair_of.is_some() || fallback.is_some() {
return Err(invalid(
"summary repair/fallback cannot consume new steering input",
));
}
if consumed_steering.is_some() {
return Err(invalid("one steering consume requires one StepPrepared"));
}
crate::queue::consume_steering(
c, consume, run, *step, request, change.id, change.at,
)?;
consumed_steering = Some(change.id);
}
}
if let Fact::ProactiveSummaryPrepared { step, request, .. } = &change.fact {
validate_request(c, &batch_blobs, &view, *step, request, &[], true)?;
}
if let Fact::ToolResultAccepted {
result,
outcome: AcceptedResult::CellRecovered { cell },
..
} = &change.fact
{
validate_cell_recovery(c, &view, *cell, result)?;
}
validate_external_final_message(c, &view, &change.fact)?;
validate_private_provider_effect(c, &view, &change.fact)?;
let recorded = RecordedFact {
schema_version: SCHEMA_VERSION,
id: change.id,
run,
revision: view
.revision
.checked_add(1)
.ok_or_else(|| invalid("Run revision overflow"))?,
at: change.at,
fact: change.fact.clone(),
};
if matches!(&recorded.fact, Fact::Cell { .. }) {
crate::cells::validate_event(c, &view, &recorded, changes, cell_approval_validation)?;
}
view.apply(&recorded)?;
let precomputed = precomputed_facts
.get(index)
.filter(|(rev, _)| *rev == recorded.revision)
.map(|(_, blob)| blob);
let sequence = record_known(
c,
&batch_blobs,
&view.spec,
&owner_json,
Some(admission_sequence),
&recorded,
precomputed,
Some(&view.attempts),
Some(&view.cells),
&mut history_cursor,
)?;
match &recorded.fact {
Fact::StopRequested { diagnostic, .. } => {
crate::queue::stop_completions(c, &view.spec.session_id, run, recorded.at)?;
if diagnostic == crate::queue::GOAL_CONTROL_STOP {
crate::queue::release_steering(c, &view.spec.session_id, run, recorded.at)?;
}
}
Fact::RunTerminated { .. } if matches!(view.spec.origin, RunOrigin::Local) => {
crate::queue::release_steering(c, &view.spec.session_id, run, recorded.at)?;
}
_ => {}
}
model_evidence::validate_partial(c, &view, &recorded)?;
model_evidence::validate_source_failure(c, &view, &recorded)?;
if matches!(recorded.fact, Fact::ExternalPublication { .. }) {
crate::external_publication::persist(c, run, &recorded)?;
}
if matches!(recorded.fact, Fact::ExternalSteering { .. }) {
crate::external_steering::persist(c, run, &recorded)?;
}
let external = if let Fact::ExternalEffect { event } = &recorded.fact {
Some(crate::external_effects::persist(
c,
run,
recorded.revision,
event,
)?)
} else {
None
};
if let Fact::Cell { event } = &recorded.fact {
crate::cells::project_side_tables(
c,
&view.spec.session_id,
Some(run),
recorded.id,
event,
Some(sequence),
)?;
dirty_cells.insert(event.cell());
} else if matches!(&recorded.fact, Fact::ContextCompacted { .. })
&& matches!(&view.spec.origin, RunOrigin::Local)
{
crate::cells::clear_session_loaded_tools(c, &view.spec.session_id)?;
}
if matches!(recorded.fact, Fact::ToolsLoaded { .. }) {
crate::cells::apply_tools_loaded(c, &view.spec.session_id, &recorded, changes)?;
}
facts.push(recorded);
sequences.push(sequence);
persisted_external.push(external);
}
for cell_id in dirty_cells {
let cell_view = view
.cells
.get(&cell_id)
.ok_or_else(|| invalid("dirty Cell missing from folded Run view"))?;
crate::cells::persist_view(c, &view.spec.session_id, Some(run), cell_view)?;
}
if steering.is_some() && consumed_steering.is_none() {
return Err(invalid("steering consumption requires StepPrepared"));
}
crate::artifacts::append(c, run, &facts, artifacts)?;
let mut catalog_items = Vec::with_capacity(facts.len());
for ((fact, &sequence), external) in facts
.iter()
.zip(sequences.iter())
.zip(persisted_external.iter())
{
crate::session_history::index_retained_known(
c,
&view.spec.owner,
&view.spec.session_id,
fact,
sequence,
external.as_ref(),
)?;
catalog_items.push((fact, sequence));
}
crate::session_catalog::index_batch(
c,
&view.spec,
&owner_json,
admission_sequence,
&catalog_items,
)?;
persist_known(c, &view, admission_sequence, &owner_json)?;
for ((fact, &sequence), external) in facts
.iter()
.zip(sequences.iter())
.zip(persisted_external.iter())
{
crate::usage::index_fact_with_external(c, &view.spec, fact, sequence, external.as_ref())?;
}
Ok((
Commit {
head: Head::from(&view),
facts,
},
true,
))
}
pub(crate) fn history(
c: &Connection,
run: RunId,
after: u64,
count: u32,
) -> Result<Vec<RecordedFact>, StoreError> {
let mut statement=c.prepare_cached("SELECT f.schema_version,maka_content_bytes(c.payload,c.encoding) FROM agent_facts f JOIN contents c ON c.id=f.body_content_id WHERE f.run=? AND f.revision>? ORDER BY f.revision LIMIT ?")?;
let mut rows = statement.query(params![run.to_string(), signed(after)?, limit(count)?])?;
let mut facts = Vec::new();
while let Some(row) = rows.next()? {
version(row.get(0)?)?;
let fact: RecordedFact = serde_json::from_slice(&row.get::<_, Vec<u8>>(1)?)?;
version(fact.schema_version)?;
if fact.run != run {
return Err(invalid("canonical fact belongs to another Run"));
}
facts.push(fact);
}
Ok(facts)
}
pub(crate) fn tool_admission_revision(
c: &Connection,
run: RunId,
tool: ToolKey,
) -> Result<Option<u64>, StoreError> {
let locator = maka_agent_facts::tool_call::tool_use_id(run, &fold::tool_key(&tool));
let id: Option<String> = c
.prepare_cached(
"SELECT h.fact_id FROM agent_run_specs s
JOIN agent_namespaces ns ON ns.owner=s.owner AND ns.session=s.session
CROSS JOIN agent_session_history h INDEXED BY agent_session_history_tool
WHERE s.run=?1 AND h.namespace_id=ns.id AND h.run=s.run
AND h.tool_use_id=?2 AND h.kind='tool_admitted'",
)?
.query_row(params![run.to_string(), locator], |row| row.get(0))
.optional()?;
let Some(id) = id else { return Ok(None) };
let recorded = fact(c, run, identity(id)?)?
.ok_or_else(|| invalid("tool admission index is missing its canonical fact"))?;
if !matches!(recorded.fact, Fact::ToolAdmitted { tool: admitted } if admitted == tool) {
return Err(invalid("tool admission index names another fact"));
}
Ok(Some(recorded.revision))
}
pub(crate) fn request(c: &Connection, run: RunId, step: StepId) -> Result<RequestSpec, StoreError> {
let bytes: Vec<u8> = c.prepare_cached("SELECT maka_content_bytes(c.payload,c.encoding) FROM agent_request_specs r JOIN contents c ON c.id=r.content_id WHERE r.run=? AND r.step=?")?
.query_row(params![run.to_string(), step.to_string()], |row| row.get(0))?;
let request: RequestSpec = serde_json::from_slice(&bytes)?;
version(request.schema_version)?;
if request.step != step {
return Err(invalid("request Step mismatch"));
}
Ok(request)
}
pub(crate) fn due(
c: &Connection,
at: UnixMillis,
after: Option<(UnixMillis, RunId, WaitId)>,
count: u32,
) -> Result<Vec<(RunId, WaitId, Wait)>, StoreError> {
let mut statement=c.prepare_cached("SELECT w.run,w.key,w.body FROM agent_waits w WHERE w.pending=1 AND w.due_at IS NOT NULL AND w.due_at<=? AND EXISTS(SELECT 1 FROM agent_runs r WHERE r.run=w.run AND r.terminal IS NULL) AND NOT EXISTS(SELECT 1 FROM agent_blockers b WHERE b.run=w.run AND b.pending=1 AND json_extract(b.body,'$.decision') IS NULL AND json_extract(b.body,'$.resolvedBy') IS NULL) AND (? IS NULL OR (w.due_at,w.run,w.key)>(?,?,?)) ORDER BY w.due_at,w.run,w.key LIMIT ?")?;
let mut rows = statement.query(params![
at.0,
after.as_ref().map(|v| v.0.0),
after.as_ref().map(|v| v.0.0),
after.as_ref().map(|v| v.1.to_string()),
after.as_ref().map(|v| v.2.to_string()),
limit(count)?
])?;
let mut waits = Vec::new();
while let Some(row) = rows.next()? {
waits.push((
identity(row.get(0)?)?,
identity(row.get(1)?)?,
serde_json::from_str(&row.get::<_, String>(2)?)?,
));
}
Ok(waits)
}
pub(crate) fn runs(
c: &Connection,
session: String,
after: Option<RunId>,
count: u32,
) -> Result<Vec<RunId>, StoreError> {
let mut statement=c.prepare_cached("SELECT run FROM agent_runs WHERE session=? AND admission_sequence>coalesce((SELECT admission_sequence FROM agent_runs WHERE run=?),0) ORDER BY admission_sequence LIMIT ?")?;
let mut rows = statement.query(params![
session,
after.map(|v| v.to_string()),
limit(count)?
])?;
let mut runs = Vec::new();
while let Some(row) = rows.next()? {
runs.push(identity(row.get(0)?)?);
}
Ok(runs)
}
pub(crate) fn ensure_headers(c: &Connection, owner: &RunOwner) -> Result<bool, StoreError> {
let owner = serde_json::to_string(owner)?;
let mut after = (String::new(), String::new());
let mut changed = false;
loop {
let page: Vec<(String, String)> = c.prepare_cached(
"SELECT s.session,s.run FROM agent_run_specs s LEFT JOIN agent_runs r ON r.run=s.run WHERE s.owner=?1 AND (s.session,s.run)>(?2,?3) AND (r.run IS NULL OR r.schema_version<>?4) ORDER BY s.session,s.run LIMIT 128"
)?.query_map(params![owner, after.0, after.1, HEADER_SCHEMA_VERSION], |row| Ok((row.get(0)?, row.get(1)?)))?
.collect::<Result<_, _>>()?;
if page.is_empty() {
return Ok(changed);
}
for (session, run) in page {
rebuild(c, identity(run.clone())?)?;
after = (session, run);
changed = true;
}
}
}
pub(crate) fn rebuild(c: &Connection, run: RunId) -> Result<Head, StoreError> {
let (spec, spec_ref) = spec(c, run)?;
for table in [
"agent_diagnostics",
"agent_diagnostic_coverage",
"agent_external_publication_items",
"agent_external_publications",
"agent_steps",
"agent_attempts",
"agent_tools",
"agent_approvals",
"agent_blockers",
"agent_waits",
"agent_runs",
"agent_answer_parts",
"agent_model_items",
"agent_external_effects",
"agent_external_steering",
] {
c.execute(
&format!("DELETE FROM {table} WHERE run=?"),
[run.to_string()],
)?;
}
crate::cells::clear_run(c, run)?;
let mut view = RunView::admitted(run, spec)?;
let mut cursor = 0;
loop {
let page = history(c, run, cursor, 128)?;
if page.is_empty() {
break;
}
for recorded in page {
if let Fact::RunAdmitted { spec: reference } = &recorded.fact
&& reference != &spec_ref
{
return Err(StoreError::EventConflict);
}
if let Fact::StepPrepared {
step,
request,
adjudications,
} = &recorded.fact
{
let empty_blobs = BatchBlobs::new();
validate_request(c, &empty_blobs, &view, *step, request, adjudications, false)?;
}
if let Fact::ProactiveSummaryPrepared { step, request, .. } = &recorded.fact {
let empty_blobs = BatchBlobs::new();
validate_request(c, &empty_blobs, &view, *step, request, &[], true)?;
}
model_evidence::validate_control(c, &view, &recorded.fact)?;
model_evidence::validate_partial(c, &view, &recorded)?;
model_evidence::validate_source_failure(c, &view, &recorded)?;
if let Fact::ContextCompacted { baseline } = &recorded.fact {
let saving_for_next_run = history(c, run, recorded.revision, 1)?
.first()
.is_some_and(|next| next.at == recorded.at && compaction::ends_run(&next.fact));
compaction::validate(c, &view, baseline, recorded.at, saving_for_next_run)?;
}
validate_external_final_message(c, &view, &recorded.fact)?;
validate_private_provider_effect(c, &view, &recorded.fact)?;
view.apply(&recorded)?;
if matches!(recorded.fact, Fact::ExternalPublication { .. }) {
crate::external_publication::replay(c, run, &recorded)?;
}
crate::cells::replay(c, &view, &recorded)?;
model_item(c, &recorded)?;
answer_part(c, &recorded)?;
if let Fact::ExternalEffect { event } = &recorded.fact {
crate::external_effects::replay(c, run, recorded.revision, event)?;
}
if matches!(recorded.fact, Fact::ExternalSteering { .. }) {
crate::external_steering::replay(c, run, &recorded)?;
}
cursor = recorded.revision;
}
}
if cursor == 0 {
return Err(invalid("canonical Run has no admission fact"));
}
crate::cells::rebuild_run(c, run)?;
crate::artifacts::rebuild(c, run)?;
crate::computer::pin_run(c, run)?;
// Session history has its own ordered rebuild; do not append its prefix again here.
let mut after = 0;
loop {
let page = history(c, run, after, 128)?;
if page.is_empty() {
break;
}
for recorded in page {
let sequence = fact_sequence(c, &recorded)?;
index_non_recall(c, &view.spec, &recorded, sequence)?;
after = recorded.revision;
}
}
persist(c, &view)?;
crate::usage::rebuild_run(c, run)?;
Ok(Head::from(&view))
}
fn answer_part(c: &Connection, fact: &RecordedFact) -> Result<(), StoreError> {
let Fact::ModelObserved {
part:
ModelPart::Text {
text_kind: maka_agent_facts::model::TextKind::Text,
text,
..
},
..
} = &fact.fact
else {
return Ok(());
};
if text.is_empty() {
return Ok(());
}
let start: u64 = c
.prepare_cached("SELECT coalesce(max(end),0) FROM agent_answer_parts WHERE run=?")?
.query_row([fact.run.to_string()], |r| column_u64(r, 0))?;
let blob = ContentBlob::new(text.to_string().into_bytes());
let end = start
.checked_add(blob.reference.bytes)
.filter(|end| *end <= i64::MAX as u64)
.ok_or_else(|| invalid("answer byte offset overflow"))?;
c.prepare_cached(
"INSERT INTO agent_answer_parts(run,revision,start,end,content_id) VALUES(?,?,?,?,?)",
)?
.execute(params![
fact.run.to_string(),
signed(fact.revision)?,
signed(start)?,
signed(end)?,
put(c, &blob)?
])?;
Ok(())
}
pub(crate) fn latest(c: &Connection, session: String) -> Result<Option<RunId>, StoreError> {
let run: Option<String> = c
.prepare_cached(
"SELECT run FROM agent_runs WHERE session=? ORDER BY admission_sequence DESC LIMIT 1",
)?
.query_row([session], |r| r.get(0))
.optional()?;
run.map(identity).transpose()
}
pub(crate) fn ready(
c: &Connection,
owner: RunOwner,
at: UnixMillis,
after: Option<u64>,
count: u32,
cause: crate::store::ReadyCause,
) -> Result<Vec<crate::store::ReadyRun>, StoreError> {
let mut statement = c.prepare_cached(&format!("WITH business AS (
SELECT r.run,r.admission_sequence,r.session FROM agent_runs r
WHERE r.owner=?1 AND r.terminal IS NULL AND r.local=1 AND r.admission_sequence>?2
AND (?5=1 OR NOT {AUTHORITY_BLOCKED} OR r.cancelled_by_risk=1 OR (r.stopped=1 AND r.stop_request IS NOT NULL AND r.stop_assessed IS NOT r.stop_request))
AND (EXISTS (SELECT 1 FROM agent_blockers b WHERE b.run=r.run AND b.pending=1 AND json_extract(b.body,'$.decision') IS NULL AND json_extract(b.body,'$.resolvedBy') IS NULL AND json_extract(b.body,'$.reason.kind') IS NOT 'current_authority_unavailable')
OR r.replans != '{{}}'
OR ((r.stopped=0 OR r.stop_request IS NULL OR r.stop_assessed IS NOT r.stop_request
OR r.cancelled_by_risk=1 OR (?5=1 AND {AUTHORITY_BLOCKED})
OR (r.stopped=1 AND json_extract(r.external,'$.admitted')=1
AND json_extract(r.external,'$.closed') IS NULL
AND json_extract(r.external,'$.cleanup.kind') IN ('confirmed','failed'))
OR EXISTS (SELECT 1 FROM agent_cells cell WHERE cell.run=r.run AND cell.pending=1 AND json_extract(maka_content_text(cell.body,cell.body_encoding),'$.status.kind')='running'))
AND (r.stopped=1 OR r.cancelled_by_risk=1 OR r.retry_due_at IS NULL OR r.retry_due_at<=?3)
AND (r.stopped=1 OR r.cancelled_by_risk=1 OR (?5=1 AND {AUTHORITY_BLOCKED}) OR NOT EXISTS (SELECT 1 FROM agent_waits w WHERE w.run=r.run AND w.pending=1 AND (w.due_at IS NULL OR w.due_at>?3) AND NOT (
{RECONCILABLE_WAIT}
OR (w.due_at IS NULL AND json_extract(w.body,'$.reason.kind') IS 'cell' AND EXISTS (
SELECT 1 FROM agent_cells c WHERE c.run=w.run AND c.cell=json_extract(w.body,'$.reason.cell')
AND json_extract(maka_content_text(c.body,c.body_encoding),'$.status.kind') IS 'running'))))))))
SELECT run,admission_sequence,session,NULL AS cleanup_task FROM business
UNION ALL
SELECT r.run,r.admission_sequence,r.session,json_extract(r.external,'$.task') AS cleanup_task
FROM agent_runs r WHERE r.owner=?1 AND r.local=1 AND r.admission_sequence>?2
AND json_extract(r.external,'$.admitted')=1 AND json_extract(r.external,'$.cleanup.kind') IS NOT 'confirmed'
AND coalesce(json_extract(r.external,'$.cleanupNotBefore'),-9223372036854775808)<=?3
AND NOT EXISTS(SELECT 1 FROM business b WHERE b.run=r.run)
ORDER BY admission_sequence LIMIT ?4"))?;
let mut rows = statement.query(params![
serde_json::to_string(&owner)?,
signed(after.unwrap_or(0))?,
at.0,
limit(count)?,
cause == crate::store::ReadyCause::CapabilitySourceChanged
])?;
let mut ready = Vec::new();
while let Some(row) = rows.next()? {
let task: Option<String> = row.get(3)?;
ready.push(crate::store::ReadyRun {
run: identity(row.get(0)?)?,
admission_sequence: column_u64(row, 1)?,
session_id: row.get(2)?,
purpose: match task {
Some(task) => crate::store::DriverPurpose::LateExternalCleanup {
task: identity(task)?,
},
None => crate::store::DriverPurpose::Business,
},
});
}
Ok(ready)
}
const MODEL_RECONCILIATION_RUNS_SQL: &str = "WITH candidates AS (
SELECT a.run FROM agent_attempts a INDEXED BY agent_model_cleanup_pending
WHERE json_extract(a.body,'$.admission') IS NOT NULL AND json_extract(a.body,'$.cleanup.kind') IS NOT 'confirmed'
AND (?4=1 OR EXISTS(SELECT 1 FROM agent_runs live WHERE live.run=a.run AND live.terminal IS NULL))
AND (?4=1 OR NOT EXISTS(SELECT 1 FROM agent_blockers b WHERE b.run=a.run AND json_extract(b.body,'$.resolvedBy') IS NULL
AND json_extract(b.body,'$.reason.kind')='model_cleanup_unconfirmed' AND json_extract(b.body,'$.reason.attempt')=a.key))
UNION
SELECT r.run FROM agent_runs r INDEXED BY agent_runs_live
JOIN agent_attempts a ON a.run=r.run AND a.key=r.current_attempt
WHERE r.owner=?1 AND r.terminal IS NULL AND r.stopped=0
AND json_extract(a.body,'$.closed.outcome')='success' AND json_extract(a.body,'$.closed.diagnostic') IS NULL
AND json_extract(a.body,'$.closed.protocol.finishReason')='stop' AND json_extract(a.body,'$.hasTools')=0
AND (?4=1 OR EXISTS(SELECT 1 FROM agent_waits w WHERE w.run=r.run AND w.pending=1 AND json_extract(w.body,'$.reason.kind')='model')
OR (EXISTS(SELECT 1 FROM agent_blockers b WHERE b.run=r.run AND b.pending=1
AND json_extract(b.body,'$.decision') IS NULL AND json_extract(b.body,'$.resolvedBy') IS NULL
AND json_extract(b.body,'$.reason.kind')='current_authority_unavailable')
AND NOT EXISTS(SELECT 1 FROM agent_waits w WHERE w.run=r.run AND w.pending=1
AND json_extract(w.body,'$.reason.kind') IN ('child','retry','provider_backoff'))))
AND NOT EXISTS(SELECT 1 FROM agent_blockers b WHERE b.run=r.run AND b.pending=1
AND json_extract(b.body,'$.decision') IS NULL AND json_extract(b.body,'$.resolvedBy') IS NULL
AND json_extract(b.body,'$.reason.kind') IS NOT 'current_authority_unavailable')
AND NOT EXISTS(SELECT 1 FROM agent_attempts pending INDEXED BY agent_model_cleanup_pending WHERE pending.run=r.run
AND json_extract(pending.body,'$.admission') IS NOT NULL AND json_extract(pending.body,'$.cleanup.kind') IS NOT 'confirmed')
) SELECT r.run,r.admission_sequence,r.session FROM candidates p CROSS JOIN agent_runs r ON r.run=p.run
WHERE r.owner=?1 AND r.local=1 AND r.admission_sequence>?2 ORDER BY r.admission_sequence LIMIT ?3";
pub(crate) fn model_reconciliation_runs(
c: &Connection,
owner: RunOwner,
after: Option<u64>,
count: u32,
cold_probe: bool,
) -> Result<Vec<crate::store::ReadyRun>, StoreError> {
let mut statement = c.prepare_cached(MODEL_RECONCILIATION_RUNS_SQL)?;
let mut rows = statement.query(params![
serde_json::to_string(&owner)?,
signed(after.unwrap_or(0))?,
limit(count)?,
cold_probe
])?;
let mut result = Vec::new();
while let Some(row) = rows.next()? {
result.push(crate::store::ReadyRun {
run: identity(row.get(0)?)?,
admission_sequence: column_u64(row, 1)?,
session_id: row.get(2)?,
purpose: crate::store::DriverPurpose::LateModelCleanup,
});
}
Ok(result)
}
pub(crate) fn model_cleanups(
c: &Connection,
run: RunId,
after: Option<ModelAttemptId>,
count: u32,
cold_probe: bool,
) -> Result<Vec<crate::store::ModelCleanupItem>, StoreError> {
let view = load(c, run, &[], false)?;
if !matches!(view.spec.origin, RunOrigin::Local)
|| !matches!(view.spec.backend, BackendSpec::Model { .. })
{
return Err(invalid("foreign model cleanup source"));
}
let mut statement = c.prepare_cached("SELECT key,body FROM agent_attempts INDEXED BY agent_model_cleanup_pending
WHERE run=? AND json_extract(body,'$.admission') IS NOT NULL AND json_extract(body,'$.cleanup.kind') IS NOT 'confirmed'
AND (?2 IS NULL OR key>?2)
AND (?4=1 OR NOT EXISTS(SELECT 1 FROM agent_blockers b WHERE b.run=agent_attempts.run AND json_extract(b.body,'$.resolvedBy') IS NULL
AND json_extract(b.body,'$.reason.kind')='model_cleanup_unconfirmed' AND json_extract(b.body,'$.reason.attempt')=agent_attempts.key))
ORDER BY key LIMIT ?3")?;
let mut rows = statement.query(params![
run.to_string(),
after.map(|id| id.to_string()),
limit(count)?,
cold_probe
])?;
let mut result = Vec::new();
while let Some(row) = rows.next()? {
let attempt: Attempt = serde_json::from_str(&row.get::<_, String>(1)?)?;
let request = request(c, run, attempt.step)?;
result.push(crate::store::ModelCleanupItem {
owner: view.spec.owner.clone(),
execution: ExecutionIdentity {
run_id: run,
session_id: view.spec.session_id.clone(),
turn_id: view.spec.turn_id.clone(),
},
attempt: identity(row.get(0)?)?,
step: attempt.step,
request: request.request,
upstream: attempt
.admission
.expect("selected admitted source")
.upstream,
});
}
Ok(result)
}
pub(crate) fn next_due(
c: &Connection,
owner: RunOwner,
after: Option<UnixMillis>,
cause: crate::store::ReadyCause,
) -> Result<Option<UnixMillis>, StoreError> {
let next: Option<i64> = c.prepare_cached(&format!("SELECT min(due) FROM (
SELECT max(coalesce(r.retry_due_at,0),coalesce(max(w.due_at),0)) AS due
FROM agent_runs r LEFT JOIN agent_waits w ON w.run=r.run AND w.pending=1 AND NOT ({RECONCILABLE_WAIT})
AND NOT (?3=1 AND w.due_at IS NULL AND {AUTHORITY_BLOCKED})
WHERE r.owner=?1 AND r.terminal IS NULL AND r.local=1 AND r.stopped=0
AND NOT EXISTS(SELECT 1 FROM agent_blockers b WHERE b.run=r.run AND b.pending=1 AND json_extract(b.body,'$.decision') IS NULL AND json_extract(b.body,'$.resolvedBy') IS NULL AND (?3=0 OR json_extract(b.body,'$.reason.kind') IS NOT 'current_authority_unavailable'))
GROUP BY r.run
HAVING sum(CASE WHEN w.key IS NOT NULL AND w.due_at IS NULL THEN 1 ELSE 0 END)=0
AND (r.retry_due_at IS NOT NULL OR count(w.due_at)>0)
UNION ALL
SELECT json_extract(r.external,'$.cleanupNotBefore') AS due FROM agent_runs r
WHERE r.owner=?1 AND r.local=1
AND json_extract(r.external,'$.admitted')=1 AND json_extract(r.external,'$.cleanup.kind') IS NOT 'confirmed'
AND json_extract(r.external,'$.cleanupNotBefore') IS NOT NULL
AND coalesce(json_extract(r.external,'$.cleanupNotBefore'),-9223372036854775808)>coalesce(?2,-9223372036854775808)
) WHERE ?2 IS NULL OR due>?2"))?
.query_row(params![serde_json::to_string(&owner)?, after.map(|at| at.0), cause == crate::store::ReadyCause::CapabilitySourceChanged], |row| row.get(0))?;
Ok(next.map(UnixMillis))
}
pub(crate) fn cleanup_frontier(
c: &Connection,
run: RunId,
) -> Result<crate::store::CleanupFrontier, StoreError> {
type RunHeaderRow = (
String,
String,
u64,
u64,
bool,
Option<String>,
String,
String,
String,
u32,
bool,
);
let (owner, session, revision, control, local, external, backend_kind, backend, turn, schema, has_publication): RunHeaderRow =
c.prepare_cached("SELECT r.owner,r.session,r.revision,r.control_version,r.local,r.external,
json_extract(maka_content_text(body.payload,body.encoding),'$.backend.kind'),json_extract(maka_content_text(body.payload,body.encoding),'$.backend.descriptor'),
json_extract(maka_content_text(body.payload,body.encoding),'$.turnId'),r.schema_version,
EXISTS(SELECT 1 FROM agent_external_publications publication WHERE publication.run=r.run)
FROM agent_runs r JOIN agent_run_specs spec ON spec.run=r.run JOIN contents body ON body.id=spec.spec_content_id
WHERE r.run=?")?.query_row([run.to_string()], |row| Ok((row.get(0)?,row.get(1)?,column_u64(row,2)?,column_u64(row,3)?,row.get(4)?,row.get(5)?,row.get(6)?,row.get(7)?,row.get(8)?,row.get(9)?,row.get(10)?)))?;
if !local || backend_kind != "executor" || schema != HEADER_SCHEMA_VERSION {
return Err(invalid(
"cleanup requires original local executor projection",
));
}
let task: fold::ExternalTask =
serde_json::from_str(&external.ok_or_else(|| invalid("original external task absent"))?)?;
if !task.admitted {
return Err(invalid("cleanup has no original task admission"));
}
Ok(crate::store::CleanupFrontier {
has_creation_evidence: task.observed != 0
|| has_publication
|| task.closed.as_ref().is_some_and(|closed| {
closed.outcome == maka_agent_facts::durable::Terminal::Completed
}),
run,
head: Head {
revision,
control_version: control,
},
owner: serde_json::from_str(&owner)?,
session_id: session,
turn_id: turn,
backend: serde_json::from_str(&backend)?,
task: task.task,
descriptor: task.descriptor,
binding: task.binding,
cleanup: task.cleanup,
not_before: task.cleanup_not_before,
})
}
// Nonempty answer parts are contiguous. The first end at or beyond the page end
// is the inclusive upper key on (run, end), even when a page cuts through a part.
// Raw parts (encoding = 0, the common streaming-delta case) slice directly in SQL
// so pagination avoids per-part read_range_by_id round trips.
const ANSWER_TEXT: &str = "SELECT p.content_id, c.encoding, max(?1-p.start,0), min(p.end,?2)-max(p.start,?1),
CASE WHEN c.encoding = 0 THEN substr(c.payload, max(?1-p.start,0)+1, min(p.end,?2)-max(p.start,?1)) END
FROM agent_answer_parts p
JOIN contents c ON c.id = p.content_id
WHERE p.run=?3 AND p.end>?1
AND p.end<=(SELECT min(end) FROM agent_answer_parts WHERE run=?3 AND end>=?2)
ORDER BY p.end";
pub(crate) fn work(
c: &Connection,
run: RunId,
offset: u64,
count: u32,
) -> Result<Option<crate::store::RunObservation>, StoreError> {
if !(4..=65536).contains(&count) {
return Err(invalid("answer page size must be in 4..=65536 bytes"));
}
if !exists(c, run)? {
return Ok(None);
}
let view = load(c, run, &[], false)?;
let high_water: u64 = c
.prepare_cached("SELECT coalesce(max(end),0) FROM agent_answer_parts WHERE run=?")?
.query_row([run.to_string()], |r| column_u64(r, 0))?;
if offset > high_water {
return Err(invalid("answer offset is beyond the captured prefix"));
}
let end = offset.saturating_add(u64::from(count)).min(high_water);
let mut bytes = Vec::new();
{
let mut statement = c.prepare_cached(ANSWER_TEXT)?;
let mut rows = statement.query(params![signed(offset)?, signed(end)?, run.to_string()])?;
while let Some(row) = rows.next()? {
let cid: i64 = row.get(0)?;
let encoding: i64 = row.get(1)?;
let slice_off = u64::try_from(row.get::<_, i64>(2)?)
.map_err(|_| invalid("negative answer slice offset"))?;
let slice_len = u64::try_from(row.get::<_, i64>(3)?)
.map_err(|_| invalid("negative answer slice length"))?;
if slice_len == 0 {
continue;
}
if encoding == maka_event_log::content::ENCODING_RAW {
let raw: Vec<u8> = row
.get::<_, Option<Vec<u8>>>(4)?
.ok_or_else(|| invalid("missing raw answer part slice"))?;
if raw.len() as u64 != slice_len {
return Err(invalid("raw answer part slice length mismatch"));
}
bytes.extend(raw);
} else {
bytes.extend(maka_event_log::content::read_range_by_id(
c, cid, slice_off, slice_len,
)?);
}
}
}
if let Err(error) = std::str::from_utf8(&bytes) {
if error.error_len().is_some() {
return Err(invalid("answer offset is not a UTF-8 boundary"));
}
bytes.truncate(error.valid_up_to());
}
let next = offset
.checked_add(u64::try_from(bytes.len()).map_err(|_| invalid("answer length exceeds u64"))?)
.ok_or_else(|| invalid("answer cursor overflow"))?;
if next == offset && offset < high_water {
return Err(invalid("answer page made no UTF-8 progress"));
}
let text = String::from_utf8(bytes).map_err(|_| invalid("invalid canonical answer bytes"))?;
let pending_interactions =
if !view.stopped && view.terminal.is_none() && matches!(view.spec.origin, RunOrigin::Local)
{
crate::session_history::pending_interaction_count(c, run, &view.spec.session_id)?
} else {
0
};
Ok(Some(crate::store::RunObservation {
view,
pending_interactions,
answer: crate::store::AnswerPage {
offset,
high_water,
text,
next: (next < high_water).then_some(next),
},
}))
}
pub(crate) fn notification(
c: &Connection,
run: RunId,
changed: bool,
) -> Result<maka_event_log::writeback::Notification, StoreError> {
if !changed {
return Ok(maka_event_log::writeback::Notification::NONE);
}
let session: String = c
.prepare_cached("SELECT session FROM agent_run_specs WHERE run=?")?
.query_row([run.to_string()], |r| r.get(0))?;
Ok(maka_event_log::writeback::Notification::METADATA.with_sessions([session]))
}
fn model_item(c: &Connection, fact: &RecordedFact) -> Result<(), StoreError> {
if let Fact::ModelObserved { attempt, index, .. } = &fact.fact {
c.prepare_cached(
"INSERT INTO agent_model_items(run,attempt,item_index,fact_id) VALUES(?,?,?,?)",
)?
.execute(params![
fact.run.to_string(),
attempt.to_string(),
signed(*index)?,
fact.id.to_string()
])?;
}
Ok(())
}
pub(crate) fn model_items(
c: &Connection,
run: RunId,
attempt: ModelAttemptId,
after: Option<u64>,
count: u32,
) -> Result<Vec<RecordedFact>, StoreError> {
let mut statement=c.prepare_cached("SELECT f.schema_version,maka_content_bytes(c.payload,c.encoding) FROM agent_model_items i JOIN agent_facts f ON f.id=i.fact_id JOIN contents c ON c.id=f.body_content_id WHERE i.run=? AND i.attempt=? AND i.item_index>? ORDER BY i.item_index LIMIT ?")?;
let mut rows = statement.query(params![
run.to_string(),
attempt.to_string(),
after.map(signed).transpose()?.unwrap_or(-1),
limit(count)?
])?;
let mut result = Vec::new();
while let Some(row) = rows.next()? {
version(row.get(0)?)?;
let fact: RecordedFact = serde_json::from_slice(&row.get::<_, Vec<u8>>(1)?)?;
version(fact.schema_version)?;
if fact.run != run || !matches!(fact.fact,Fact::ModelObserved{attempt:id,..} if id==attempt)
{
return Err(invalid(
"model item index does not match canonical identity",
));
}
result.push(fact);
}
Ok(result)
}
#[cfg(test)]
mod answer_page_tests {
use super::*;
use rusqlite::StatementStatus;
#[test]
fn answer_pages_visit_only_intersecting_parts() {
let db = Connection::open_in_memory().unwrap();
let catalog: Vec<_> = maka_event_log::ROOT_MIGRATIONS
.iter()
.chain(crate::MIGRATIONS)
.copied()
.collect();
maka_event_log::migration::run(&db, &catalog).unwrap();
db.execute_batch(r#"
INSERT INTO contents(id,content_sha256,payload) VALUES(1,'spec',x'7b7d'),(2,'text',CAST('Aä½ B' AS BLOB));
INSERT INTO agent_run_specs(run,schema_version,owner,session,spec_content_id) VALUES('run',1,'owner','chat',1);
"#).unwrap();
// Also insert a zstd-compressed answer part (encoding != 0) to verify the non-raw
// fallback path alongside raw inline slicing.
let compressed_part = "Aä½ B".repeat(120);
let compressed_blob = crate::ContentBlob::new(compressed_part.as_bytes().to_vec());
let compressed_cid = super::put(&db, &compressed_blob).unwrap();
let compressed_enc: i64 = db
.query_row(
"SELECT encoding FROM contents WHERE id=?",
[compressed_cid],
|r| r.get(0),
)
.unwrap();
assert_ne!(compressed_enc, maka_event_log::content::ENCODING_RAW);
let window = |start: i64, end: i64| {
let mut body = db.prepare(ANSWER_TEXT).unwrap();
let mut rows = body.query(params![start, end, "run"]).unwrap();
let mut bytes = Vec::new();
let mut deferred = Vec::new();
while let Some(r) = rows.next().unwrap() {
let cid: i64 = r.get(0).unwrap();
let enc: i64 = r.get(1).unwrap();
let off = r.get::<_, i64>(2).unwrap() as u64;
let len = r.get::<_, i64>(3).unwrap() as u64;
if len == 0 {
continue;
}
if enc == maka_event_log::content::ENCODING_RAW {
bytes.extend(r.get::<_, Vec<u8>>(4).unwrap());
} else {
deferred.push((bytes.len(), cid, off, len));
}
}
drop(rows);
let body_steps = body.get_status(StatementStatus::VmStep);
drop(body);
if !deferred.is_empty() {
let mut rebuilt = Vec::new();
let mut prev = 0usize;
for (pos, cid, off, len) in deferred {
rebuilt.extend_from_slice(&bytes[prev..pos]);
rebuilt.extend(
maka_event_log::content::read_range_by_id(&db, cid, off, len).unwrap(),
);
prev = pos;
}
rebuilt.extend_from_slice(&bytes[prev..]);
bytes = rebuilt;
}
(String::from_utf8(bytes).unwrap(), body_steps)
};
let mut costs = Vec::new();
let mut previous = 0;
for count in [16, 2048] {
db.execute(
"WITH RECURSIVE n(v) AS (VALUES(?1+1) UNION ALL SELECT v+1 FROM n WHERE v<?2)
INSERT INTO agent_facts SELECT v,'f'||v,'run',v,1,0,1 FROM n",
params![previous, count],
)
.unwrap();
db.execute(
"INSERT INTO agent_answer_parts SELECT 'run',revision,5*(revision-1),5*revision,2
FROM agent_facts WHERE revision>?",
[previous],
)
.unwrap();
let early = window(4, 11);
let late = window(5 * count - 6, 5 * count);
assert_eq!(early.0, "BAä½ BA");
assert_eq!(late.0, "BAä½ B");
assert_eq!(window(5, 10).0, "Aä½ B");
assert_eq!(window(5 * count, 5 * count).0, "");
costs.push([early.1, late.1]);
previous = count;
}
for (small, large) in costs[0].into_iter().zip(costs[1]) {
assert!(
large <= small * 2,
"fixed page cost grew from {small} to {large} VM steps"
);
}
// Append one compressed part after the raw parts and read across the raw->compressed boundary.
let tail_start = 5 * previous;
let tail_end = tail_start + compressed_part.len() as i64;
db.execute(
"INSERT INTO agent_facts VALUES(?1,'f'||?1,'run',?1,1,0,1)",
[previous + 1],
)
.unwrap();
db.execute(
"INSERT INTO agent_answer_parts VALUES('run',?1,?2,?3,?4)",
params![previous + 1, tail_start, tail_end, compressed_cid],
)
.unwrap();
assert_eq!(window(tail_start - 1, tail_start + 5).0, "BAä½ B");
}
}
pub(crate) fn migrate_retry_streak(c: &Connection) -> Result<(), maka_event_log::StoreError> {
let runs: Vec<String> = {
let mut statement =
c.prepare("SELECT run FROM agent_runs WHERE retries > 0 OR retry_phase = 'fallback'")?;
let rows = statement.query_map([], |row| row.get(0))?;
rows.collect::<Result<_, _>>()?
};
if runs.is_empty() {
return Ok(());
}
let mut facts = c.prepare(
"SELECT c.payload FROM agent_facts f JOIN contents c ON c.id = f.body_content_id WHERE f.run = ? ORDER BY f.revision ASC",
)?;
let mut update = c.prepare("UPDATE agent_runs SET retry_streak = ? WHERE run = ?")?;
for run in runs {
let mut current_attempt = None;
let mut streak = fold::RetryStreak::default();
let payloads = facts.query_map([&run], |row| row.get::<_, Vec<u8>>(0))?;
for payload in payloads {
let bytes = payload?;
let recorded: RecordedFact = serde_json::from_slice(&bytes).map_err(|error| {
maka_event_log::StoreError::Migration(format!(
"failed to decode agent fact for retry_streak backfill on run {run}: {error}"
))
})?;
match &recorded.fact {
Fact::ModelAttemptPrepared { attempt, .. } => {
current_attempt = Some(*attempt);
}
Fact::ModelTransportSelected {
attempt,
phase: maka_agent_facts::model::retry_transport::RetryTransportPhase::Fallback,
} => {
streak = fold::RetryStreak::FallbackTransitionPending { attempt: *attempt };
}
Fact::RetryCharged { attempt, .. } => {
streak = streak.on_retry_charged(*attempt).map_err(|error| {
maka_event_log::StoreError::Migration(format!(
"failed to replay retry_streak for run {run}: {error}"
))
})?;
}
Fact::ModelClosed {
attempt,
outcome: maka_agent_facts::accounting::Outcome::Success,
diagnostic: None,
..
} if current_attempt == Some(*attempt) => {
streak = fold::RetryStreak::default();
}
_ => {}
}
}
let encoded = serde_json::to_string(&streak).map_err(|error| {
maka_event_log::StoreError::Migration(format!(
"failed to encode retry_streak for run {run}: {error}"
))
})?;
update.execute(params![encoded, run])?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::MODEL_RECONCILIATION_RUNS_SQL;
use rusqlite::{Connection, params};
fn put_legacy_content(db: &Connection, blob: &crate::ContentBlob) -> i64 {
if maka_event_log::content::has_encoding_column(db).unwrap() {
super::put(db, blob).unwrap()
} else {
blob.store_legacy(db).unwrap()
}
}
#[test]
fn model_reconciliation_runs_drives_join_from_candidates_not_due_index() {
let db = Connection::open_in_memory().unwrap();
let catalog: Vec<_> = maka_event_log::ROOT_MIGRATIONS
.iter()
.chain(crate::MIGRATIONS)
.copied()
.collect();
maka_event_log::migration::run(&db, &catalog).unwrap();
let mut stmt = db
.prepare(&format!(
"EXPLAIN QUERY PLAN {MODEL_RECONCILIATION_RUNS_SQL}"
))
.unwrap();
let plan: Vec<String> = stmt
.query_map(params!["{}", 0i64, 64i64, false], |r| r.get(3))
.unwrap()
.collect::<Result<_, _>>()
.unwrap();
assert!(
plan.iter().all(|step| !step.contains("agent_runs_due")),
"reconciliation query must not scan historical runs via agent_runs_due: {plan:?}"
);
assert!(
plan.iter()
.any(|step| step.contains("SEARCH r USING") && step.contains("(run=?)")),
"outer join must probe agent_runs by run PK from candidates: {plan:?}"
);
}
#[test]
fn migration_53_backfills_retry_streak_matching_fact_replay() {
use crate::{
ContentBlob,
fold::{self, RunView},
};
use maka_agent_facts::{
accounting::Outcome,
context::ModelClosureProtocol,
durable::{
AttemptRecovery, Fact, FactId, ModelAttemptId, RecordedFact, RunId, SCHEMA_VERSION,
StepId, UnixMillis,
},
model::{ModelFinishReason, retry_transport::RetryTransportPhase},
};
use maka_plugin_core::operation::OperationCleanup;
let db = Connection::open_in_memory().unwrap();
let catalog: Vec<_> = maka_event_log::ROOT_MIGRATIONS
.iter()
.chain(crate::MIGRATIONS)
.copied()
.collect();
let through_52: Vec<_> = catalog
.iter()
.filter(|m| m.version <= 52)
.copied()
.collect();
maka_event_log::migration::run(&db, &through_52).unwrap();
let seed_run = |facts: Vec<Fact>, retries: u32, retry_phase: &str| -> (RunId, RunView) {
let run = RunId::new();
let (mut spec, _) = crate::store::stop_tests::spec();
spec.session_id = format!("mig53-{run}");
spec.budget.retries = 2;
let spec_blob = ContentBlob::json(&spec).unwrap();
let spec_cid = put_legacy_content(&db, &spec_blob);
let owner_json = serde_json::to_string(&spec.owner).unwrap();
db.execute(
"INSERT INTO agent_run_specs(run,schema_version,owner,session,spec_content_id) VALUES(?,?,?,?,?)",
params![run.to_string(), SCHEMA_VERSION, owner_json, spec.session_id, spec_cid],
)
.unwrap();
let mut view = RunView::admitted(run, spec).unwrap();
let all_facts = std::iter::once(Fact::RunAdmitted {
spec: spec_blob.reference().clone(),
})
.chain(facts);
let mut admission_seq = 0_i64;
let mut revision = 0_u64;
for fact in all_facts {
revision += 1;
let recorded = RecordedFact {
schema_version: SCHEMA_VERSION,
id: FactId::new(),
run,
revision,
at: UnixMillis(revision as i64),
fact,
};
view.apply(&recorded).unwrap();
let fact_blob = ContentBlob::json(&recorded).unwrap();
let cid = put_legacy_content(&db, &fact_blob);
db.execute(
"INSERT INTO agent_facts(id,run,revision,schema_version,at,body_content_id) VALUES(?,?,?,?,?,?)",
params![
recorded.id.to_string(),
run.to_string(),
revision as i64,
SCHEMA_VERSION,
recorded.at.0,
cid
],
)
.unwrap();
if revision == 1 {
admission_seq = db.last_insert_rowid();
}
}
db.execute(
"INSERT INTO agent_runs(run,schema_version,owner,session,admission_sequence,local,revision,control_version,stopped,terminal,tokens,retries,retry_due_at,retry_pending,current_step,current_attempt,cancelled_by_risk,replans,baseline,external,stop_request,stop_assessed,retry_phase,finish_requested,proactive_summary,output_limit_continuations) VALUES(?,?,?,?,?,?,?,?,0,NULL,0,?,NULL,NULL,NULL,NULL,0,'{}',NULL,NULL,NULL,NULL,?,0,NULL,0)",
params![
run.to_string(),
super::HEADER_SCHEMA_VERSION,
owner_json,
format!("mig53-{run}"),
admission_seq,
1_i64,
revision as i64,
0_i64,
retries,
retry_phase,
],
)
.unwrap();
(run, view)
};
let req = ContentBlob::json(&serde_json::json!({}))
.unwrap()
.reference()
.clone();
let ok_protocol = serde_json::to_value(ModelClosureProtocol {
model_time_ms: None,
finish_reason: ModelFinishReason::Stop,
provider_options: None,
cache_read_reported: None,
response_id: None,
model: None,
timestamp: None,
compaction: None,
summary: None,
})
.unwrap();
let fail_facts = |step: StepId, attempt: ModelAttemptId, prepare_step: bool| {
let mut out = Vec::new();
if prepare_step {
out.push(Fact::StepPrepared {
step,
request: req.clone(),
adjudications: vec![],
});
}
out.extend([
Fact::ModelAttemptPrepared { attempt, step },
Fact::ModelAttemptAdmitted {
attempt,
upstream: serde_json::Value::Null,
},
Fact::ModelInterrupted {
attempt,
diagnostic: "timed out".into(),
},
Fact::AttemptRecoveryRecorded {
attempt,
recovery: AttemptRecovery::FrozenRetrySafe { not_before: None },
},
Fact::ModelCleanupObserved {
attempt,
cleanup: OperationCleanup::Confirmed,
},
]);
out
};
let succeed_facts = |step: StepId, attempt: ModelAttemptId| {
vec![
Fact::ModelAttemptPrepared { attempt, step },
Fact::ModelAttemptAdmitted {
attempt,
upstream: serde_json::Value::Null,
},
Fact::ModelClosed {
attempt,
outcome: Outcome::Success,
diagnostic: None,
usage: Default::default(),
protocol: ok_protocol.clone(),
},
Fact::ModelCleanupObserved {
attempt,
cleanup: OperationCleanup::Confirmed,
},
]
};
// 1) Primary mid-streak with a succeeding background proactive summary (must NOT reset).
let (s1, a1, bg1) = (StepId::new(), ModelAttemptId::new(), ModelAttemptId::new());
let mut f1 = fail_facts(s1, a1, true);
f1.push(Fact::RetryCharged {
attempt: a1,
phase: RetryTransportPhase::Primary,
due_at: UnixMillis(10),
diagnostic: "retry".into(),
});
f1.extend([
Fact::ProactiveSummaryPrepared {
step: StepId::new(),
request: req.clone(),
attempt: bg1,
},
Fact::ModelAttemptAdmitted {
attempt: bg1,
upstream: serde_json::Value::Null,
},
Fact::ModelClosed {
attempt: bg1,
outcome: Outcome::Success,
diagnostic: None,
usage: Default::default(),
protocol: ok_protocol.clone(),
},
Fact::ModelCleanupObserved {
attempt: bg1,
cleanup: OperationCleanup::Confirmed,
},
]);
let (run_mid_primary, view_mid_primary) = seed_run(f1, 1, "primary");
// 2) Primary retry followed by foreground success (resets to Regular { charged: 0 }).
let (s2, a2, a2_ok) = (StepId::new(), ModelAttemptId::new(), ModelAttemptId::new());
let mut f2 = fail_facts(s2, a2, true);
f2.push(Fact::RetryCharged {
attempt: a2,
phase: RetryTransportPhase::Primary,
due_at: UnixMillis(1),
diagnostic: "retry".into(),
});
f2.extend(succeed_facts(s2, a2_ok));
let (run_reset_primary, view_reset_primary) = seed_run(f2, 1, "primary");
// 3) ModelTransportSelected(Fallback) pending its transition RetryCharged.
let (s3, a3_1, a3_2, a3_3) = (
StepId::new(),
ModelAttemptId::new(),
ModelAttemptId::new(),
ModelAttemptId::new(),
);
let mut f3 = fail_facts(s3, a3_1, true);
f3.push(Fact::RetryCharged {
attempt: a3_1,
phase: RetryTransportPhase::Primary,
due_at: UnixMillis(1),
diagnostic: "r1".into(),
});
f3.extend(fail_facts(s3, a3_2, false));
f3.push(Fact::RetryCharged {
attempt: a3_2,
phase: RetryTransportPhase::Primary,
due_at: UnixMillis(1),
diagnostic: "r2".into(),
});
f3.extend(fail_facts(s3, a3_3, false));
f3.push(Fact::ModelTransportSelected {
attempt: a3_3,
phase: RetryTransportPhase::Fallback,
});
let (run_fallback_pending, view_fallback_pending) = seed_run(f3.clone(), 2, "fallback");
// 4) Fallback transition + one post-transition Fallback retry -> AfterFallbackTransition { charged: 1 }.
let a4_4 = ModelAttemptId::new();
let mut f4 = f3.clone();
f4.push(Fact::RetryCharged {
attempt: a3_3,
phase: RetryTransportPhase::Fallback,
due_at: UnixMillis(1),
diagnostic: "fallback-transition".into(),
});
f4.extend(fail_facts(s3, a4_4, false));
f4.push(Fact::RetryCharged {
attempt: a4_4,
phase: RetryTransportPhase::Fallback,
due_at: UnixMillis(1),
diagnostic: "fallback-r1".into(),
});
let (run_fallback_charged, view_fallback_charged) = seed_run(f4.clone(), 4, "fallback");
// 5) Fallback succeeded -> reset to Regular { charged: 0 }.
let mut f5 = f4;
f5.extend(succeed_facts(s3, ModelAttemptId::new()));
let (run_fallback_reset, view_fallback_reset) = seed_run(f5, 4, "fallback");
// Apply migration 53 (SQL + atomic data backfill).
maka_event_log::migration::run(&db, &catalog).unwrap();
let expected = [
(
run_mid_primary,
view_mid_primary.retry_streak,
fold::RetryStreak::Regular { charged: 1 },
),
(
run_reset_primary,
view_reset_primary.retry_streak,
fold::RetryStreak::Regular { charged: 0 },
),
(
run_fallback_pending,
view_fallback_pending.retry_streak,
fold::RetryStreak::FallbackTransitionPending { attempt: a3_3 },
),
(
run_fallback_charged,
view_fallback_charged.retry_streak,
fold::RetryStreak::AfterFallbackTransition { charged: 1 },
),
(
run_fallback_reset,
view_fallback_reset.retry_streak,
fold::RetryStreak::Regular { charged: 0 },
),
];
for (run, folded, want) in expected {
assert_eq!(folded, want, "folded streak mismatch for {run}");
let raw: String = db
.query_row(
"SELECT retry_streak FROM agent_runs WHERE run = ?",
[run.to_string()],
|row| row.get(0),
)
.unwrap();
let migrated: fold::RetryStreak = serde_json::from_str(&raw).unwrap();
assert_eq!(migrated, folded, "migrated streak mismatch for {run}");
}
}
#[test]
fn external_task_instructions_ref_fails_closed_on_malformed_reference() {
use crate::ContentBlob;
use maka_agent_facts::durable::{ContentRef, RunId};
let db = Connection::open_in_memory().unwrap();
maka_event_log::migration::run(
&db,
&maka_event_log::ROOT_MIGRATIONS
.iter()
.chain(crate::MIGRATIONS)
.copied()
.collect::<Vec<_>>(),
)
.unwrap();
let run = RunId::new();
let spec_blob = ContentBlob::new(b"{}".to_vec());
let spec_cid = spec_blob.store(&db).unwrap();
db.execute(
r#"INSERT INTO agent_run_specs(run, schema_version, owner, session, spec_content_id)
VALUES(?1, 1, '"test"', 'sess-instr', ?2)"#,
params![run.to_string(), spec_cid],
)
.unwrap();
let insert_descriptor = |payload: &[u8]| -> ContentRef {
let blob = ContentBlob::new(payload.to_vec());
let cid = blob.store(&db).unwrap();
db.execute(
"INSERT OR IGNORE INTO agent_content_pins(run, content_id) VALUES(?1, ?2)",
params![run.to_string(), cid],
)
.unwrap();
blob.reference().clone()
};
// Absent and null instructionsRef return Ok(None).
let absent = insert_descriptor(br#"{"payload":{"prompt":"hi"}}"#);
assert_eq!(
super::external_task_instructions_ref(&db, run, &absent).unwrap(),
None
);
let null_ref = insert_descriptor(br#"{"payload":{"instructionsRef":null}}"#);
assert_eq!(
super::external_task_instructions_ref(&db, run, &null_ref).unwrap(),
None
);
// Valid instructionsRef returns Ok(Some(ref)).
let valid_ref = ContentRef {
digest: format!("sha256:{}", "b".repeat(64)),
bytes: 42,
};
let valid_desc = insert_descriptor(
&serde_json::to_vec(&serde_json::json!({
"payload": { "instructionsRef": valid_ref }
}))
.unwrap(),
);
assert_eq!(
super::external_task_instructions_ref(&db, run, &valid_desc).unwrap(),
Some(valid_ref)
);
// Malformed instructionsRef (wrong type or invalid digest) MUST fail closed.
let wrong_type = insert_descriptor(br#"{"payload":{"instructionsRef":"not-a-ref"}}"#);
assert!(super::external_task_instructions_ref(&db, run, &wrong_type).is_err());
let bad_digest = insert_descriptor(
br#"{"payload":{"instructionsRef":{"digest":"sha256:not-hex","bytes":10}}}"#,
);
assert!(super::external_task_instructions_ref(&db, run, &bad_digest).is_err());
let invalid_json = insert_descriptor(b"not json at all");
assert!(super::external_task_instructions_ref(&db, run, &invalid_json).is_err());
}
}