blob: fdea61996a5d1573dcd3d6b07a6a044731a6fa7c [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.
*/
use maka_agent_facts::durable::RunOwner;
use maka_event_log::{
StoreError,
connection::Query,
root_store::DataWriter,
writeback::{Notification, Prepared, Statement},
};
use rusqlite::{Connection, OptionalExtension, params};
use serde_json::Value;
use uuid::Uuid;
#[derive(Clone)]
pub struct Inbox {
pub source_root: String,
pub op_id: Uuid,
pub digest: String,
}
impl Inbox {
pub fn is_conflict(error: &StoreError) -> bool {
matches!(error.underlying(), StoreError::InvalidTransition(reason) if reason == "cross_root_operation_digest_conflict")
}
pub async fn receipt(&self, writer: &DataWriter) -> Result<Option<Value>, StoreError> {
writer.query(self.clone()).await
}
pub fn read(&self, db: &Connection) -> Result<Option<Value>, StoreError> {
let row: Option<(String, String)> = db.query_row(
"SELECT digest, receipt_json FROM agent_cross_root_inbox WHERE source_root=? AND op_id=?",
params![self.source_root, self.op_id.to_string()],
|row| Ok((row.get(0)?, row.get(1)?)),
).optional()?;
match row {
Some((digest, _)) if digest != self.digest => Err(crate::store::invalid(
"cross_root_operation_digest_conflict",
)),
Some((_, receipt)) => Ok(Some(serde_json::from_str(&receipt)?)),
None => Ok(None),
}
}
pub fn record(
&self,
db: &Connection,
receipt: &Value,
input: Option<&Value>,
) -> Result<(), StoreError> {
db.execute(
"INSERT INTO agent_cross_root_inbox(source_root, op_id, digest, receipt_json, input_json) VALUES(?,?,?,?,?)",
params![
self.source_root, self.op_id.to_string(), self.digest, serde_json::to_string(receipt)?,
input.map(serde_json::to_string).transpose()?,
],
)?;
Ok(())
}
}
impl Query for Inbox {
type Output = Option<Value>;
fn execute(self, db: &Connection) -> Result<Self::Output, StoreError> {
self.read(db)
}
}
pub struct Outgoing {
pub op_id: Uuid,
pub request: Value,
}
impl Outgoing {
fn target_root(&self) -> Option<&str> {
self.request
.pointer("/operation/targetRoot")
.and_then(Value::as_str)
}
pub fn insert(
&self,
db: &Connection,
owner: &RunOwner,
room: Option<&str>,
) -> Result<(), StoreError> {
db.execute(
"INSERT INTO agent_cross_root_outbox(owner, op_id, room, target_root, request_json) VALUES(?,?,?,?,?)",
params![
serde_json::to_string(owner)?,
self.op_id.to_string(),
room,
self.target_root(),
serde_json::to_string(&self.request)?
],
)?;
Ok(())
}
}
/// A direct dispatch can complete before the sending Host observes its response.
pub struct RecordDirectDispatch {
pub owner: RunOwner,
pub outgoing: Outgoing,
}
impl Statement for RecordDirectDispatch {
type Value = ();
type Output = ();
fn execute(&self, db: &Connection) -> Result<Prepared<()>, StoreError> {
let owner = serde_json::to_string(&self.owner)?;
let id = self.outgoing.op_id.to_string();
let request = serde_json::to_string(&self.outgoing.request)?;
let changed = db.execute(
"INSERT INTO agent_cross_root_outbox(owner, op_id, target_root, request_json, next_attempt)
VALUES(?,?,?,?,NULL) ON CONFLICT(owner, op_id) DO NOTHING",
params![owner, id, self.outgoing.target_root(), request],
)? != 0;
if !changed {
let original: String = db.query_row(
"SELECT request_json FROM agent_cross_root_outbox WHERE owner=? AND op_id=?",
params![owner, id],
|row| row.get(0),
)?;
if original != request {
return Err(crate::store::invalid(
"cross_root_operation_digest_conflict",
));
}
}
Ok(Prepared {
value: (),
changed,
notification: Notification::NONE,
})
}
fn committed((): ()) {}
fn isolated_rejection(error: &StoreError) -> bool {
Inbox::is_conflict(error)
}
}
pub struct OriginalDirectDispatch {
pub owner: RunOwner,
pub op_id: Uuid,
pub target_root: String,
pub worker_session: String,
pub caller_session: String,
}
impl OriginalDirectDispatch {
pub fn verify(&self, db: &Connection) -> Result<(), StoreError> {
let matches: bool = db.query_row(
"SELECT EXISTS(SELECT 1 FROM agent_cross_root_outbox WHERE owner=?1 AND op_id=?2 AND room IS NULL
AND json_extract(request_json, '$.operation.targetRoot')=?3
AND json_extract(request_json, '$.operation.action.kind')='send'
AND json_extract(request_json, '$.operation.action.input.sessionId')=?4
AND json_extract(request_json, '$.operation.action.caller.sessionId')=?5
AND json_extract(request_json, '$.operation.action.input.onComplete') IS NOT 'none')",
params![serde_json::to_string(&self.owner)?, self.op_id.to_string(),
self.target_root, self.worker_session, self.caller_session],
|row| row.get(0),
)?;
if !matches {
return Err(crate::store::invalid(
"cross_root_completion_without_original_delivery",
));
}
Ok(())
}
pub fn is_missing(error: &StoreError) -> bool {
matches!(error.underlying(), StoreError::InvalidTransition(reason)
if reason == "cross_root_completion_without_original_delivery")
}
}
pub struct PendingOutboxEntry {
pub op_id: String,
pub target_root: String,
pub room: Option<String>,
pub next_attempt: i64,
pub attempts: u32,
pub request: Value,
}
pub struct OutboxBatch {
pub ready: Vec<PendingOutboxEntry>,
pub next_wake_at: Option<i64>,
}
/// Fetches at most one due outgoing operation per distinct `target_root` so an offline
/// peer never head-of-line blocks deliveries to online peers, plus the earliest future
/// retry timestamp across all roots.
pub struct NextOutgoingPerRoot {
pub owner: RunOwner,
pub now: i64,
pub exclude_roots: Vec<String>,
pub limit: usize,
}
impl Query for NextOutgoingPerRoot {
type Output = OutboxBatch;
fn execute(self, db: &Connection) -> Result<Self::Output, StoreError> {
use rusqlite::{params_from_iter, types::Value as SqlValue};
let owner = serde_json::to_string(&self.owner)?;
let limit = self.limit.clamp(1, 16);
let exclude_clause = if self.exclude_roots.is_empty() {
String::new()
} else {
let slots = (0..self.exclude_roots.len())
.map(|i| format!("?{}", i + 3))
.collect::<Vec<_>>()
.join(",");
format!(" AND target_root NOT IN ({slots})")
};
let mut base_params: Vec<SqlValue> = Vec::with_capacity(self.exclude_roots.len() + 3);
base_params.push(owner.into());
base_params.push(self.now.into());
for root in &self.exclude_roots {
base_params.push(root.clone().into());
}
let limit_param_idx = base_params.len() + 1;
let ready_sql = format!(
"SELECT op_id, target_root, room, next_attempt, attempts, request_json
FROM (
SELECT op_id, target_root, room, next_attempt, attempts, request_json,
ROW_NUMBER() OVER (
PARTITION BY target_root
ORDER BY next_attempt ASC, op_id ASC
) AS rn
FROM agent_cross_root_outbox
WHERE owner=?1 AND next_attempt IS NOT NULL AND next_attempt <= ?2{exclude_clause}
)
WHERE rn = 1
ORDER BY next_attempt ASC, op_id ASC
LIMIT ?{limit_param_idx}"
);
let mut ready_params = base_params.clone();
ready_params.push((limit as i64).into());
let mut ready = Vec::new();
{
let mut ready_stmt = db.prepare(&ready_sql)?;
let mut rows = ready_stmt.query(params_from_iter(ready_params))?;
while let Some(row) = rows.next()? {
let op_id: String = row.get(0)?;
let target_root: String = row.get::<_, Option<String>>(1)?.unwrap_or_default();
let room: Option<String> = row.get(2)?;
let next_attempt: i64 = row.get(3)?;
let attempts = u32::try_from(row.get::<_, i64>(4)?.max(0)).unwrap_or(u32::MAX);
let raw: String = row.get(5)?;
ready.push(PendingOutboxEntry {
op_id,
target_root,
room,
next_attempt,
attempts,
request: serde_json::from_str(&raw)?,
});
}
}
let wake_sql = format!(
"SELECT MIN(next_attempt) FROM agent_cross_root_outbox
WHERE owner=?1 AND next_attempt IS NOT NULL AND next_attempt > ?2{exclude_clause}"
);
let next_wake_at: Option<i64> = db
.prepare(&wake_sql)?
.query_row(params_from_iter(base_params), |row| row.get(0))
.optional()?
.flatten();
Ok(OutboxBatch {
ready,
next_wake_at,
})
}
}
pub enum Dispatch {
RetryAt { next_attempt: i64, error: String },
Settled(Value),
}
pub struct SetDispatch {
pub owner: RunOwner,
pub op_id: String,
pub result: Dispatch,
}
impl Statement for SetDispatch {
type Value = ();
type Output = ();
fn execute(&self, db: &Connection) -> Result<Prepared<()>, StoreError> {
let owner = serde_json::to_string(&self.owner)?;
let changed = match &self.result {
Dispatch::RetryAt {
next_attempt,
error,
} => db.execute(
"UPDATE agent_cross_root_outbox
SET next_attempt=?, attempts=attempts+1, last_error=?
WHERE owner=? AND op_id=? AND next_attempt IS NOT NULL AND remote_status IS NULL",
params![next_attempt, error, owner, self.op_id],
)?,
Dispatch::Settled(receipt) => {
let room: Option<Option<String>> = db
.query_row(
"UPDATE agent_cross_root_outbox
SET next_attempt=NULL, last_error=NULL, receipt_json=?
WHERE owner=? AND op_id=? AND next_attempt IS NOT NULL AND remote_status IS NULL RETURNING room",
params![serde_json::to_string(receipt)?, owner, self.op_id],
|row| row.get(0),
)
.optional()?;
if let Some(Some(room)) = room {
db.execute(
"UPDATE agent_rooms SET revision=revision+1 WHERE owner=? AND session=?",
params![owner, room],
)?;
return Ok(Prepared {
value: (),
changed: true,
notification: Notification::METADATA.with_sessions([room]),
});
}
usize::from(room.is_some())
}
};
Ok(Prepared {
value: (),
changed: changed != 0,
notification: Notification::NONE,
})
}
fn committed((): ()) {}
fn isolated_rejection(_: &StoreError) -> bool {
false
}
}
/// Resets backed-off outbox items targeting a peer that just transitioned online so
/// queued wakes and completions deliver immediately instead of waiting for backoff expiry.
pub struct WakeRootOutbox {
pub owner: RunOwner,
pub target_root: String,
pub now: i64,
}
impl Statement for WakeRootOutbox {
type Value = usize;
type Output = usize;
fn execute(&self, db: &Connection) -> Result<Prepared<usize>, StoreError> {
let owner = serde_json::to_string(&self.owner)?;
let changed = db.execute(
"UPDATE agent_cross_root_outbox
SET next_attempt=?1, attempts=0
WHERE owner=?2
AND target_root=?3
AND next_attempt IS NOT NULL
AND next_attempt > ?1",
params![self.now, owner, self.target_root],
)?;
Ok(Prepared {
value: changed,
changed: changed != 0,
notification: if changed != 0 {
Notification::METADATA
} else {
Notification::NONE
},
})
}
fn committed(value: usize) -> usize {
value
}
fn isolated_rejection(_: &StoreError) -> bool {
false
}
}
/// Settles a remote Room wake completion directly on `agent_cross_root_outbox` so the
/// Room UI updates its `deliveryStates` pills without posting noisy robot receipt text.
pub struct SettleRoomRemoteCompletion {
pub inbox: Inbox,
pub owner: RunOwner,
pub original_op_id: Uuid,
pub session_id: String,
pub source_message_id: String,
pub worker_session_id: String,
pub status: &'static str,
pub error: Option<String>,
}
impl Statement for SettleRoomRemoteCompletion {
type Value = Value;
type Output = Value;
fn execute(&self, db: &Connection) -> Result<Prepared<Value>, StoreError> {
if let Some(receipt) = self.inbox.read(db)? {
return Ok(Prepared {
value: receipt,
changed: false,
notification: Notification::NONE,
});
}
let owner = serde_json::to_string(&self.owner)?;
let matched: bool = db.query_row(
"SELECT EXISTS(SELECT 1 FROM agent_cross_root_outbox WHERE owner=?1 AND op_id=?2 AND room=?3
AND json_extract(request_json, '$.operation.targetRoot')=?4
AND json_extract(request_json, '$.operation.action.kind')='wake'
AND json_extract(request_json, '$.operation.action.sourceRoomId')=?3
AND json_extract(request_json, '$.operation.action.sourceMessageId')=?5
AND json_extract(request_json, '$.operation.action.targetSessionId')=?6)",
params![
owner,
self.original_op_id.to_string(),
self.session_id,
self.inbox.source_root,
self.source_message_id,
self.worker_session_id,
],
|row| row.get(0),
)?;
if !matched {
return Err(crate::store::invalid(
"cross_root_completion_without_original_delivery",
));
}
let last_error = if self.status == "failed" {
self.error.as_deref()
} else {
None
};
db.execute(
"UPDATE agent_cross_root_outbox
SET next_attempt=NULL, remote_status=?1, last_error=?2
WHERE owner=?3 AND op_id=?4 AND room=?5",
params![
self.status,
last_error,
owner,
self.original_op_id.to_string(),
self.session_id,
],
)?;
db.execute(
"UPDATE agent_rooms SET revision=revision+1 WHERE owner=? AND session=?",
params![owner, self.session_id],
)?;
let receipt = serde_json::json!({
"kind": "room_completion_settled",
"sessionId": self.session_id,
"messageId": self.source_message_id,
"status": self.status,
});
self.inbox.record(db, &receipt, None)?;
Ok(Prepared {
value: receipt,
changed: true,
notification: Notification::METADATA.with_sessions([self.session_id.clone()]),
})
}
fn committed(value: Value) -> Value {
value
}
fn isolated_rejection(error: &StoreError) -> bool {
Inbox::is_conflict(error) || OriginalDirectDispatch::is_missing(error)
}
}
pub struct Watch {
pub session: String,
pub message: String,
pub route: Value,
}
impl Watch {
pub fn insert(&self, db: &Connection, owner: &RunOwner) -> Result<(), StoreError> {
db.execute(
"INSERT INTO agent_cross_root_watches(owner, session, message, route_json) VALUES(?,?,?,?)",
params![serde_json::to_string(owner)?, self.session, self.message, serde_json::to_string(&self.route)?],
)?;
Ok(())
}
}
pub struct PendingWatches {
pub owner: RunOwner,
pub after: Option<(String, String)>,
}
impl Query for PendingWatches {
type Output = Vec<Watch>;
fn execute(self, db: &Connection) -> Result<Self::Output, StoreError> {
let (session, message) = self.after.unwrap_or_default();
let mut statement = db.prepare_cached(
"SELECT w.session, w.message, w.route_json FROM agent_cross_root_watches w
LEFT JOIN agent_queue_items q ON q.session=w.session AND q.message=w.message
WHERE w.owner=? AND (w.session, w.message)>(?,?) AND q.state IS NOT 'pending'
ORDER BY w.session, w.message LIMIT 64",
)?;
let mut rows = statement.query(params![
serde_json::to_string(&self.owner)?,
session,
message
])?;
let mut watches = Vec::new();
while let Some(row) = rows.next()? {
watches.push(Watch {
session: row.get(0)?,
message: row.get(1)?,
route: serde_json::from_str(&row.get::<_, String>(2)?)?,
});
}
Ok(watches)
}
}
pub struct PublishCompletion {
pub owner: RunOwner,
pub watch: Watch,
pub outgoing: Outgoing,
}
impl Statement for PublishCompletion {
type Value = ();
type Output = ();
fn execute(&self, db: &Connection) -> Result<Prepared<()>, StoreError> {
let changed = db.execute(
"DELETE FROM agent_cross_root_watches WHERE owner=? AND session=? AND message=?",
params![
serde_json::to_string(&self.owner)?,
self.watch.session,
self.watch.message
],
)? != 0;
if changed {
self.outgoing.insert(db, &self.owner, None)?;
}
Ok(Prepared {
value: (),
changed,
notification: Notification::METADATA,
})
}
fn committed((): ()) {}
fn isolated_rejection(_: &StoreError) -> bool {
false
}
}
#[cfg(test)]
mod tests {
use super::*;
fn test_owner() -> RunOwner {
RunOwner {
deployment: Uuid::nil(),
namespace: maka_plugin_core::composition::InstanceId(vec![Uuid::nil()]),
}
}
fn open_db() -> Connection {
let db = Connection::open_in_memory().unwrap();
db.pragma_update(None, "foreign_keys", "ON").unwrap();
let catalog: Vec<_> = maka_event_log::ROOT_MIGRATIONS
.iter()
.chain(crate::MIGRATIONS)
.copied()
.collect();
maka_event_log::migration::run(&db, &catalog).unwrap();
db
}
#[test]
fn completion_settling_before_dispatch_blocks_stale_retry_and_error_clear() {
let db = open_db();
db.execute(
"INSERT INTO session_control(id, fingerprint, revision, created_at, updated_at, archived, configuration)
VALUES('room-1', 'fp', 1, 1, 1, 0, '{}')",
[],
)
.unwrap();
let owner = test_owner();
db.execute(
"INSERT INTO agent_rooms(owner, session, revision) VALUES(?1, 'room-1', 1)",
[serde_json::to_string(&owner).unwrap()],
)
.unwrap();
let op_id = Uuid::new_v4();
let outgoing = Outgoing {
op_id,
request: serde_json::json!({
"operation": {
"targetRoot": "root-b",
"action": {
"kind": "wake",
"sourceRoomId": "room-1",
"sourceMessageId": "msg-1",
"targetSessionId": "worker-b"
}
}
}),
};
outgoing.insert(&db, &owner, Some("room-1")).unwrap();
let settle = SettleRoomRemoteCompletion {
inbox: Inbox {
op_id: Uuid::new_v4(),
source_root: "root-b".into(),
digest: "sha256:test".into(),
},
owner: owner.clone(),
original_op_id: op_id,
session_id: "room-1".into(),
source_message_id: "msg-1".into(),
worker_session_id: "worker-b".into(),
status: "failed",
error: Some("worker crashed".into()),
};
settle.execute(&db).unwrap();
let late_retry = SetDispatch {
owner: owner.clone(),
op_id: op_id.to_string(),
result: Dispatch::RetryAt {
next_attempt: 99_999,
error: "stale ack timeout".into(),
},
};
assert!(!late_retry.execute(&db).unwrap().changed);
let late_settled = SetDispatch {
owner: owner.clone(),
op_id: op_id.to_string(),
result: Dispatch::Settled(serde_json::json!({"kind": "queued"})),
};
assert!(!late_settled.execute(&db).unwrap().changed);
let (next_attempt, remote_status, last_error): (Option<i64>, Option<String>, Option<String>) =
db.query_row(
"SELECT next_attempt, remote_status, last_error FROM agent_cross_root_outbox WHERE op_id=?1",
[op_id.to_string()],
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
)
.unwrap();
assert_eq!(next_attempt, None);
assert_eq!(remote_status.as_deref(), Some("failed"));
assert_eq!(last_error.as_deref(), Some("worker crashed"));
}
}