Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(agent-session): stream log runs to GraphQL over a Redis Stream with acks (#7987)
Eric Hayesa9d19b1415a0
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex bff9b218a5..28c4828e1c 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -440,6 +440,7 @@"crates/agent_inmem","crates/agent_runtime_protocol","crates/agent_session",+ "crates/agent_session_realtime","crates/agent_trigger","crates/ai_billing","crates/ai_engine",diff --git a/Cargo.lock b/Cargo.lockindex b4de1710d0..743563e23d 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -414,6 +414,7 @@ dependencies = ["agent_inmem","agent_runtime_protocol","agent_session",+ "agent_session_realtime","agent_trigger","ai_billing","ai_tools",@@ -681,14 +682,14 @@ dependencies = [name = "agent_session_realtime"version = "0.1.0"dependencies = [+ "agent-client-protocol","agent_runtime_protocol","agent_session","broadcast","chrono",- "kafka_util",- "macro_event_broker",+ "macro_env_var","macro_uuid",- "rdkafka",+ "redis","rootcause","serde_json","tokio",diff --git a/crates/agent_session/src/domain/events.rs b/crates/agent_session/src/domain/events.rsindex 457a4745b5..0b775a89bb 100644--- a/crates/agent_session/src/domain/events.rs+++ b/crates/agent_session/src/domain/events.rs@@ -16,7 +16,7 @@ mod test;use agent_runtime_protocol::domain::action::AgentActionId;use bots::domain::models::BotId;use macro_event_broker::{Event, MacroEvent, TopicEvent};-use macro_event_topics::{MacroAgentSessionLifecycleTopic, MacroAgentSessionLogTopic};+use macro_event_topics::MacroAgentSessionLifecycleTopic;use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;use messages::domain::models::MessageParent;@@ -466,39 +466,10 @@ impl MacroEvent for AgentSessionLifecycleMacroEvent {}}-/// A run of frames appended to a session's log, published to-/// [`MacroAgentSessionLogTopic`] and keyed by session id.-///-/// The connection gateway pushes the same run to the viewers this process-/// knows about; this is for a process that serves viewers of its own, such-/// as the GraphQL subscription in document storage. Each entry is exactly-/// the stored row, so a subscriber folds the same bytes a reader of the-/// durable log does.-#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(tag = "event_type", content = "metadata")]-pub enum AgentSessionLogTopicEvent {- /// Frames were appended to the log, in log order.- #[serde(rename = "agent_session_log.appended")]- Appended(LogAppendedMetadata),-}--impl AgentSessionLogTopicEvent {- /// The session the frames belong to.- #[must_use]- pub fn session_id(&self) -> AgentSessionId {- match self {- Self::Appended(metadata) => metadata.agent_session_id,- }- }-}--impl TopicEvent for AgentSessionLogTopicEvent {- type Topic = MacroAgentSessionLogTopic;-- const SCHEMA_VERSION: u8 = 1;-}--/// The frames one flush appended, as the log stored them.+/// The frames one flush appended, as the log stored them: what the harness+/// hands to a process serving viewers of its own, such as the GraphQL+/// subscription in document storage. Each entry is exactly the stored row, so+/// a subscriber folds the same bytes a reader of the durable log does.#[derive(Debug, Clone, Serialize, Deserialize)]pub struct LogAppendedMetadata {/// The session the frames belong to.@@ -520,9 +491,9 @@ pub struct LogAppendedEntry {pub content: Message,}-impl From<&LogAppended> for AgentSessionLogTopicEvent {+impl From<&LogAppended> for LogAppendedMetadata {fn from(event: &LogAppended) -> Self {- Self::Appended(LogAppendedMetadata {+ Self {agent_session_id: event.agent_session_id,entries: event.entries@@ -534,7 +505,7 @@ impl From<&LogAppended> for AgentSessionLogTopicEvent {content: stored.entry.content.clone(),}).collect(),- })+ }}}@@ -558,44 +529,3 @@ impl LogAppendedMetadata {.collect()}}--/// Publishable event for [`MacroAgentSessionLogTopic`], keyed by session id-/// so one session's frames stay in order on one partition.-#[derive(Debug, Clone)]-pub struct AgentSessionLogMacroEvent {- key: String,- event: Event<AgentSessionLogTopicEvent>,-}--impl AgentSessionLogMacroEvent {- /// Wrap a run of frames for publication.- #[must_use]- pub fn new(event: AgentSessionLogTopicEvent) -> Self {- Self {- key: event.session_id().to_string(),- event: Event::new(event),- }- }-- /// The run this event carries.- #[must_use]- pub fn into_payload(self) -> AgentSessionLogTopicEvent {- self.event.event- }-}--impl MacroEvent for AgentSessionLogMacroEvent {- type EventPayload = AgentSessionLogTopicEvent;-- fn key(&self) -> &str {- &self.key- }-- fn event(&self) -> &Event<Self::EventPayload> {- &self.event- }-- fn from_event(key: String, event: Event<Self::EventPayload>) -> Self {- Self { key, event }- }-}diff --git a/crates/agent_session/src/outbound/broker_log_realtime.rs b/crates/agent_session/src/outbound/broker_log_realtime.rsdeleted file mode 100644index 01f4b8e629..0000000000--- a/crates/agent_session/src/outbound/broker_log_realtime.rs+++ /dev/null@@ -1,82 +0,0 @@-//! [`AgentSessionRealtime`] that also publishes each appended run to the-//! event broker, so a process serving viewers of its own - the GraphQL-//! subscription in document storage - hears the frames too.--#[cfg(test)]-mod test;--use crate::domain::events::{AgentSessionLogMacroEvent, AgentSessionLogTopicEvent};-use crate::domain::model::{AgentSessionId, AgentSessionRenamed, LogAppended};-use crate::domain::ports::{AgentSessionQueueChanged, AgentSessionRealtime};-use macro_event_broker::MacroEventBroker;--/// `inner` keeps doing what it does; each run of frames is published to-/// `macro.agent_session_log` as well. The broker publish is best effort, as-/// the port allows: a refusal is logged and the inner result is returned.-#[derive(Debug, Clone)]-pub struct BrokerLogRealtime<Inner, Broker> {- inner: Inner,- broker: Broker,-}--impl<Inner, Broker> BrokerLogRealtime<Inner, Broker> {- /// Publish through `inner`, and each log run through `broker` too.- pub fn new(inner: Inner, broker: Broker) -> Self {- Self { inner, broker }- }-}--impl<Inner, Broker> AgentSessionRealtime for BrokerLogRealtime<Inner, Broker>-where- Inner: AgentSessionRealtime + Sync,- Broker: MacroEventBroker + Sync,-{- async fn publish(&self, event: LogAppended) -> Result<(), rootcause::Report> {- let session_id = event.agent_session_id;- let macro_event = AgentSessionLogMacroEvent::new(AgentSessionLogTopicEvent::from(&event));- let inner = self.inner.publish(event).await;- let published = match self.broker.send_event(¯o_event) {- Ok(handle) => match handle.await {- Ok(result) => result.map_err(|error| error.to_string()),- Err(join_error) => Err(join_error.to_string()),- },- Err(error) => Err(error.to_string()),- };- if let Err(error) = published {- tracing::warn!(- %error,- %session_id,- "failed to publish appended agent session log frames to the broker"- );- }- inner- }-- fn publish_updated(- &self,- session: AgentSessionId,- ) -> impl Future<Output = Result<(), rootcause::Report>> + Send {- self.inner.publish_updated(session)- }-- fn publish_renamed(- &self,- event: AgentSessionRenamed,- ) -> impl Future<Output = Result<(), rootcause::Report>> + Send {- self.inner.publish_renamed(event)- }-- fn publish_queue_changed(- &self,- event: AgentSessionQueueChanged,- ) -> impl Future<Output = Result<(), rootcause::Report>> + Send {- self.inner.publish_queue_changed(event)- }-- fn publish_changes_updated(- &self,- session: AgentSessionId,- ) -> impl Future<Output = Result<(), rootcause::Report>> + Send {- self.inner.publish_changes_updated(session)- }-}diff --git a/crates/agent_session/src/outbound/broker_log_realtime/test.rs b/crates/agent_session/src/outbound/broker_log_realtime/test.rsdeleted file mode 100644index 8fff5ef743..0000000000--- a/crates/agent_session/src/outbound/broker_log_realtime/test.rs+++ /dev/null@@ -1,123 +0,0 @@-use std::sync::{Arc, Mutex};--use agent_runtime_protocol::domain::schema::v0::{SystemEvent, ToServerMessage};-use macro_event_broker::{EventBrokerError, MacroEvent, MacroEventBroker};-use macro_uuid::Uuid;--use super::BrokerLogRealtime;-use crate::domain::model::{- AgentSessionId, AgentSessionLog, LogAppended, Message, StoredAgentSessionLog,-};-use crate::domain::ports::{AgentSessionRealtime, NoOpRealtime};--#[derive(Debug, Clone)]-struct Published {- topic: String,- key: String,- envelope: serde_json::Value,-}--/// Records what was handed to the broker, or refuses everything.-#[derive(Clone, Default)]-struct FakeBroker {- published: Arc<Mutex<Vec<Published>>>,- refuses: bool,-}--impl MacroEventBroker for FakeBroker {- fn send_event<E: MacroEvent + ?Sized>(- &self,- event: &E,- ) -> Result<tokio::task::JoinHandle<Result<(), EventBrokerError>>, EventBrokerError> {- self.published- .lock()- .expect("fake broker is not poisoned")- .push(Published {- topic: event.topic().to_string(),- key: event.key().to_string(),- envelope: serde_json::to_value(event.event())?,- });- let refuses = self.refuses;- Ok(tokio::spawn(async move {- if refuses {- Err(EventBrokerError::UnknownTopic("refused".to_owned()))- } else {- Ok(())- }- }))- }-}--/// Counts what the wrapped realtime was handed.-#[derive(Clone, Default)]-struct CountingRealtime {- published: Arc<Mutex<usize>>,-}--impl AgentSessionRealtime for CountingRealtime {- async fn publish(&self, _event: LogAppended) -> Result<(), rootcause::Report> {- *self.published.lock().expect("not poisoned") += 1;- Ok(())- }-}--fn appended() -> LogAppended {- LogAppended {- turn_state: None,- agent_session_id: AgentSessionId::TEST_A,- entries: vec![StoredAgentSessionLog {- id: Uuid::from_u128(1),- created_at: chrono::Utc::now(),- entry: AgentSessionLog {- agent_session_id: AgentSessionId::TEST_A,- user_id: None,- content: Message::ToServer(ToServerMessage::Event {- event: SystemEvent::AcpReady,- }),- },- }],- }-}--#[tokio::test]-async fn publishes_the_run_to_both_the_inner_realtime_and_the_log_topic() {- let broker = FakeBroker::default();- let inner = CountingRealtime::default();- let realtime = BrokerLogRealtime::new(inner.clone(), broker.clone());-- realtime.publish(appended()).await.expect("published");-- assert_eq!(*inner.published.lock().expect("not poisoned"), 1);- let published = broker- .published- .lock()- .expect("fake broker is not poisoned");- assert_eq!(published.len(), 1);- assert_eq!(published[0].topic, "macro.agent_session_log");- assert_eq!(published[0].key, AgentSessionId::TEST_A.to_string());- assert_eq!(- published[0].envelope["event_type"],- "agent_session_log.appended"- );- assert_eq!(published[0].envelope["schema_version"], 1);- let entries = published[0].envelope["metadata"]["entries"]- .as_array()- .expect("entries");- assert_eq!(entries.len(), 1);- assert_eq!(entries[0]["id"], Uuid::from_u128(1).to_string());- assert_eq!(entries[0]["content"]["direction"], "to_server");-}--#[tokio::test]-async fn a_refused_broker_publish_does_not_fail_the_append() {- let broker = FakeBroker {- refuses: true,- ..FakeBroker::default()- };- let realtime = BrokerLogRealtime::new(NoOpRealtime, broker.clone());-- realtime- .publish(appended())- .await- .expect("inner result wins");-}diff --git a/crates/agent_session/src/outbound/mod.rs b/crates/agent_session/src/outbound/mod.rsindex 4dbf95a72f..c7033f8b55 100644--- a/crates/agent_session/src/outbound/mod.rs+++ b/crates/agent_session/src/outbound/mod.rs@@ -13,6 +13,3 @@ pub mod connection_gateway_realtime;/// Publishing lifecycle facts to the event broker.pub mod broker_lifecycle_publisher;--/// Mirroring each appended log run to the event broker.-pub mod broker_log_realtime;diff --git a/crates/agent_session_realtime/Cargo.toml b/crates/agent_session_realtime/Cargo.tomlindex 68669b64dd..31117c0081 100644--- a/crates/agent_session_realtime/Cargo.toml+++ b/crates/agent_session_realtime/Cargo.toml@@ -5,31 +5,39 @@ publish = falseversion = "0.1.0"[features]-# The Kafka consumer feeding the fan-out; without it only the ports and the+# The Redis Stream publisher and consumer; without it only the ports and the# fan-out service compile, for the GraphQL schema crate.-consumer = [- "dep:kafka_util",- "dep:rdkafka",- "macro_event_broker/outbound",+default = ["redis"]+redis = [+ "dep:chrono",+ "dep:macro_uuid",+ "dep:redis",+ "dep:serde_json",]-default = ["consumer"][dependencies]agent_session = { path = "../agent_session", default-features = false }broadcast = { path = "../broadcast" }-kafka_util = { path = "../kafka_util", optional = true }-macro_event_broker = { path = "../macro_event_broker", default-features = false }-rdkafka = { workspace = true, optional = true }+chrono = { workspace = true, optional = true }+macro_uuid = { path = "../macro_uuid", optional = true }+redis = { workspace = true, optional = true, features = [+ "aio",+ "streams",+ "tokio-comp",+] }rootcause = { workspace = true }+serde_json = { workspace = true, optional = true }tokio = { workspace = true, features = ["sync", "time"] }tokio-retry = { workspace = true }tracing = { workspace = true }workspace-hack = { version = "0.1", path = "../workspace-hack" }[dev-dependencies]+agent-client-protocol = { workspace = true }agent_runtime_protocol = { path = "../agent_runtime_protocol" }agent_session = { path = "../agent_session", default-features = false, features = ["test-utils"] }chrono = { workspace = true }+macro_env_var = { path = "../macro_env_var" }macro_uuid = { path = "../macro_uuid" }serde_json = { workspace = true }tokio = { workspace = true, features = ["macros", "rt-multi-thread", "test-util", "time"] }diff --git a/crates/agent_session_realtime/src/domain/ports.rs b/crates/agent_session_realtime/src/domain/ports.rsindex e333543e9a..317cf79d1d 100644--- a/crates/agent_session_realtime/src/domain/ports.rs+++ b/crates/agent_session_realtime/src/domain/ports.rs@@ -6,10 +6,56 @@ use agent_session::domain::events::LogAppendedMetadata;use agent_session::domain::model::{AgentSessionId, StoredAgentSessionLog};use rootcause::Report;-/// Receives runs of appended frames from wherever the harness published them.+/// The transport's name for one delivery of a run, handed back to+/// acknowledge it. Opaque outside the adapter that minted it.+#[derive(Debug, Clone, PartialEq, Eq, Hash)]+pub struct DeliveryId(String);++impl DeliveryId {+ /// Wrap a transport's delivery id.+ #[must_use]+ pub fn new(id: impl Into<String>) -> Self {+ Self(id.into())+ }++ /// The transport's delivery id.+ #[must_use]+ pub fn as_str(&self) -> &str {+ &self.0+ }+}++impl std::fmt::Display for DeliveryId {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str(&self.0)+ }+}++/// One run as the transport delivered it.+#[derive(Debug, Clone)]+pub struct ReceivedRun {+ /// The frames.+ pub run: LogAppendedMetadata,+ /// What acknowledging this delivery takes.+ pub delivery: DeliveryId,+ /// Whether the transport delivered this run before without it being+ /// acknowledged: a subscriber may already hold some of its rows.+ pub redelivered: bool,+}++/// Receives runs of appended frames from wherever the harness published them,+/// at least once each.+///+/// A run stays owed to this process until it is acknowledged: a run received+/// but never acknowledged is delivered again, so a subscriber folds by row id+/// and tolerates seeing a row twice.pub trait AgentSessionLogConsumer: Send + Sync + 'static {- /// Waits for and returns the next appended run.- fn recv(&self) -> impl Future<Output = Result<LogAppendedMetadata, Report>> + Send;+ /// Waits for and returns the next run owed to this process.+ fn recv(&self) -> impl Future<Output = Result<ReceivedRun, Report>> + Send;++ /// Acknowledge a delivery once its run reached every subscriber it had,+ /// so it is not delivered again.+ fn ack(&self, delivery: &DeliveryId) -> impl Future<Output = Result<(), Report>> + Send;}/// Session-scoped subscriptions to received runs of frames.diff --git a/crates/agent_session_realtime/src/domain/service.rs b/crates/agent_session_realtime/src/domain/service.rsindex fad6340f24..57c3d1e55d 100644--- a/crates/agent_session_realtime/src/domain/service.rs+++ b/crates/agent_session_realtime/src/domain/service.rs@@ -3,14 +3,17 @@#[cfg(test)]mod test;-use std::{num::NonZeroUsize, time::Duration};+use std::{+ num::NonZeroUsize,+ time::{Duration, Instant},+};use agent_session::domain::model::{AgentSessionId, StoredAgentSessionLog};use broadcast::{BroadcastManager, GlobalSpawner};use rootcause::prelude::{Report, ResultExt as _};use tokio_retry::{Retry, strategy::ExponentialBackoff};-use super::ports::{AgentSessionLogConsumer, AgentSessionLogSubscriptionService};+use super::ports::{AgentSessionLogConsumer, AgentSessionLogSubscriptionService, ReceivedRun};/// Runs retained by each session-keyed broadcast channel.const BROADCAST_BUFFER_CAPACITY: NonZeroUsize = NonZeroUsize::new(64).unwrap();@@ -47,6 +50,13 @@ where}}+ /// The consumer feeding the fan-out, for its own lifecycle - closing it+ /// on shutdown, say.+ #[must_use]+ pub fn consumer(&self) -> &C {+ &self.consumer+ }+/// Subscribes to runs appended to `session_id`.////// The receiver is closed if its buffer fills, so a slow subscriber@@ -63,32 +73,90 @@ where/// Receives runs and distributes them until reception fails for good.///- /// Run this in a supervised task. A run for a session nobody subscribed- /// to is dropped: the durable log already has it.+ /// Run this in a supervised task. Each run is acknowledged once it was+ /// handed to the session's subscribers, and a run for a session nobody+ /// here subscribed to is acknowledged straight away: the durable log+ /// already has it. A failed acknowledgement is logged, not fatal; the run+ /// is delivered again, and subscribers fold by row id.#[tracing::instrument(skip(self), err)]pub async fn run(&self) -> Result<(), Report> {loop {- let appended = Retry::start(receive_retry_strategy(), || self.consumer.recv())+ let received = Retry::start(receive_retry_strategy(), || self.consumer.recv()).await.context(format!("failed to receive appended agent session log frames after {MAX_RECEIVE_ATTEMPTS} attempts"))?;- let session_id = appended.agent_session_id;- match self.broadcasts.publish(&session_id, appended.into_stored()) {- Ok(subscriber_count) => tracing::trace!(- %session_id,- subscriber_count,- "distributed appended agent session log frames"- ),- Err(_) => tracing::trace!(- %session_id,- "dropping appended agent session log frames without subscribers"- ),- }+ self.distribute(received).await;+ }+ }++ /// Hand one run to its session's subscribers, then acknowledge it.+ #[tracing::instrument(+ name = "agent.session.log.fan_out",+ skip_all,+ fields(+ agent.session.id = %received.run.agent_session_id,+ agent.log.frame_count = received.run.entries.len(),+ agent.log.delivery_id = %received.delivery,+ agent.log.redelivered = received.redelivered,+ agent.log.subscriber_count = tracing::field::Empty,+ agent.log.acked = tracing::field::Empty,+ agent.log.fan_out_us = tracing::field::Empty,+ agent.log.ack_us = tracing::field::Empty,+ )+ )]+ async fn distribute(&self, received: ReceivedRun) {+ let span = tracing::Span::current();+ let ReceivedRun {+ run,+ delivery,+ redelivered,+ } = received;+ let session_id = run.agent_session_id;+ let frame_count = run.entries.len();++ let started = Instant::now();+ let subscriber_count = self+ .broadcasts+ .publish(&session_id, run.into_stored())+ .unwrap_or(0);+ span.record("agent.log.fan_out_us", elapsed_us(started));+ span.record("agent.log.subscriber_count", subscriber_count);+ if subscriber_count == 0 {+ tracing::trace!(+ %session_id,+ frame_count,+ "no subscribers for appended agent session log frames; acknowledging"+ );+ } else {+ tracing::debug!(+ %session_id,+ frame_count,+ subscriber_count,+ redelivered,+ "distributed appended agent session log frames"+ );}++ let started = Instant::now();+ let acked = self.consumer.ack(&delivery).await.inspect_err(|error| {+ tracing::warn!(+ error = ?error,+ %session_id,+ delivery = %delivery,+ "failed to acknowledge an agent session log run; it will be delivered again"+ );+ });+ span.record("agent.log.ack_us", elapsed_us(started));+ span.record("agent.log.acked", acked.is_ok());}}+/// Microseconds since `started`, saturating.+fn elapsed_us(started: Instant) -> u64 {+ u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX)+}+impl<C> AgentSessionLogSubscriptionService for AgentSessionLogConsumerService<C>whereC: AgentSessionLogConsumer,diff --git a/crates/agent_session_realtime/src/domain/service/test.rs b/crates/agent_session_realtime/src/domain/service/test.rsindex 8675d91abf..d22ff5ff3e 100644--- a/crates/agent_session_realtime/src/domain/service/test.rs+++ b/crates/agent_session_realtime/src/domain/service/test.rs@@ -7,24 +7,66 @@ use macro_uuid::Uuid;use rootcause::Report;use super::AgentSessionLogConsumerService;-use crate::domain::ports::AgentSessionLogConsumer;+use crate::domain::ports::{AgentSessionLogConsumer, DeliveryId, ReceivedRun};-/// Hands out queued runs, then blocks forever.+/// Hands out queued runs, then blocks forever; records what was acknowledged.#[derive(Clone, Default)]struct QueuedConsumer {runs: Arc<Mutex<Vec<LogAppendedMetadata>>>,+ acked: Arc<Mutex<Vec<DeliveryId>>>,+ refuses_acks: bool,+}++impl QueuedConsumer {+ fn acked(&self) -> Vec<String> {+ self.acked+ .lock()+ .expect("not poisoned")+ .iter()+ .map(|delivery| delivery.as_str().to_owned())+ .collect()+ }}impl AgentSessionLogConsumer for QueuedConsumer {- async fn recv(&self) -> Result<LogAppendedMetadata, Report> {+ async fn recv(&self) -> Result<ReceivedRun, Report> {loop {let next = self.runs.lock().expect("not poisoned").pop();match next {- Some(run) => return Ok(run),+ Some(run) => {+ let delivery = DeliveryId::new(run.entries[0].id.to_string());+ return Ok(ReceivedRun {+ run,+ delivery,+ redelivered: false,+ });+ }None => tokio::time::sleep(std::time::Duration::from_millis(5)).await,}}}++ async fn ack(&self, delivery: &DeliveryId) -> Result<(), Report> {+ if self.refuses_acks {+ return Err(rootcause::report!("refused"));+ }+ self.acked+ .lock()+ .expect("not poisoned")+ .push(delivery.clone());+ Ok(())+ }+}++/// Polls `condition` until it holds or two seconds pass.+async fn eventually(condition: impl Fn() -> bool) {+ tokio::time::timeout(std::time::Duration::from_secs(2), async {+ while !condition() {+ tokio::time::sleep(std::time::Duration::from_millis(5)).await;+ }+ })+ .await+ .expect("condition held in time");}fn run(session: AgentSessionId, ids: impl IntoIterator<Item = u128>) -> LogAppendedMetadata {@@ -84,3 +126,75 @@ async fn delivers_each_run_to_its_sessions_subscribers_as_stored_rows() {);running.abort();}++#[tokio::test]+async fn acknowledges_each_run_after_handing_it_to_subscribers() {+ let consumer = QueuedConsumer::default();+ let service = Arc::new(AgentSessionLogConsumerService::new(consumer.clone()));+ let mut a = service.subscribe(AgentSessionId::TEST_A);+ let running = tokio::spawn({+ let service = Arc::clone(&service);+ async move { service.run().await }+ });++ consumer+ .runs+ .lock()+ .expect("not poisoned")+ .push(run(AgentSessionId::TEST_A, [7]));++ tokio::time::timeout(std::time::Duration::from_secs(2), a.recv())+ .await+ .expect("delivered in time")+ .expect("open");+ eventually(|| consumer.acked() == [Uuid::from_u128(7).to_string()]).await;+ running.abort();+}++#[tokio::test]+async fn acknowledges_a_run_nobody_here_subscribed_to() {+ let consumer = QueuedConsumer::default();+ let service = Arc::new(AgentSessionLogConsumerService::new(consumer.clone()));+ let running = tokio::spawn({+ let service = Arc::clone(&service);+ async move { service.run().await }+ });++ consumer+ .runs+ .lock()+ .expect("not poisoned")+ .push(run(AgentSessionId::TEST_B, [9]));++ eventually(|| consumer.acked() == [Uuid::from_u128(9).to_string()]).await;+ running.abort();+}++#[tokio::test]+async fn a_refused_acknowledgement_does_not_stop_the_fan_out() {+ let consumer = QueuedConsumer {+ refuses_acks: true,+ ..QueuedConsumer::default()+ };+ let service = Arc::new(AgentSessionLogConsumerService::new(consumer.clone()));+ let mut a = service.subscribe(AgentSessionId::TEST_A);+ let running = tokio::spawn({+ let service = Arc::clone(&service);+ async move { service.run().await }+ });++ consumer.runs.lock().expect("not poisoned").extend([+ run(AgentSessionId::TEST_A, [2]),+ run(AgentSessionId::TEST_A, [1]),+ ]);++ for expected in [1, 2] {+ let rows = tokio::time::timeout(std::time::Duration::from_secs(2), a.recv())+ .await+ .expect("delivered in time")+ .expect("open");+ assert_eq!(rows[0].id, Uuid::from_u128(expected));+ }+ assert!(!running.is_finished(), "the fan-out keeps running");+ running.abort();+}diff --git a/crates/agent_session_realtime/src/lib.rs b/crates/agent_session_realtime/src/lib.rsindex 94bbbc1c90..3721e29832 100644--- a/crates/agent_session_realtime/src/lib.rs+++ b/crates/agent_session_realtime/src/lib.rs@@ -1,13 +1,13 @@#![deny(missing_docs)]//! Session-scoped fan-out of appended agent session log frames.//!-//! The harness publishes each run of frames it stores to-//! `macro.agent_session_log`; a process serving viewers over GraphQL consumes-//! that topic here and hands each run to whoever subscribed to the session.-//! No composition root and no tasks are started here.+//! The harness appends each run of frames it stores to a Redis Stream; a+//! process serving viewers over GraphQL reads that stream through a consumer+//! group of its own, hands each run to whoever subscribed to the session, and+//! acknowledges it. No composition root and no tasks are started here./// Ports and the fan-out service.pub mod domain;-/// The Kafka consumer feeding the fan-out.-#[cfg(feature = "consumer")]+/// The Redis Stream publisher and consumer.+#[cfg(feature = "redis")]pub mod outbound;diff --git a/crates/agent_session_realtime/src/outbound/log_topic_consumer.rs b/crates/agent_session_realtime/src/outbound/log_topic_consumer.rsdeleted file mode 100644index 1c9118834f..0000000000--- a/crates/agent_session_realtime/src/outbound/log_topic_consumer.rs+++ /dev/null@@ -1,111 +0,0 @@-//! Independent Kafka consumer of appended agent session log frames.-//!-//! Every process receives every run published after it starts: the adapter-//! manually assigns all `macro.agent_session_log` partitions without joining-//! a durable consumer group, and commits no offsets. A viewer who missed a-//! run while this process was down refetches the durable log, which is what-//! the receiver closing tells them to do.--#[cfg(test)]-mod test;--use std::time::Duration;--use agent_session::domain::events::{- AgentSessionLogMacroEvent, AgentSessionLogTopicEvent, LogAppendedMetadata,-};-use kafka_util::{InitialOffset, KafkaEventConsumer, Ungrouped};-use macro_event_broker::{- EventBrokerError, KafkaConsumerAdapter, MacroEventCollection, MacroEventConsumerService,-};-use rdkafka::message::Message as _;-use rootcause::prelude::{Report, ResultExt as _};--use crate::domain::ports::AgentSessionLogConsumer;--/// Maximum time to wait for topic metadata during partition assignment.-const TOPIC_METADATA_TIMEOUT: Duration = Duration::from_secs(10);--type IndependentKafkaConsumer = KafkaConsumerAdapter<Ungrouped, DeclaredMacroEvent>;-type LogEventConsumer = MacroEventConsumerService<DeclaredMacroEvent, IndependentKafkaConsumer>;--macro_event_broker::declare_topics!(DeclaredMacroEvent: AgentSessionLogMacroEvent);--/// Independent consumer of appended agent session log frames.-///-/// Starts at the end of every current partition, so it receives only runs-/// published after construction. Partitions added later need a new consumer.-pub struct LogTopicConsumer {- consumer: LogEventConsumer,-}--impl LogTopicConsumer {- /// Creates a consumer and assigns every current partition of the topic.- #[tracing::instrument(fields(brokers), err)]- pub fn from_env(brokers: &str) -> Result<Self, Report> {- let consumer = KafkaEventConsumer::<Ungrouped>::from_env(brokers)- .context("failed to create independent agent session log consumer")?;- let consumer =- IndependentKafkaConsumer::new(consumer, InitialOffset::Latest, TOPIC_METADATA_TIMEOUT)- .context("failed to assign agent session log topic partitions")?;- tracing::info!(- topics = ?DeclaredMacroEvent::topics(),- "independent agent session log consumer listening"- );- Ok(Self {- consumer: LogEventConsumer::new(consumer),- })- }-- /// Receives and decodes the next run.- ///- /// Cancel-safe. An unsupported schema version is a poison record and is- /// skipped; other malformed payloads are returned as errors.- pub async fn recv(&self) -> Result<LogAppendedMetadata, Report> {- loop {- let message = self- .consumer- .recv()- .await- .context("failed to receive agent session log event")?;- let event = match message.decode_payload() {- Ok(event) => event,- Err(EventBrokerError::UnsupportedSchemaVersion {- topic,- expected,- actual,- }) => {- let kafka_message = message.inner();- tracing::warn!(- topic,- expected,- actual,- partition = kafka_message.partition(),- offset = kafka_message.offset(),- "dropping agent session log event with unsupported schema version"- );- continue;- }- Err(error) => {- return Err(Report::new(error)- .context("failed to decode agent session log event")- .into_dynamic());- }- };-- return match event {- DeclaredMacroEvent::AgentSessionLogMacroEvent(event) => {- let AgentSessionLogTopicEvent::Appended(appended) = event.into_payload();- Ok(appended)- }- };- }- }-}--impl AgentSessionLogConsumer for LogTopicConsumer {- #[tracing::instrument(err, skip(self))]- async fn recv(&self) -> Result<LogAppendedMetadata, Report> {- LogTopicConsumer::recv(self).await- }-}diff --git a/crates/agent_session_realtime/src/outbound/log_topic_consumer/test.rs b/crates/agent_session_realtime/src/outbound/log_topic_consumer/test.rsdeleted file mode 100644index 03ba676ffb..0000000000--- a/crates/agent_session_realtime/src/outbound/log_topic_consumer/test.rs+++ /dev/null@@ -1,83 +0,0 @@-use agent_runtime_protocol::domain::schema::v0::{SystemEvent, ToServerMessage};-use agent_session::domain::model::Message;-use macro_event_broker::{- EventBrokerError, MacroEventCollection as _, MessageParts, MessageWrapper,-};--use super::DeclaredMacroEvent;--struct TestMessage {- payload: Vec<u8>,-}--impl MessageParts for TestMessage {- fn key(&self) -> Option<&str> {- Some("0000000a-0000-0000-0000-000000000000")- }-- fn payload(&self) -> Option<&[u8]> {- Some(&self.payload)- }-- fn topic(&self) -> &str {- "macro.agent_session_log"- }-}--#[test]-fn assigns_only_the_log_topic() {- assert_eq!(DeclaredMacroEvent::topics(), ["macro.agent_session_log"]);-}--#[test]-fn decodes_an_appended_run() {- let content = serde_json::to_value(Message::ToServer(ToServerMessage::Event {- event: SystemEvent::AcpReady,- }))- .expect("serializable");- let message = MessageWrapper::<_, DeclaredMacroEvent>::new(TestMessage {- payload: serde_json::to_vec(&serde_json::json!({- "event_id": "00000000-0000-0000-0000-000000000001",- "schema_version": 1,- "event_type": "agent_session_log.appended",- "metadata": {- "agent_session_id": "0000000a-0000-0000-0000-000000000000",- "entries": [{- "id": "00000000-0000-0000-0000-000000000001",- "created_at": "2026-08-13T12:34:56.789Z",- "user_id": null,- "content": content- }]- }- }))- .expect("serializable"),- });-- let DeclaredMacroEvent::AgentSessionLogMacroEvent(event) =- message.decode_payload().expect("decodes");- let super::AgentSessionLogTopicEvent::Appended(appended) = event.into_payload();- let rows = appended.into_stored();- assert_eq!(rows.len(), 1);- assert_eq!(- rows[0].entry.agent_session_id.to_string(),- "0000000a-0000-0000-0000-000000000000"- );-}--#[test]-fn rejects_unsupported_schema_versions() {- let message = MessageWrapper::<_, DeclaredMacroEvent>::new(TestMessage {- payload: serde_json::to_vec(&serde_json::json!({- "event_id": "00000000-0000-0000-0000-000000000001",- "schema_version": 2,- "event_type": "agent_session_log.appended",- "metadata": { "agent_session_id": "0000000a-0000-0000-0000-000000000000", "entries": [] }- }))- .expect("serializable"),- });-- assert!(matches!(- message.decode_payload(),- Err(EventBrokerError::UnsupportedSchemaVersion { .. })- ));-}diff --git a/crates/agent_session_realtime/src/outbound/mod.rs b/crates/agent_session_realtime/src/outbound/mod.rsindex f2bc298bf1..ad99aa8411 100644--- a/crates/agent_session_realtime/src/outbound/mod.rs+++ b/crates/agent_session_realtime/src/outbound/mod.rs@@ -1,4 +1,5 @@//! Transport adapters feeding the fan-out.-/// Independent Kafka consumer of `macro.agent_session_log`.-pub mod log_topic_consumer;+/// Runs of frames over a Redis Stream: the harness' publisher and the+/// consumer-group reader.+pub mod redis_stream;diff --git a/crates/agent_session_realtime/src/outbound/redis_stream.rs b/crates/agent_session_realtime/src/outbound/redis_stream.rsnew file mode 100644index 0000000000..69b462e66f--- /dev/null+++ b/crates/agent_session_realtime/src/outbound/redis_stream.rs@@ -0,0 +1,85 @@+//! Appended agent session log frames over a Redis Stream.+//!+//! The harness `XADD`s each run of frames it stores to one stream,+//! [`STREAM_KEY`]. Every process serving viewers over GraphQL reads the whole+//! stream through a consumer group of its own, so each process sees every+//! run, and acknowledges a run once it has handed it to the session's+//! subscribers. A run the process received but never acknowledged - its+//! connection dropped mid-read, say - stays pending in its group and is read+//! again once the connection is back.+//!+//! The stream carries the frames themselves rather than a pointer to them, so+//! a run's size is bounded only by Redis' 512 MiB value limit. It keeps+//! [`RETENTION`] of history: trimmed on every append by entry id, which is a+//! timestamp.++#[cfg(test)]+mod test;++/// The `XREADGROUP` consumer feeding the fan-out.+pub mod consumer;+/// The `XADD` publisher wrapping the harness' realtime.+pub mod publisher;++use std::time::Duration;++use agent_session::domain::events::LogAppendedMetadata;+use rootcause::Report;+use rootcause::prelude::ResultExt as _;++/// The one stream every run of every session is appended to.+pub const STREAM_KEY: &str = "agent_session_log:v1";++/// How long the stream keeps an entry. Long enough for a reader whose+/// connection dropped to come back and read what it missed; past it, the+/// durable log is where a viewer catches up.+pub const RETENTION: Duration = Duration::from_secs(15 * 60);++/// Prefix of every consumer group a reading process creates, so abandoned+/// groups can be told apart from anything else reading the stream.+pub const GROUP_PREFIX: &str = "agent-session-log-subscriptions:";++/// Wire format version, carried on every entry.+pub const WIRE_VERSION: u8 = 1;++/// Entry field names.+pub(crate) mod field {+ /// [`super::WIRE_VERSION`].+ pub const VERSION: &str = "v";+ /// The session the frames belong to, duplicated out of the payload so+ /// `XRANGE` in redis-cli says whose run an entry is.+ pub const SESSION: &str = "session";+ /// How many frames the payload holds.+ pub const FRAMES: &str = "frames";+ /// Unix milliseconds the publisher sent the entry at, for delivery lag.+ pub const PUBLISHED_AT_MS: &str = "published_at_ms";+ /// [`LogAppendedMetadata`] as JSON.+ pub const PAYLOAD: &str = "payload";+}++/// The JSON a run travels as.+pub(crate) fn encode(run: &LogAppendedMetadata) -> Result<String, Report> {+ Ok(serde_json::to_string(run).context("failed to encode an agent session log run")?)+}++/// A run back from its JSON.+pub(crate) fn decode(payload: &[u8]) -> Result<LogAppendedMetadata, Report> {+ Ok(serde_json::from_slice(payload).context("failed to decode an agent session log run")?)+}++/// Unix milliseconds now.+pub(crate) fn now_ms() -> u64 {+ u64::try_from(chrono::Utc::now().timestamp_millis()).unwrap_or_default()+}++/// The `MINID` that trims entries older than [`RETENTION`]: entry ids start+/// with the unix milliseconds Redis added them at.+pub(crate) fn retention_floor(now_ms: u64) -> String {+ let retention_ms = u64::try_from(RETENTION.as_millis()).unwrap_or(u64::MAX);+ format!("{}-0", now_ms.saturating_sub(retention_ms))+}++/// The unix milliseconds an entry id was assigned at.+pub(crate) fn entry_id_ms(entry_id: &str) -> Option<u64> {+ entry_id.split_once('-')?.0.parse().ok()+}diff --git a/crates/agent_session_realtime/src/outbound/redis_stream/consumer.rs b/crates/agent_session_realtime/src/outbound/redis_stream/consumer.rsnew file mode 100644index 0000000000..6af34d5e62--- /dev/null+++ b/crates/agent_session_realtime/src/outbound/redis_stream/consumer.rs@@ -0,0 +1,662 @@+#[cfg(test)]+mod test;++use std::collections::VecDeque;+use std::time::{Duration, Instant};++use redis::aio::MultiplexedConnection;+use redis::streams::{+ StreamId, StreamInfoConsumersReply, StreamInfoGroupsReply, StreamReadOptions, StreamReadReply,+};+use redis::{AsyncCommands as _, AsyncConnectionConfig, RedisError};+use rootcause::Report;+use rootcause::prelude::ResultExt as _;++use super::{GROUP_PREFIX, STREAM_KEY, WIRE_VERSION, decode, entry_id_ms, field, now_ms};+use crate::domain::ports::{AgentSessionLogConsumer, DeliveryId, ReceivedRun};++/// How long one `XREADGROUP` blocks waiting for new entries. Bounded so the+/// read loop comes back up regularly for housekeeping.+const READ_BLOCK: Duration = Duration::from_secs(5);++/// Entries one `XREADGROUP` returns at most.+const READ_COUNT: usize = 64;++/// How long connecting to Redis may take.+const CONNECT_TIMEOUT: Duration = Duration::from_secs(2);++/// How long a non-blocking command (`XACK`, `XINFO`, `XGROUP`) may take.+const COMMAND_RESPONSE_TIMEOUT: Duration = Duration::from_secs(2);++/// How often the read loop logs the stream's and this group's state.+const STATS_INTERVAL: Duration = Duration::from_secs(60);++/// How often the read loop looks for groups their process abandoned.+const REAP_INTERVAL: Duration = Duration::from_secs(10 * 60);++/// A group whose every consumer has been idle this long belongs to a process+/// that is gone: a live one reads at least every [`READ_BLOCK`].+const ABANDONED_AFTER: Duration = Duration::from_secs(60 * 60);++/// Which entries the next read asks for.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum ReadMode {+ /// This consumer's own pending entries: delivered, never acknowledged.+ /// `XREADGROUP ... 0`.+ Pending,+ /// Entries never delivered to this group. `XREADGROUP ... >`.+ New,+}++impl ReadMode {+ fn id(self) -> &'static str {+ match self {+ Self::Pending => "0",+ Self::New => ">",+ }+ }++ fn as_str(self) -> &'static str {+ match self {+ Self::Pending => "pending",+ Self::New => "new",+ }+ }+}++/// An entry read but not yet handed out, with how it was read.+struct Buffered {+ entry: StreamId,+ mode: ReadMode,+}++/// Everything the read loop owns. Behind one lock: `recv` is called by one+/// fan-out loop at a time.+struct ReadState {+ /// Dedicated to `XREADGROUP`: a blocked read holds a multiplexed+ /// connection's pipeline, so nothing else shares it.+ connection: Option<MultiplexedConnection>,+ buffered: VecDeque<Buffered>,+ mode: ReadMode,+ last_stats: Instant,+ last_reap: Instant,+}++/// Reads [`STREAM_KEY`] through a consumer group of this process' own, at+/// least once.+///+/// The group starts at the stream's end, so the process receives runs+/// appended after it started. Every run it receives stays pending in the+/// group until [`AgentSessionLogConsumer::ack`]; after any failed read the+/// consumer reconnects and first rereads its own pending entries, so a run+/// in flight when the connection dropped is delivered again rather than+/// lost.+///+/// What it does not cover: entries trimmed before this process read them+/// (older than [`super::RETENTION`]), and a group lost with Redis itself.+/// Both are logged at error.+pub struct RedisLogStreamConsumer {+ client: redis::Client,+ stream: String,+ group: String,+ consumer: String,+ state: tokio::sync::Mutex<ReadState>,+ /// For `XACK`, `XINFO` and `XGROUP`, which must not queue behind a+ /// blocked read.+ commands: tokio::sync::Mutex<Option<MultiplexedConnection>>,+}++impl RedisLogStreamConsumer {+ /// Create this process' consumer group at the stream's end and reap any+ /// group a gone process left behind.+ #[tracing::instrument(+ name = "agent.session.log_stream.connect",+ skip_all,+ err,+ fields(+ messaging.system = "redis",+ messaging.destination.name = STREAM_KEY,+ messaging.consumer.group.name = tracing::field::Empty,+ )+ )]+ pub async fn connect(client: redis::Client) -> Result<Self, Report> {+ Self::connect_to(client, STREAM_KEY.to_owned()).await+ }++ /// [`Self::connect`] to a stream other than [`STREAM_KEY`].+ pub(crate) async fn connect_to(client: redis::Client, stream: String) -> Result<Self, Report> {+ let instance = macro_uuid::generate_uuid_v7();+ let group = format!("{GROUP_PREFIX}{instance}");+ tracing::Span::current().record("messaging.consumer.group.name", group.as_str());+ let now = Instant::now();+ let consumer = Self {+ client,+ stream,+ consumer: instance.to_string(),+ group,+ state: tokio::sync::Mutex::new(ReadState {+ connection: None,+ buffered: VecDeque::new(),+ mode: ReadMode::New,+ last_stats: now,+ last_reap: now,+ }),+ commands: tokio::sync::Mutex::new(None),+ };+ consumer.create_group().await?;+ let _ = consumer.reap_abandoned_groups().await.inspect_err(|error| {+ tracing::warn!(error = ?error, "failed to reap abandoned agent session log groups");+ });+ Ok(consumer)+ }++ /// This process' consumer group.+ #[must_use]+ pub fn group(&self) -> &str {+ &self.group+ }++ /// Destroy this process' consumer group: nothing reads it once the+ /// process stops. Call on shutdown; a group left behind is reaped by+ /// another process after [`ABANDONED_AFTER`].+ #[tracing::instrument(+ name = "agent.session.log_stream.close",+ skip_all,+ err,+ fields(+ messaging.system = "redis",+ messaging.destination.name = %self.stream,+ messaging.consumer.group.name = %self.group,+ )+ )]+ pub async fn close(&self) -> Result<(), Report> {+ let mut connection = self.commands().await?;+ let destroyed: usize = connection+ .xgroup_destroy(&self.stream, &self.group)+ .await+ .context("failed to destroy the agent session log consumer group")?;+ tracing::info!(+ messaging.consumer.group.name = %self.group,+ destroyed,+ "destroyed the agent session log consumer group"+ );+ Ok(())+ }++ async fn connect_with(+ &self,+ response_timeout: Option<Duration>,+ ) -> Result<MultiplexedConnection, Report> {+ let config = AsyncConnectionConfig::new()+ .set_connection_timeout(Some(CONNECT_TIMEOUT))+ .set_response_timeout(response_timeout);+ Ok(self+ .client+ .get_multiplexed_async_connection_with_config(&config)+ .await+ .context("failed to connect to Redis to read agent session log runs")?)+ }++ /// The command connection, opened if there is none.+ async fn commands(&self) -> Result<MultiplexedConnection, Report> {+ let mut held = self.commands.lock().await;+ if let Some(connection) = held.as_ref() {+ return Ok(connection.clone());+ }+ let connection = self.connect_with(Some(COMMAND_RESPONSE_TIMEOUT)).await?;+ *held = Some(connection.clone());+ Ok(connection)+ }++ async fn reset_commands(&self) {+ self.commands.lock().await.take();+ }++ /// `XGROUP CREATE ... $ MKSTREAM`, tolerating a group that exists.+ #[tracing::instrument(+ name = "agent.session.log_stream.create_group",+ skip_all,+ err,+ fields(messaging.consumer.group.name = %self.group, created = tracing::field::Empty)+ )]+ async fn create_group(&self) -> Result<(), Report> {+ let mut connection = self.commands().await?;+ let created: Result<(), RedisError> = connection+ .xgroup_create_mkstream(&self.stream, &self.group, "$")+ .await;+ match created {+ Ok(()) => {+ tracing::Span::current().record("created", true);+ tracing::info!(+ messaging.consumer.group.name = %self.group,+ "created the agent session log consumer group"+ );+ Ok(())+ }+ Err(error) if error.code() == Some("BUSYGROUP") => {+ tracing::Span::current().record("created", false);+ Ok(())+ }+ Err(error) => {+ self.reset_commands().await;+ Err(Report::new(error)+ .context("failed to create the agent session log consumer group")+ .into_dynamic())+ }+ }+ }++ /// One `XREADGROUP`, buffering what it returns.+ #[tracing::instrument(+ name = "agent.session.log_stream.read",+ skip_all,+ err,+ fields(+ otel.kind = "consumer",+ messaging.system = "redis",+ messaging.operation.name = "receive",+ messaging.operation.type = "receive",+ messaging.destination.name = %self.stream,+ messaging.consumer.group.name = %self.group,+ agent.log.read_mode = state.mode.as_str(),+ messaging.batch.message_count = tracing::field::Empty,+ agent.log.read_ms = tracing::field::Empty,+ )+ )]+ async fn read(&self, state: &mut ReadState) -> Result<(), Report> {+ let span = tracing::Span::current();+ let mut connection = match state.connection.as_ref() {+ Some(connection) => connection.clone(),+ None => {+ // A blocked read answers after up to READ_BLOCK; the response+ // timeout leaves room for that and a slow reply on top.+ let connection = self+ .connect_with(Some(READ_BLOCK + COMMAND_RESPONSE_TIMEOUT))+ .await?;+ tracing::info!(+ messaging.consumer.group.name = %self.group,+ "connected the agent session log stream reader"+ );+ state.connection = Some(connection.clone());+ connection+ }+ };++ let mode = state.mode;+ let mut options = StreamReadOptions::default()+ .group(&self.group, &self.consumer)+ .count(READ_COUNT);+ if mode == ReadMode::New {+ let block_ms = usize::try_from(READ_BLOCK.as_millis()).unwrap_or(usize::MAX);+ options = options.block(block_ms);+ }++ let started = Instant::now();+ let read: Result<Option<StreamReadReply>, RedisError> = connection+ .xread_options(&[self.stream.as_str()], &[mode.id()], &options)+ .await;+ span.record(+ "agent.log.read_ms",+ u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),+ );++ let reply = match read {+ Ok(reply) => reply,+ Err(error) if error.code() == Some("NOGROUP") => {+ // The group is gone: Redis restarted, or the stream key was+ // evicted or deleted. Whatever was appended meanwhile is lost+ // to this process; start over at the stream's end.+ tracing::error!(+ error = ?error,+ messaging.consumer.group.name = %self.group,+ "the agent session log consumer group disappeared; recreating it at the stream's end, runs appended meanwhile are lost to this process"+ );+ state.mode = ReadMode::New;+ state.buffered.clear();+ return self.create_group().await;+ }+ Err(error) => {+ // Whatever this read might have delivered is pending in the+ // group; reread it once reconnected.+ state.connection = None;+ state.mode = ReadMode::Pending;+ return Err(Report::new(error)+ .context(format!(+ "failed to XREADGROUP {} agent session log runs",+ mode.as_str()+ ))+ .into_dynamic());+ }+ };++ let entries: Vec<StreamId> = reply+ .map(|reply| reply.keys.into_iter().flat_map(|key| key.ids).collect())+ .unwrap_or_default();+ span.record("messaging.batch.message_count", entries.len());++ if mode == ReadMode::Pending {+ if entries.is_empty() {+ tracing::info!(+ messaging.consumer.group.name = %self.group,+ "replayed every pending agent session log run; reading new runs"+ );+ state.mode = ReadMode::New;+ } else {+ tracing::warn!(+ messaging.consumer.group.name = %self.group,+ messaging.batch.message_count = entries.len(),+ "redelivering agent session log runs that were never acknowledged"+ );+ }+ }+ state+ .buffered+ .extend(entries.into_iter().map(|entry| Buffered { entry, mode }));+ Ok(())+ }++ /// Turn one read entry into a run, or acknowledge and skip it if it+ /// cannot become one.+ #[tracing::instrument(+ name = "agent.session.log_stream.receive",+ skip_all,+ fields(+ otel.kind = "consumer",+ messaging.system = "redis",+ messaging.operation.name = "process",+ messaging.operation.type = "process",+ messaging.destination.name = %self.stream,+ messaging.consumer.group.name = %self.group,+ messaging.message.id = %buffered.entry.id,+ messaging.message.body.size = tracing::field::Empty,+ agent.session.id = tracing::field::Empty,+ agent.log.frame_count = tracing::field::Empty,+ agent.log.redelivered = buffered.mode == ReadMode::Pending,+ agent.log.delivery_lag_ms = tracing::field::Empty,+ agent.log.decode_us = tracing::field::Empty,+ agent.log.skipped = tracing::field::Empty,+ )+ )]+ async fn receive(&self, buffered: Buffered) -> Option<ReceivedRun> {+ let span = tracing::Span::current();+ let Buffered { entry, mode } = buffered;+ let delivery = DeliveryId::new(entry.id.clone());++ if let Some(published_at) = entry+ .get::<u64>(field::PUBLISHED_AT_MS)+ .or_else(|| entry_id_ms(&entry.id))+ {+ span.record(+ "agent.log.delivery_lag_ms",+ now_ms().saturating_sub(published_at),+ );+ }+ if let Some(session) = entry.get::<String>(field::SESSION) {+ span.record("agent.session.id", session.as_str());+ }++ let Some(payload) = entry.get::<Vec<u8>>(field::PAYLOAD) else {+ // A pending entry the stream trimmed comes back with no fields.+ span.record("agent.log.skipped", "trimmed");+ tracing::error!(+ messaging.message.id = %entry.id,+ messaging.consumer.group.name = %self.group,+ read_mode = mode.as_str(),+ "an agent session log run was trimmed before it was acknowledged; it is lost to this process"+ );+ self.ack_skipped(&delivery).await;+ return None;+ };+ span.record("messaging.message.body.size", payload.len());++ let version = entry.get::<u8>(field::VERSION);+ if version != Some(WIRE_VERSION) {+ span.record("agent.log.skipped", "unsupported_version");+ tracing::warn!(+ messaging.message.id = %entry.id,+ expected = WIRE_VERSION,+ actual = ?version,+ "dropping agent session log run with an unsupported wire version"+ );+ self.ack_skipped(&delivery).await;+ return None;+ }++ let started = Instant::now();+ let decoded = decode(&payload);+ span.record(+ "agent.log.decode_us",+ u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX),+ );+ let run = match decoded {+ Ok(run) => run,+ Err(error) => {+ span.record("agent.log.skipped", "undecodable");+ tracing::error!(+ error = ?error,+ messaging.message.id = %entry.id,+ "dropping undecodable agent session log run"+ );+ self.ack_skipped(&delivery).await;+ return None;+ }+ };+ span.record(+ "agent.session.id",+ tracing::field::display(run.agent_session_id),+ );+ span.record("agent.log.frame_count", run.entries.len());++ Some(ReceivedRun {+ run,+ delivery,+ redelivered: mode == ReadMode::Pending,+ })+ }++ /// Acknowledge an entry that will never become a run, so it is not+ /// redelivered forever. Best effort.+ async fn ack_skipped(&self, delivery: &DeliveryId) {+ let _ = self.ack(delivery).await.inspect_err(|error| {+ tracing::warn!(+ error = ?error,+ messaging.message.id = %delivery,+ "failed to acknowledge a skipped agent session log entry"+ );+ });+ }++ /// Stats every [`STATS_INTERVAL`], reaping every [`REAP_INTERVAL`]. Both+ /// best effort: failures are logged and never stop reading.+ async fn housekeep(&self, state: &mut ReadState) {+ if state.last_stats.elapsed() >= STATS_INTERVAL {+ state.last_stats = Instant::now();+ let _ = self+ .log_stats(state.buffered.len())+ .await+ .inspect_err(|error| {+ tracing::warn!(error = ?error, "failed to read agent session log stream stats");+ });+ }+ if state.last_reap.elapsed() >= REAP_INTERVAL {+ state.last_reap = Instant::now();+ let _ = self.reap_abandoned_groups().await.inspect_err(|error| {+ tracing::warn!(error = ?error, "failed to reap abandoned agent session log groups");+ });+ }+ }++ /// Log the stream's length and this group's backlog, for dashboards and+ /// monitors.+ #[tracing::instrument(+ name = "agent.session.log_stream.stats",+ skip_all,+ err,+ fields(messaging.consumer.group.name = %self.group)+ )]+ async fn log_stats(&self, buffered: usize) -> Result<(), Report> {+ let mut connection = self.commands().await?;+ let length: usize = connection+ .xlen(&self.stream)+ .await+ .context("failed to XLEN the agent session log stream")?;+ let groups: StreamInfoGroupsReply = connection+ .xinfo_groups(&self.stream)+ .await+ .context("failed to XINFO GROUPS the agent session log stream")?;+ let ours = groups.groups.iter().find(|group| group.name == self.group);+ let reader_groups = groups+ .groups+ .iter()+ .filter(|group| group.name.starts_with(GROUP_PREFIX))+ .count();+ tracing::info!(+ messaging.destination.name = %self.stream,+ messaging.consumer.group.name = %self.group,+ agent.log_stream.length = length,+ agent.log_stream.groups = reader_groups,+ agent.log_stream.pending = ours.map(|group| group.pending),+ agent.log_stream.lag = ours.and_then(|group| group.lag),+ agent.log_stream.last_delivered_id = ours.map(|group| group.last_delivered_id.as_str()),+ agent.log_stream.buffered = buffered,+ agent.log_stream.group_present = ours.is_some(),+ "agent session log stream stats"+ );+ Ok(())+ }++ /// Destroy every reader group other than this one that is older than+ /// [`ABANDONED_AFTER`] and whose consumers have all been idle that long:+ /// their process is gone, and a group nobody reads only grows its pending+ /// list.+ #[tracing::instrument(+ name = "agent.session.log_stream.reap",+ skip_all,+ err,+ fields(+ messaging.consumer.group.name = %self.group,+ agent.log_stream.groups = tracing::field::Empty,+ agent.log_stream.reaped = tracing::field::Empty,+ )+ )]+ async fn reap_abandoned_groups(&self) -> Result<(), Report> {+ let span = tracing::Span::current();+ let mut connection = self.commands().await?;+ let groups: StreamInfoGroupsReply = connection+ .xinfo_groups(&self.stream)+ .await+ .context("failed to XINFO GROUPS the agent session log stream")?;+ span.record("agent.log_stream.groups", groups.groups.len());++ let abandoned_ms = usize::try_from(ABANDONED_AFTER.as_millis()).unwrap_or(usize::MAX);+ let mut reaped = 0_usize;+ for group in groups+ .groups+ .iter()+ .filter(|group| group.name.starts_with(GROUP_PREFIX) && group.name != self.group)+ {+ // A group younger than the threshold may just not have read yet:+ // its process started a moment ago, and a group has no+ // consumers until its first read.+ let age = group_age(&group.name);+ if age.is_some_and(|age| age < ABANDONED_AFTER) {+ continue;+ }+ let consumers: StreamInfoConsumersReply = connection+ .xinfo_consumers(&self.stream, &group.name)+ .await+ .context("failed to XINFO CONSUMERS an agent session log group")?;+ let least_idle_ms = consumers+ .consumers+ .iter()+ .map(|consumer| consumer.idle)+ .min();+ if least_idle_ms.is_some_and(|idle| idle < abandoned_ms) {+ continue;+ }+ let destroyed: usize = connection+ .xgroup_destroy(&self.stream, &group.name)+ .await+ .context("failed to destroy an abandoned agent session log group")?;+ reaped += destroyed;+ tracing::info!(+ messaging.consumer.group.name = %group.name,+ agent.log_stream.pending = group.pending,+ agent.log_stream.least_idle_ms = least_idle_ms,+ agent.log_stream.group_age_s = age.map(|age| age.as_secs()),+ agent.log_stream.consumers = consumers.consumers.len(),+ "reaped an abandoned agent session log consumer group"+ );+ }+ span.record("agent.log_stream.reaped", reaped);+ Ok(())+ }+}++/// How long ago a reader group was created, from the UUIDv7 its name ends+/// in. `None` for a name this crate did not mint.+fn group_age(group: &str) -> Option<Duration> {+ let instance = group.strip_prefix(GROUP_PREFIX)?;+ let (seconds, nanos) = macro_uuid::Uuid::parse_str(instance)+ .ok()?+ .get_timestamp()?+ .to_unix();+ let created = Duration::new(seconds, nanos);+ let now = Duration::from_millis(now_ms());+ Some(now.saturating_sub(created))+}++impl AgentSessionLogConsumer for RedisLogStreamConsumer {+ async fn recv(&self) -> Result<ReceivedRun, Report> {+ let mut state = self.state.lock().await;+ loop {+ if let Some(buffered) = state.buffered.pop_front() {+ if let Some(received) = self.receive(buffered).await {+ return Ok(received);+ }+ continue;+ }+ self.housekeep(&mut state).await;+ self.read(&mut state).await?;+ }+ }++ #[tracing::instrument(+ name = "agent.session.log_stream.ack",+ skip_all,+ err,+ fields(+ messaging.system = "redis",+ messaging.operation.name = "ack",+ messaging.operation.type = "settle",+ messaging.destination.name = %self.stream,+ messaging.consumer.group.name = %self.group,+ messaging.message.id = %delivery,+ agent.log.acked = tracing::field::Empty,+ )+ )]+ async fn ack(&self, delivery: &DeliveryId) -> Result<(), Report> {+ let mut connection = self.commands().await?;+ let acked: Result<usize, RedisError> = connection+ .xack(&self.stream, &self.group, &[delivery.as_str()])+ .await;+ let acked = match acked {+ Ok(acked) => acked,+ Err(error) => {+ self.reset_commands().await;+ return Err(Report::new(error)+ .context("failed to XACK an agent session log run")+ .into_dynamic());+ }+ };+ tracing::Span::current().record("agent.log.acked", acked);+ if acked == 0 {+ // Already acknowledged, or its group was recreated since.+ tracing::debug!(+ messaging.message.id = %delivery,+ "XACK acknowledged nothing for an agent session log run"+ );+ }+ Ok(())+ }+}diff --git a/crates/agent_session_realtime/src/outbound/redis_stream/consumer/test.rs b/crates/agent_session_realtime/src/outbound/redis_stream/consumer/test.rsnew file mode 100644index 0000000000..1578377fe4--- /dev/null+++ b/crates/agent_session_realtime/src/outbound/redis_stream/consumer/test.rs@@ -0,0 +1,353 @@+//! Integration tests against a running Redis.+//!+//! Run with: `REDIS_URL=redis://localhost:6379 cargo test -p agent_session_realtime -- --ignored`++use std::time::Duration;++use agent_client_protocol::RawJsonRpcMessage;+use agent_runtime_protocol::domain::schema::v0::{AcpMessage, SystemEvent, ToServerMessage};+use agent_session::domain::model::{+ AgentSessionId, AgentSessionLog, LogAppended, Message, StoredAgentSessionLog,+};+use agent_session::domain::ports::{AgentSessionRealtime as _, NoOpRealtime};+use macro_uuid::Uuid;+use redis::AsyncCommands as _;+use redis::streams::StreamInfoGroupsReply;++use super::*;+use crate::outbound::redis_stream::publisher::RedisLogStreamRealtime;++const RECV_TIMEOUT: Duration = Duration::from_secs(10);++fn client() -> redis::Client {+ let url = macro_env_var::maybe_read_env("REDIS_URL")+ .unwrap_or_else(|| "redis://127.0.0.1:6379".to_owned());+ redis::Client::open(url).expect("valid Redis URL")+}++/// A stream key of the test's own, deleted when dropped.+struct TestStream {+ key: String,+}++impl TestStream {+ fn new(test: &str) -> Self {+ Self {+ key: format!("test:{test}:{}", macro_uuid::generate_uuid_v7()),+ }+ }++ async fn consumer(&self) -> RedisLogStreamConsumer {+ RedisLogStreamConsumer::connect_to(client(), self.key.clone())+ .await+ .expect("connected")+ }++ fn publisher(&self) -> RedisLogStreamRealtime<NoOpRealtime> {+ RedisLogStreamRealtime::to_stream(NoOpRealtime, client(), self.key.clone())+ }++ async fn connection(&self) -> redis::aio::MultiplexedConnection {+ client()+ .get_multiplexed_async_connection()+ .await+ .expect("connected")+ }++ async fn groups(&self) -> Vec<String> {+ let groups: StreamInfoGroupsReply = self+ .connection()+ .await+ .xinfo_groups(&self.key)+ .await+ .expect("XINFO GROUPS");+ groups.groups.into_iter().map(|group| group.name).collect()+ }++ async fn pending(&self, group: &str) -> usize {+ let groups: StreamInfoGroupsReply = self+ .connection()+ .await+ .xinfo_groups(&self.key)+ .await+ .expect("XINFO GROUPS");+ groups+ .groups+ .into_iter()+ .find(|candidate| candidate.name == group)+ .map(|group| group.pending)+ .expect("group exists")+ }+}++impl Drop for TestStream {+ fn drop(&mut self) {+ if let Ok(mut connection) = client().get_connection() {+ let _: Result<(), _> = redis::Commands::del(&mut connection, &self.key);+ }+ }+}++fn appended(session: AgentSessionId, ids: impl IntoIterator<Item = u128>) -> LogAppended {+ LogAppended {+ turn_state: None,+ agent_session_id: session,+ entries: ids+ .into_iter()+ .map(|id| StoredAgentSessionLog {+ id: Uuid::from_u128(id),+ created_at: chrono::Utc::now(),+ entry: AgentSessionLog {+ agent_session_id: session,+ user_id: None,+ content: Message::ToServer(ToServerMessage::Event {+ event: SystemEvent::AcpReady,+ }),+ },+ })+ .collect(),+ }+}++async fn recv(consumer: &RedisLogStreamConsumer) -> ReceivedRun {+ tokio::time::timeout(RECV_TIMEOUT, consumer.recv())+ .await+ .expect("received in time")+ .expect("received")+}++fn ids(received: &ReceivedRun) -> Vec<Uuid> {+ received.run.entries.iter().map(|entry| entry.id).collect()+}++#[tokio::test]+#[ignore = "Redis doesn't exist in CI"]+async fn a_published_run_is_received_whole_and_acknowledged() {+ let stream = TestStream::new("roundtrip");+ let consumer = stream.consumer().await;++ stream+ .publisher()+ .publish(appended(AgentSessionId::TEST_A, [1, 2]))+ .await+ .expect("published");++ let received = recv(&consumer).await;+ assert_eq!(received.run.agent_session_id, AgentSessionId::TEST_A);+ assert_eq!(ids(&received), [Uuid::from_u128(1), Uuid::from_u128(2)]);+ assert!(!received.redelivered);+ assert_eq!(+ stream.pending(consumer.group()).await,+ 1,+ "owed until acked"+ );++ consumer.ack(&received.delivery).await.expect("acked");+ assert_eq!(stream.pending(consumer.group()).await, 0);+}++#[tokio::test]+#[ignore = "Redis doesn't exist in CI"]+async fn a_run_larger_than_kafkas_limit_goes_through() {+ let stream = TestStream::new("large");+ let consumer = stream.consumer().await;+ let mut event = appended(AgentSessionId::TEST_A, [1]);+ // ~3 MiB of tool output, the shape that broke the Kafka topic.+ event.entries[0].entry.content = Message::ToServer(ToServerMessage::Acp(AcpMessage(+ RawJsonRpcMessage::notification(+ "session/update".to_owned(),+ serde_json::json!({+ "sessionId": "s",+ "update": {+ "sessionUpdate": "tool_call_update",+ "toolCallId": "t",+ "rawOutput": { "text": "x".repeat(3 * 1024 * 1024) }+ }+ }),+ )+ .expect("valid notification"),+ )));++ stream.publisher().publish(event).await.expect("published");++ let received = recv(&consumer).await;+ assert_eq!(ids(&received), [Uuid::from_u128(1)]);+}++#[tokio::test]+#[ignore = "Redis doesn't exist in CI"]+async fn every_process_receives_every_run() {+ let stream = TestStream::new("fan_out");+ let first = stream.consumer().await;+ let second = stream.consumer().await;++ stream+ .publisher()+ .publish(appended(AgentSessionId::TEST_B, [5]))+ .await+ .expect("published");++ assert_eq!(ids(&recv(&first).await), [Uuid::from_u128(5)]);+ assert_eq!(ids(&recv(&second).await), [Uuid::from_u128(5)]);+}++#[tokio::test]+#[ignore = "Redis doesn't exist in CI"]+async fn an_unacknowledged_run_is_redelivered_after_a_failed_read() {+ let stream = TestStream::new("redelivery");+ let consumer = stream.consumer().await;+ let publisher = stream.publisher();++ publisher+ .publish(appended(AgentSessionId::TEST_A, [1]))+ .await+ .expect("published");+ let first = recv(&consumer).await;+ assert!(!first.redelivered);++ // What a failed read leaves behind: no connection, replay pending next.+ {+ let mut state = consumer.state.lock().await;+ state.connection = None;+ state.mode = ReadMode::Pending;+ }+ publisher+ .publish(appended(AgentSessionId::TEST_A, [2]))+ .await+ .expect("published");++ let again = recv(&consumer).await;+ assert!(again.redelivered, "the unacknowledged run comes back first");+ assert_eq!(ids(&again), [Uuid::from_u128(1)]);+ assert_eq!(again.delivery, first.delivery);+ consumer.ack(&again.delivery).await.expect("acked");++ let next = recv(&consumer).await;+ assert!(!next.redelivered);+ assert_eq!(ids(&next), [Uuid::from_u128(2)]);+}++#[tokio::test]+#[ignore = "Redis doesn't exist in CI"]+async fn a_pending_run_trimmed_before_its_ack_is_skipped_and_settled() {+ let stream = TestStream::new("trimmed");+ let consumer = stream.consumer().await;+ let publisher = stream.publisher();++ publisher+ .publish(appended(AgentSessionId::TEST_A, [1]))+ .await+ .expect("published");+ let first = recv(&consumer).await;+ let _: usize = stream+ .connection()+ .await+ .xdel(&stream.key, &[first.delivery.as_str()])+ .await+ .expect("XDEL");+ {+ let mut state = consumer.state.lock().await;+ state.mode = ReadMode::Pending;+ }+ publisher+ .publish(appended(AgentSessionId::TEST_A, [2]))+ .await+ .expect("published");++ let next = recv(&consumer).await;+ assert_eq!(ids(&next), [Uuid::from_u128(2)]);+ consumer.ack(&next.delivery).await.expect("acked");+ assert_eq!(+ stream.pending(consumer.group()).await,+ 0,+ "the trimmed entry was acknowledged, not left pending forever"+ );+}++#[tokio::test]+#[ignore = "Redis doesn't exist in CI"]+async fn a_lost_group_is_recreated_and_reading_resumes() {+ let stream = TestStream::new("lost_group");+ let consumer = stream.consumer().await;+ let _: usize = stream+ .connection()+ .await+ .xgroup_destroy(&stream.key, consumer.group())+ .await+ .expect("XGROUP DESTROY");++ let receiving = tokio::time::timeout(RECV_TIMEOUT, consumer.recv());+ let publishing = async {+ // After the read that recreates the group.+ tokio::time::sleep(Duration::from_millis(500)).await;+ stream+ .publisher()+ .publish(appended(AgentSessionId::TEST_A, [3]))+ .await+ .expect("published");+ };+ let (received, ()) = tokio::join!(receiving, publishing);++ let received = received.expect("received in time").expect("received");+ assert_eq!(ids(&received), [Uuid::from_u128(3)]);+ assert!(stream.groups().await.contains(&consumer.group().to_owned()));+}++#[tokio::test]+#[ignore = "Redis doesn't exist in CI"]+async fn a_group_without_consumers_is_reaped_and_others_are_left_alone() {+ let stream = TestStream::new("reap");+ let live = stream.consumer().await;+ let abandoned = format!("{GROUP_PREFIX}abandoned");+ let foreign = "someone-elses-group";+ let mut connection = stream.connection().await;+ let () = connection+ .xgroup_create_mkstream(&stream.key, &abandoned, "$")+ .await+ .expect("XGROUP CREATE");+ let () = connection+ .xgroup_create_mkstream(&stream.key, foreign, "$")+ .await+ .expect("XGROUP CREATE");++ live.reap_abandoned_groups().await.expect("reaped");++ let groups = stream.groups().await;+ assert!(!groups.contains(&abandoned), "{groups:?}");+ assert!(groups.contains(&foreign.to_owned()), "{groups:?}");+ assert!(groups.contains(&live.group().to_owned()), "{groups:?}");+}++#[tokio::test]+#[ignore = "Redis doesn't exist in CI"]+async fn closing_destroys_the_process_group() {+ let stream = TestStream::new("close");+ let consumer = stream.consumer().await;+ assert!(stream.groups().await.contains(&consumer.group().to_owned()));++ consumer.close().await.expect("closed");++ assert!(!stream.groups().await.contains(&consumer.group().to_owned()));+}++#[tokio::test]+#[ignore = "Redis doesn't exist in CI"]+async fn a_young_group_that_has_not_read_yet_is_not_reaped() {+ let stream = TestStream::new("young");+ // Connected, so created, but never read: no consumers yet.+ let starting = stream.consumer().await;+ let other = stream.consumer().await;++ other.reap_abandoned_groups().await.expect("reaped");++ assert!(stream.groups().await.contains(&starting.group().to_owned()));+}++#[test]+fn a_group_minted_now_is_young_and_a_foreign_name_has_no_age() {+ let group = format!("{GROUP_PREFIX}{}", macro_uuid::generate_uuid_v7());+ let age = group_age(&group).expect("a minted group has an age");+ assert!(age < Duration::from_secs(5), "{age:?}");+ assert_eq!(group_age("someone-elses-group"), None);+ assert_eq!(group_age(&format!("{GROUP_PREFIX}abandoned")), None);+}diff --git a/crates/agent_session_realtime/src/outbound/redis_stream/publisher.rs b/crates/agent_session_realtime/src/outbound/redis_stream/publisher.rsnew file mode 100644index 0000000000..0f9e5d1def--- /dev/null+++ b/crates/agent_session_realtime/src/outbound/redis_stream/publisher.rs@@ -0,0 +1,236 @@+use std::sync::Arc;+use std::time::{Duration, Instant};++use agent_session::domain::events::LogAppendedMetadata;+use agent_session::domain::model::{AgentSessionId, AgentSessionRenamed, LogAppended};+use agent_session::domain::ports::{AgentSessionQueueChanged, AgentSessionRealtime};+use redis::aio::MultiplexedConnection;+use redis::streams::{StreamAddOptions, StreamTrimStrategy, StreamTrimmingMode};+use redis::{AsyncCommands as _, AsyncConnectionConfig};+use rootcause::Report;+use rootcause::prelude::ResultExt as _;++use super::{STREAM_KEY, WIRE_VERSION, encode, field, now_ms, retention_floor};++/// How long one `XADD` may take. Generous: a run can carry megabytes of tool+/// output, which the client's 500 ms default does not leave room for.+const PUBLISH_RESPONSE_TIMEOUT: Duration = Duration::from_secs(5);++/// How long connecting to Redis may take before a publish gives up.+const CONNECT_TIMEOUT: Duration = Duration::from_secs(2);++/// A run this large is logged with its largest frame, so whatever produces+/// oversized frames can be found from the logs.+const LARGE_RUN_BYTES: usize = 1024 * 1024;++/// [`AgentSessionRealtime`] that also appends each run of frames to the+/// agent session log stream, so a process serving viewers of its own - the+/// GraphQL subscription in document storage - hears the frames too.+///+/// `inner` keeps doing what it does, and its result is what `publish`+/// returns. The stream append is best effort, as the port allows: a failure+/// is logged at error, because a viewer reading through the stream misses the+/// run until it refetches.+///+/// Clones share one connection.+#[derive(Clone)]+pub struct RedisLogStreamRealtime<Inner> {+ inner: Inner,+ client: redis::Client,+ stream: String,+ connection: Arc<tokio::sync::Mutex<Option<MultiplexedConnection>>>,+}++impl<Inner> RedisLogStreamRealtime<Inner> {+ /// Publish through `inner`, and append each log run through `client` too.+ /// Connects lazily, on the first run.+ pub fn new(inner: Inner, client: redis::Client) -> Self {+ Self::to_stream(inner, client, STREAM_KEY.to_owned())+ }++ /// [`Self::new`], appending to a stream other than [`STREAM_KEY`].+ pub(crate) fn to_stream(inner: Inner, client: redis::Client, stream: String) -> Self {+ Self {+ inner,+ client,+ stream,+ connection: Arc::new(tokio::sync::Mutex::new(None)),+ }+ }++ /// A connection, opened if there is none. Multiplexed and cheap to clone,+ /// so concurrent publishes share it.+ async fn connection(&self) -> Result<MultiplexedConnection, Report> {+ let mut held = self.connection.lock().await;+ if let Some(connection) = held.as_ref() {+ return Ok(connection.clone());+ }+ let config = AsyncConnectionConfig::new()+ .set_connection_timeout(Some(CONNECT_TIMEOUT))+ .set_response_timeout(Some(PUBLISH_RESPONSE_TIMEOUT));+ let connection = self+ .client+ .get_multiplexed_async_connection_with_config(&config)+ .await+ .context("failed to connect to Redis to publish agent session log runs")?;+ tracing::info!(+ messaging.destination.name = %self.stream,+ "connected the agent session log stream publisher"+ );+ *held = Some(connection.clone());+ Ok(connection)+ }++ /// Forget the connection after a failure, so the next publish reconnects+ /// rather than reusing a broken one.+ async fn reset_connection(&self) {+ self.connection.lock().await.take();+ }++ /// Append one run to the stream, trimming whatever is past retention.+ #[tracing::instrument(+ name = "agent.session.log_stream.publish",+ err,+ skip_all,+ fields(+ otel.kind = "producer",+ messaging.system = "redis",+ messaging.operation.name = "publish",+ messaging.operation.type = "send",+ messaging.destination.name = %self.stream,+ messaging.message.id = tracing::field::Empty,+ messaging.message.body.size = tracing::field::Empty,+ agent.session.id = %run.agent_session_id,+ agent.log.frame_count = run.entries.len(),+ agent.log.encode_us = tracing::field::Empty,+ agent.log.redis_ms = tracing::field::Empty,+ agent.log.large_run = tracing::field::Empty,+ )+ )]+ async fn append(&self, run: &LogAppendedMetadata) -> Result<String, Report> {+ let span = tracing::Span::current();++ let started = Instant::now();+ let payload = encode(run)?;+ span.record(+ "agent.log.encode_us",+ u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX),+ );+ span.record("messaging.message.body.size", payload.len());+ let large = payload.len() >= LARGE_RUN_BYTES;+ span.record("agent.log.large_run", large);+ if large {+ log_large_run(run, payload.len());+ }++ let published_at = now_ms();+ let options = StreamAddOptions::default().trim(StreamTrimStrategy::minid(+ StreamTrimmingMode::Approx,+ retention_floor(published_at),+ ));+ let fields = [+ (field::VERSION, WIRE_VERSION.to_string()),+ (field::SESSION, run.agent_session_id.to_string()),+ (field::FRAMES, run.entries.len().to_string()),+ (field::PUBLISHED_AT_MS, published_at.to_string()),+ (field::PAYLOAD, payload),+ ];++ let mut connection = self.connection().await?;+ let started = Instant::now();+ let added: Result<Option<String>, _> = connection+ .xadd_options(&self.stream, "*", &fields, &options)+ .await;+ span.record(+ "agent.log.redis_ms",+ u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),+ );+ let entry_id = match added {+ Ok(Some(entry_id)) => entry_id,+ Ok(None) => {+ return Err(rootcause::report!(+ "Redis accepted the XADD but returned no entry id"+ ));+ }+ Err(error) => {+ self.reset_connection().await;+ return Err(Report::new(error)+ .context("failed to XADD an agent session log run")+ .into_dynamic());+ }+ };+ span.record("messaging.message.id", entry_id.as_str());+ Ok(entry_id)+ }+}++/// Log a run that crossed [`LARGE_RUN_BYTES`] with the size and id of its+/// largest frame. Sizes only: frames are session content, never logged.+fn log_large_run(run: &LogAppendedMetadata, body_size: usize) {+ let largest = run+ .entries+ .iter()+ .map(|entry| {+ let size = serde_json::to_vec(&entry.content)+ .map(|bytes| bytes.len())+ .unwrap_or_default();+ (entry.id, size)+ })+ .max_by_key(|(_, size)| *size);+ let (largest_frame_id, largest_frame_bytes) = largest.unwrap_or_default();+ tracing::warn!(+ agent.session.id = %run.agent_session_id,+ messaging.message.body.size = body_size,+ agent.log.frame_count = run.entries.len(),+ agent.log.largest_frame_id = %largest_frame_id,+ agent.log.largest_frame_bytes = largest_frame_bytes,+ "publishing a large agent session log run"+ );+}++impl<Inner> AgentSessionRealtime for RedisLogStreamRealtime<Inner>+where+ Inner: AgentSessionRealtime + Sync,+{+ async fn publish(&self, event: LogAppended) -> Result<(), Report> {+ let run = LogAppendedMetadata::from(&event);+ let inner = self.inner.publish(event).await;+ let _ = self.append(&run).await.inspect_err(|error| {+ tracing::error!(+ error = ?error,+ agent.session.id = %run.agent_session_id,+ agent.log.frame_count = run.entries.len(),+ "failed to append agent session log frames to the stream"+ );+ });+ inner+ }++ fn publish_updated(+ &self,+ session: AgentSessionId,+ ) -> impl Future<Output = Result<(), Report>> + Send {+ self.inner.publish_updated(session)+ }++ fn publish_renamed(+ &self,+ event: AgentSessionRenamed,+ ) -> impl Future<Output = Result<(), Report>> + Send {+ self.inner.publish_renamed(event)+ }++ fn publish_queue_changed(+ &self,+ event: AgentSessionQueueChanged,+ ) -> impl Future<Output = Result<(), Report>> + Send {+ self.inner.publish_queue_changed(event)+ }++ fn publish_changes_updated(+ &self,+ session: AgentSessionId,+ ) -> impl Future<Output = Result<(), Report>> + Send {+ self.inner.publish_changes_updated(session)+ }+}diff --git a/crates/agent_session_realtime/src/outbound/redis_stream/test.rs b/crates/agent_session_realtime/src/outbound/redis_stream/test.rsnew file mode 100644index 0000000000..434199d317--- /dev/null+++ b/crates/agent_session_realtime/src/outbound/redis_stream/test.rs@@ -0,0 +1,55 @@+use agent_runtime_protocol::domain::schema::v0::{SystemEvent, ToServerMessage};+use agent_session::domain::events::{LogAppendedEntry, LogAppendedMetadata};+use agent_session::domain::model::{AgentSessionId, Message};+use macro_uuid::Uuid;++use super::*;++#[test]+fn the_retention_floor_trims_entries_older_than_retention() {+ let retention_ms = u64::try_from(RETENTION.as_millis()).expect("fits");+ assert_eq!(+ retention_floor(retention_ms + 1_000),+ "1000-0",+ "an id at the floor's millisecond and later survives"+ );+}++#[test]+fn the_retention_floor_never_underflows() {+ assert_eq!(retention_floor(5), "0-0");+}++#[test]+fn an_entry_id_names_the_millisecond_it_was_added_at() {+ assert_eq!(entry_id_ms("1791910053617-3"), Some(1_791_910_053_617));+ assert_eq!(entry_id_ms("not-an-id"), None);+ assert_eq!(entry_id_ms("12345"), None);+}++#[test]+fn a_run_survives_its_wire_encoding() {+ let run = LogAppendedMetadata {+ agent_session_id: AgentSessionId::TEST_A,+ entries: vec![LogAppendedEntry {+ id: Uuid::from_u128(1),+ created_at: chrono::Utc::now(),+ user_id: None,+ content: Message::ToServer(ToServerMessage::Event {+ event: SystemEvent::AcpReady,+ }),+ }],+ };++ let decoded = decode(encode(&run).expect("encodes").as_bytes()).expect("decodes");++ assert_eq!(decoded.agent_session_id, run.agent_session_id);+ assert_eq!(decoded.entries.len(), 1);+ assert_eq!(decoded.entries[0].id, run.entries[0].id);+ assert_eq!(decoded.entries[0].created_at, run.entries[0].created_at);+}++#[test]+fn an_undecodable_payload_is_an_error_not_a_panic() {+ assert!(decode(b"{\"agent_session_id\":").is_err());+}diff --git a/crates/macro_event_topics/src/lib.rs b/crates/macro_event_topics/src/lib.rsindex 74a01b9545..2190c246e7 100644--- a/crates/macro_event_topics/src/lib.rs+++ b/crates/macro_event_topics/src/lib.rs@@ -87,7 +87,10 @@ topics! {MacroCalendarTopic => "macro.calendar",/// Agent session lifecycle facts: opened, turns, waiting for input, settled, stopped, renamed, deleted.MacroAgentSessionLifecycleTopic => "macro.agent_session_lifecycle",- /// Runs of frames appended to an agent session's log, for realtime viewers served by another process.+ /// Retired: runs of appended agent session log frames now travel over a+ /// Redis Stream (`agent_session_realtime::outbound::redis_stream`). Kept+ /// declared until every harness task publishing here has been replaced;+ /// remove it, and its cluster topic, after that rollout.MacroAgentSessionLogTopic => "macro.agent_session_log",/// Database lifecycle (created, renamed, trashed, restored, purged) and table-change events.MacroDatabasesTopic => "macro.databases",diff --git a/services/agent_harness_service/Cargo.toml b/services/agent_harness_service/Cargo.tomlindex 923060e73c..a80536d685 100644--- a/services/agent_harness_service/Cargo.toml+++ b/services/agent_harness_service/Cargo.toml@@ -33,6 +33,7 @@ agent_inmem = { path = "../../crates/agent_inmem" }ai_tools = { path = "../../crates/ai_tools" }agent_runtime_protocol = { path = "../../crates/agent_runtime_protocol", features = ["utoipa"] }agent_session = { path = "../../crates/agent_session", features = ["ai_tools"] }+agent_session_realtime = { path = "../../crates/agent_session_realtime" }ai_toolset = { path = "../../crates/ai_toolset" }rmcp = { workspace = true }agent_trigger = { path = "../../crates/agent_trigger", features = ["outbound"] }diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex f9402f5341..f7d2bb33aa 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -95,10 +95,10 @@ use agent_session::inbound::axum_router::{AgentSessionControlState, AgentSessionRouterState, CreateSessionState,};use agent_session::outbound::broker_lifecycle_publisher::BrokerLifecyclePublisher;-use agent_session::outbound::broker_log_realtime::BrokerLogRealtime;use agent_session::outbound::connection_gateway_realtime::ConnectionGatewayAgentSessionRealtime;use agent_session::outbound::name_generator::HaikuAgentSessionNameGenerator;use agent_session::outbound::postgres::PgAgentSessionRepo;+use agent_session_realtime::outbound::redis_stream::publisher::RedisLogStreamRealtime;use agent_trigger::domain::broker_events::AgentSessionMacroEvent;use anyhow::Context as _;use bot_id::BotId;@@ -321,17 +321,22 @@ async fn run() -> anyhow::Result<()> {config.settlement_route()?,);let lifecycle_publisher = Arc::new(BrokerLifecyclePublisher::new(broker.clone()));+ // Shared with every replica: runtime command forwarding, model probes,+ // and the agent session log stream.+ let redis = redis::Client::open(config.redis_uri.as_ref())+ .context("failed to create the shared Redis client")?;let sessions = AgentSessionServiceImpl::new(session_repo.clone(),FoldedMessageService::new(session_repo.clone()),// Frames reach this process's viewers through the gateway and every- // other process's through the broker (the GraphQL log subscription).- BrokerLogRealtime::new(+ // other process's through the Redis log stream (the GraphQL log+ // subscription).+ RedisLogStreamRealtime::new(ConnectionGatewayAgentSessionRealtime::new(connection_gateway.clone(),session_audience.clone(),),- broker.clone(),+ redis.clone(),),agent_session::domain::name_generation::AdmittedAgentSessionNameGenerator::new(HaikuAgentSessionNameGenerator::new(recorder.clone()),@@ -947,8 +952,6 @@ async fn run() -> anyhow::Result<()> {// it and the harness takes sessions out of it. Attach/detach is mirrored// to the harnesses table so the settings page can show connection state.let runtimes = RuntimeRegistry::with_presence(Arc::new(PgHarnessPresence::new(pool.clone())));- let redis = redis::Client::open(config.redis_uri.as_ref())- .context("failed to create the runtime command Redis client")?;// Read once, here, rather than at every session this deployment opens: a// URL that names no repository is a misconfiguration of the deployment,// and refusing it at startup is the difference between one loud failurediff --git a/services/document_storage_service/src/server.rs b/services/document_storage_service/src/server.rsindex 513e885202..5b2cc9ace2 100644--- a/services/document_storage_service/src/server.rs+++ b/services/document_storage_service/src/server.rs@@ -17,7 +17,8 @@ use crate::{service::{self, s3::S3},};use agent_session_realtime::{- domain::service::AgentSessionLogConsumerService, outbound::log_topic_consumer::LogTopicConsumer,+ domain::service::AgentSessionLogConsumerService,+ outbound::redis_stream::consumer::RedisLogStreamConsumer,};use analytics_client::{AnalyticsClient, AnalyticsClientConfig, MetaConfig};use anyhow::Context;@@ -1673,10 +1674,14 @@ pub async fn run() -> anyhow::Result<()> {}});+ // Reads the harness' agent session log stream through a consumer group of+ // this process' own, and fans each run out to GraphQL log subscribers.let agent_session_log_realtime = Arc::new(AgentSessionLogConsumerService::new(- LogTopicConsumer::from_env(config.kafka_brokers.as_ref()).map_err(|error| {- anyhow::anyhow!("failed to create agent session log topic consumer: {error:?}")- })?,+ RedisLogStreamConsumer::connect(redis_client.clone())+ .await+ .map_err(|error| {+ anyhow::anyhow!("failed to create agent session log stream consumer: {error:?}")+ })?,));consumer_tracker.spawn({let service = Arc::clone(&agent_session_log_realtime);@@ -1706,6 +1711,13 @@ pub async fn run() -> anyhow::Result<()> {_ = tokio::time::sleep(Duration::from_secs(1)) => {}}}+ // Nothing reads this process' group once it stops.+ let _ = service.consumer().close().await.inspect_err(|error| {+ tracing::warn!(+ error = ?error,+ "failed to close the agent session log stream consumer group"+ );+ });}});