Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(agents): reopen the session log subscription when the server ends it (#9770)

Wolf Mermelsteina7103729e5b2
diff --git a/apps/web/src/features/block-agent/context/confirm-session-control.test.ts b/apps/web/src/features/block-agent/context/confirm-session-control.test.ts
index 2a0c9b5377..d20db9037f 100644
--- a/apps/web/src/features/block-agent/context/confirm-session-control.test.ts
+++ b/apps/web/src/features/block-agent/context/confirm-session-control.test.ts
@@ -1,6 +1,27 @@
import type { AgentSession } from '@core/agent-session/AgentSession';
import { err, ok } from 'neverthrow';
import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const spanAttributes = vi.hoisted(() => new Map<string, unknown>());
+// A span takes attributes until its callback settles, as an ended one would.
+vi.mock('@macro-inc/observability', () => ({
+ Telemetry: {
+ span: async (_name: string, run: (span: unknown) => Promise<void>) => {
+ let ended = false;
+ try {
+ return await run({
+ setAttr: (name: string, value: unknown) => {
+ if (!ended) spanAttributes.set(name, value);
+ },
+ error: () => undefined,
+ });
+ } finally {
+ ended = true;
+ }
+ },
+ },
+}));
+
import { confirmSessionControl } from './confirm-session-control';
function session() {
@@ -62,7 +83,10 @@ const flush = async () => {
await Promise.resolve();
await Promise.resolve();
};
-afterEach(() => vi.useRealTimers());
+afterEach(() => {
+ vi.useRealTimers();
+ spanAttributes.clear();
+});
describe('confirmed session controls', () => {
it('waits past HTTP acceptance and unrelated actions for the correlated runtime outcome', async () => {
const test = session();
@@ -124,6 +148,31 @@ describe('confirmed session controls', () => {
await vi.advanceTimersByTimeAsync(60_000);
expect(test.refresh).toHaveBeenCalledOnce();
});
+ it('records a settle the refetched log folded as the reread, not the feed', async () => {
+ vi.useFakeTimers();
+ const test = session();
+ // The session tells its listeners about the refetched log well before the
+ // refresh resolves, as `AgentSession.refresh` does: it still drains and
+ // may fetch again.
+ test.refresh.mockImplementation(async () => {
+ test.outcome('accepted');
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ });
+ const result = confirmSessionControl(test.value, action);
+ await vi.advanceTimersByTimeAsync(10_050);
+ await result;
+ expect(spanAttributes.get('agent.control.settled_by')).toBe('refresh');
+ expect(spanAttributes.get('agent.control.refreshes')).toBe(1);
+ });
+ it('records a settle the live feed delivered as the feed', async () => {
+ const test = session();
+ const result = confirmSessionControl(test.value, action);
+ await flush();
+ test.outcome('accepted');
+ await result;
+ expect(spanAttributes.get('agent.control.settled_by')).toBe('feed');
+ expect(spanAttributes.get('agent.control.refreshes')).toBe(0);
+ });
it('fails immediately on HTTP rejection', async () => {
const test = session();
test.issue.mockResolvedValue(err([{ message: 'disconnected' }]));
diff --git a/apps/web/src/features/block-agent/context/confirm-session-control.ts b/apps/web/src/features/block-agent/context/confirm-session-control.ts
index 96c864df61..62728c1496 100644
--- a/apps/web/src/features/block-agent/context/confirm-session-control.ts
+++ b/apps/web/src/features/block-agent/context/confirm-session-control.ts
@@ -54,7 +54,11 @@ async function awaitConfirmation(
const actionId = result.value.actionId;
span.setAttr('agent.action.id', actionId);
let refreshes = 0;
- let settledBy: 'feed' | 'refresh' = 'feed';
+ /**
+ * A settle while a reread is in flight is the reread's: the session tells
+ * its listeners about the refetched log before the refresh resolves.
+ */
+ let rereading = false;
await new Promise<void>((resolve, reject) => {
let finished = false;
const finish = (error?: Error) => {
@@ -70,6 +74,7 @@ async function awaitConfirmation(
const inspect = async () => {
try {
const snapshot = await session.snapshot();
+ if (finished) return;
const message = snapshot.messages.find(
(message) => message.requestId === actionId
);
@@ -77,7 +82,10 @@ async function awaitConfirmation(
const part = message.parts.find((part) => part.kind === 'control');
if (part?.kind !== 'control' || part.outcome.kind === 'pending') return;
span.setAttr('agent.control.outcome', part.outcome.kind);
- span.setAttr('agent.control.settled_by', settledBy);
+ span.setAttr(
+ 'agent.control.settled_by',
+ rereading ? 'refresh' : 'feed'
+ );
finish(
part.outcome.kind === 'rejected'
? new Error(part.outcome.message)
@@ -93,10 +101,13 @@ async function awaitConfirmation(
};
const reread = async () => {
refreshes += 1;
- await session.refresh();
- settledBy = 'refresh';
- await inspect();
- settledBy = 'feed';
+ rereading = true;
+ try {
+ await session.refresh();
+ await inspect();
+ } finally {
+ rereading = false;
+ }
};
const giveUp = async () => {
let bound: ReturnType<typeof setTimeout> | undefined;
diff --git a/apps/web/src/lib/core/agent-session/load-telemetry.ts b/apps/web/src/lib/core/agent-session/load-telemetry.ts
index a92030b639..7626ecc560 100644
--- a/apps/web/src/lib/core/agent-session/load-telemetry.ts
+++ b/apps/web/src/lib/core/agent-session/load-telemetry.ts
@@ -386,6 +386,31 @@ export class SessionLoadTrace {
}
}
+/**
+ * The log subscription ended and is being reopened: the server closed it
+ * (a subscriber that fell behind, a refused session) or the transport gave
+ * up. Every frame published until the new one is up reaches the session only
+ * through the refetch that follows, so a burst of these is a live feed that
+ * keeps dying.
+ */
+export function traceFollowResumed(
+ sessionId: string,
+ reason: 'error' | 'ended',
+ attempt: number,
+ delayMs: number
+): void {
+ const span = start('agent.session.log.follow_resumed', sessionId);
+ if (!span) return;
+ try {
+ span.setAttr('agent.session.log.follow.reason', reason);
+ span.setAttr('agent.session.log.follow.attempt', attempt);
+ span.setAttr('agent.session.log.follow.delay_ms', delayMs);
+ span.end();
+ } catch {
+ // See the module comment.
+ }
+}
+
/**
* A write of the cached log, after the load: its own short span and
* measure, since the load span has usually ended by the time rows stream in.
diff --git a/apps/web/src/lib/queries/agent-session/log.test.ts b/apps/web/src/lib/queries/agent-session/log.test.ts
index 4d3eabf7a0..4cb8f84e45 100644
--- a/apps/web/src/lib/queries/agent-session/log.test.ts
+++ b/apps/web/src/lib/queries/agent-session/log.test.ts
@@ -14,8 +14,10 @@ vi.mock('@core/constant/featureFlags', () => ({
enableGraphqlSoup: {},
isFeatureEnabled: () => true,
}));
+const telemetry = vi.hoisted(() => ({ traceFollowResumed: vi.fn() }));
vi.mock('@core/agent-session/load-telemetry', () => ({
traceCacheWrite: () => undefined,
+ traceFollowResumed: telemetry.traceFollowResumed,
}));
const metadata = vi.hoisted(() => new WeakMap<object, { source: string }>());
@@ -91,25 +93,31 @@ function fromCache<T>(data: T): Result<T> {
}
let query: ReturnType<typeof makeSubject<Result<AgentSessionLogQuery>>>;
-let appended: ReturnType<
+type Appended = ReturnType<
typeof makeSubject<
Result<{ agentSessionLogAppended: ReturnType<typeof entry>[] }>
>
>;
+/** The latest subscription the client opened. */
+let appended: Appended;
+/** Every subscription the client opened, in order. */
+let subscriptions: Appended[];
/** The order the client was asked for things in. */
let calls: string[];
beforeEach(() => {
vi.useFakeTimers();
calls = [];
+ subscriptions = [];
query = makeSubject();
- appended = makeSubject();
client.query.mockImplementation((): Source<unknown> => {
calls.push('query');
return query.source;
});
client.subscription.mockImplementation((): Source<unknown> => {
calls.push('subscription');
+ appended = makeSubject();
+ subscriptions.push(appended);
return appended.source;
});
host.readQuery.mockResolvedValue({ kind: 'miss' });
@@ -251,19 +259,102 @@ describe('watchAgentSessionLog', () => {
expect(written.user.agentSession?.log.entries).toHaveLength(2);
});
- it('reports a gap when the subscription errors', async () => {
+ it('reopens a subscription the server ended with an error, then reports the gap', async () => {
+ const rows = vi.fn();
const gap = vi.fn();
const watch = watchAgentSessionLog(SESSION, 'cache-and-network', {
- rows: () => undefined,
+ rows,
gap,
});
- appended.next({
+ query.next(fromNetwork(logData([1])));
+ await watch.fetched;
+
+ // What urql hands on when the server closes a subscriber that fell
+ // behind: the error, then the end of the stream.
+ const closed = subscriptions[0];
+ closed.next({
error: new Error('closed after falling behind'),
stale: false,
hasNext: false,
} as unknown as Result<{ agentSessionLogAppended: never[] }>);
+ closed.complete();
+ expect(gap).not.toHaveBeenCalled();
+ await settle();
+ expect(subscriptions).toHaveLength(2);
+ expect(calls).toEqual(['subscription', 'query', 'subscription']);
expect(gap).toHaveBeenCalledOnce();
+ expect(telemetry.traceFollowResumed).toHaveBeenCalledExactlyOnceWith(
+ SESSION,
+ 'error',
+ 1,
+ 0
+ );
+
+ // The control answer the runtime logs after the wake reaches the
+ // session live, without a reread.
+ subscriptions[1].next(fromNetwork({ agentSessionLogAppended: [entry(2)] }));
+ expect(rows).toHaveBeenCalledWith([row(2)]);
+ watch.stop();
+ });
+
+ it('reopens a subscription that ended without an error', async () => {
+ const gap = vi.fn();
+ const watch = watchAgentSessionLog(SESSION, 'cache-and-network', {
+ rows: () => undefined,
+ gap,
+ });
+ subscriptions[0].complete();
+ await settle();
+
+ expect(subscriptions).toHaveLength(2);
+ expect(gap).toHaveBeenCalledOnce();
+ expect(telemetry.traceFollowResumed).toHaveBeenCalledExactlyOnceWith(
+ SESSION,
+ 'ended',
+ 1,
+ 0
+ );
+ watch.stop();
+ });
+
+ it('backs off while the subscription keeps ending, and starts over once it delivers', async () => {
+ const watch = watchAgentSessionLog(SESSION, 'cache-and-network', {
+ rows: () => undefined,
+ gap: () => undefined,
+ });
+ subscriptions[0].complete();
+ await settle();
+ expect(subscriptions).toHaveLength(2);
+
+ subscriptions[1].complete();
+ await vi.advanceTimersByTimeAsync(999);
+ expect(subscriptions).toHaveLength(2);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(subscriptions).toHaveLength(3);
+
+ subscriptions[2].complete();
+ await vi.advanceTimersByTimeAsync(3_000);
+ expect(subscriptions).toHaveLength(4);
+
+ subscriptions[3].next(fromNetwork({ agentSessionLogAppended: [entry(2)] }));
+ subscriptions[3].complete();
+ await settle();
+ expect(subscriptions).toHaveLength(5);
watch.stop();
});
+
+ it('does not reopen once stopped', async () => {
+ const gap = vi.fn();
+ const watch = watchAgentSessionLog(SESSION, 'cache-and-network', {
+ rows: () => undefined,
+ gap,
+ });
+ subscriptions[0].complete();
+ watch.stop();
+ await vi.advanceTimersByTimeAsync(60_000);
+
+ expect(subscriptions).toHaveLength(1);
+ expect(gap).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/web/src/lib/queries/agent-session/log.ts b/apps/web/src/lib/queries/agent-session/log.ts
index 5fac580295..8a92abaad2 100644
--- a/apps/web/src/lib/queries/agent-session/log.ts
+++ b/apps/web/src/lib/queries/agent-session/log.ts
@@ -9,7 +9,10 @@
* open starts from a log as complete as the last one ended.
*/
-import { traceCacheWrite } from '@core/agent-session/load-telemetry';
+import {
+ traceCacheWrite,
+ traceFollowResumed,
+} from '@core/agent-session/load-telemetry';
import {
enableGraphqlSoup,
isFeatureEnabled,
@@ -33,7 +36,7 @@ import {
getGraphqlSoupClient,
} from '@service-storage/graphql-soup';
import { type OperationResult, stringifyDocument } from '@urql/core';
-import { pipe, subscribe } from 'wonka';
+import { onEnd, pipe, subscribe } from 'wonka';
/** What the fold needs: the agent and the raw rows. */
export type SessionLogSnapshot = {
@@ -92,8 +95,8 @@ export type SessionLogWatch = {
/**
* How a watch follows the session after the fetch: each run of frames the
* harness appends, in log order, as the harness flushed it. `gap` means
- * rows may have been missed - the subscription fell behind or the socket
- * reconnected - and the caller must refetch the log.
+ * rows may have been missed - the subscription ended and was reopened, or a
+ * run could not be read - and the caller must refetch the log.
*/
export type SessionLogFollow = {
rows: (rows: AgentSessionLogEntryDto[]) => void;
@@ -281,46 +284,96 @@ export function watchAgentSessionLog(
};
}
+/**
+ * Waits before reopening a subscription that ended, by how many times in a
+ * row it has: the first reopens at once, for a server that closed a
+ * subscriber which fell behind; the rest back off, for one that keeps
+ * refusing.
+ */
+const RESUBSCRIBE_DELAYS_MS = [0, 1_000, 3_000, 10_000, 30_000];
+
/**
* Subscribe to the session's appended frames. Every run reaches `follow`
- * at once; the appender hears it too, to keep the cached log in step. An
- * error or an end from the server is a gap: the subscription fell behind,
- * and the rows it dropped are only in the durable log.
+ * at once; the appender hears it too, to keep the cached log in step.
+ *
+ * A subscription that ends - an error, or the server completing it - is
+ * reopened, and then reported as a gap: the rows it dropped are only in the
+ * durable log, and the refetch starts after the new subscription so the two
+ * overlap. Left ended, the session would hear nothing more until it was
+ * opened again, and a control the runtime answered would wait on a reread.
*/
function followAppended(
sessionId: string,
follow: SessionLogFollow,
appender: Appender | undefined
): () => void {
- const { unsubscribe } = pipe(
- getGraphqlSoupClient().subscription<
- AgentSessionLogAppendedSubscription,
- AgentSessionLogAppendedSubscriptionVariables
- >(AgentSessionLogAppendedDocument, { sessionId }),
- subscribe((result) => {
- if (result.error) {
- console.warn(
- '[agent-session] log subscription interrupted',
- result.error
- );
- follow.gap();
- return;
- }
- const entries = result.data?.agentSessionLogAppended;
- if (!entries || entries.length === 0) return;
- let rows: AgentSessionLogEntryDto[];
- try {
- rows = entries.map((entry) => toRow(sessionId, entry));
- } catch (error) {
- console.warn('[agent-session] log subscription row unreadable', error);
+ let stopped = false;
+ let failures = 0;
+ let unsubscribe: (() => void) | undefined;
+ let reopen: ReturnType<typeof setTimeout> | undefined;
+
+ const open = () => {
+ let ended = false;
+ const end = (reason: 'error' | 'ended') => {
+ if (ended || stopped) return;
+ ended = true;
+ const delay =
+ RESUBSCRIBE_DELAYS_MS[
+ Math.min(failures, RESUBSCRIBE_DELAYS_MS.length - 1)
+ ];
+ failures += 1;
+ traceFollowResumed(sessionId, reason, failures, delay);
+ // Reopened from a timer, never inside the ending source's own callback.
+ reopen = setTimeout(() => {
+ reopen = undefined;
+ unsubscribe?.();
+ if (stopped) return;
+ open();
follow.gap();
- return;
- }
- appender?.appended(rows);
- follow.rows(rows);
- })
- );
- return unsubscribe;
+ }, delay);
+ };
+ ({ unsubscribe } = pipe(
+ getGraphqlSoupClient().subscription<
+ AgentSessionLogAppendedSubscription,
+ AgentSessionLogAppendedSubscriptionVariables
+ >(AgentSessionLogAppendedDocument, { sessionId }),
+ onEnd(() => end('ended')),
+ subscribe((result) => {
+ if (ended) return;
+ if (result.error) {
+ console.warn(
+ '[agent-session] log subscription interrupted',
+ result.error
+ );
+ end('error');
+ return;
+ }
+ const entries = result.data?.agentSessionLogAppended;
+ if (!entries || entries.length === 0) return;
+ failures = 0;
+ let rows: AgentSessionLogEntryDto[];
+ try {
+ rows = entries.map((entry) => toRow(sessionId, entry));
+ } catch (error) {
+ console.warn(
+ '[agent-session] log subscription row unreadable',
+ error
+ );
+ follow.gap();
+ return;
+ }
+ appender?.appended(rows);
+ follow.rows(rows);
+ })
+ ));
+ };
+ open();
+
+ return () => {
+ stopped = true;
+ clearTimeout(reopen);
+ unsubscribe?.();
+ };
}
type Appender = {
diff --git a/crates/agent_session_realtime/AGENTS.md b/crates/agent_session_realtime/AGENTS.md
index 0f18caedde..47f7d7b7f4 100644
--- a/crates/agent_session_realtime/AGENTS.md
+++ b/crates/agent_session_realtime/AGENTS.md
@@ -3,15 +3,16 @@
## What it is
Part of agent sessions: fans out newly appended agent session log frames,
-from Kafka to whoever is subscribed over GraphQL, so an open session view
-updates live.
+from the harness' Redis Stream to whoever is subscribed over GraphQL, so an
+open session view updates live.
## Start here
- `src/domain/service.rs` + `src/domain/ports.rs`: the fan-out service —
hands each consumed run of frames to its session's subscribers.
-- `src/outbound/log_topic_consumer.rs`: the Kafka consumer for
- `macro.agent_session_log` (behind the `consumer` feature).
+- `src/outbound/redis_stream.rs`: the `agent_session_log:v1` stream; its
+ `publisher` wraps the harness' realtime and its `consumer` feeds the
+ fan-out (both behind the `redis` feature).
## Scope
@@ -26,6 +27,14 @@ updates live.
- Used by: `complete_graph` (the GraphQL `agentSessionLogAppended`
subscription, its sole consumer).
+## Gotchas
+
+- A subscriber that falls 16 runs behind (a wake's `session/load` replay is a
+ burst) is closed, and its GraphQL stream ends with an error. That is the
+ contract, not a fault: the web watch (`apps/web/src/lib/queries/agent-session/log.ts`)
+ reopens the subscription and refetches the log. A client that does not
+ reopen hears nothing more from the session.
+
## Checks
- `cargo test -p agent_session_realtime` (`SQLX_OFFLINE` unset).
diff --git a/crates/complete_graph/src/schema.rs b/crates/complete_graph/src/schema.rs
index dce10e4dc0..365ec2460b 100644
--- a/crates/complete_graph/src/schema.rs
+++ b/crates/complete_graph/src/schema.rs
@@ -683,6 +683,11 @@ where
.collect::<Result<Vec<_>, _>>()
.map_err(|error| async_graphql::Error::new(error.to_string()));
}
+ // The viewer reopens and refetches; this is how often it has to.
+ tracing::warn!(
+ agent.session.id = %session_id,
+ "closing an agent session log subscription that fell behind"
+ );
yield Err(async_graphql::Error::new(
"agent session log subscription closed after falling behind",
));
diff --git a/docs/agent-guide/ai-chat.md b/docs/agent-guide/ai-chat.md
index 7e592d6e56..27e90b39a8 100644
--- a/docs/agent-guide/ai-chat.md
+++ b/docs/agent-guide/ai-chat.md
@@ -82,10 +82,15 @@ a persona, effort, or speed keeps the control request. Either way the prompt
shows as one bubble that the logged row confirms in place.
Switching a disconnected session's model wakes its runtime first; the
-selector re-enables with the new model's options once the runtime answers. If
-the live feed misses that answer, the client reads the log after 10 seconds,
-and after a minute it takes back an unconfirmed change, so the selector shows
-the runtime's model again and stays usable.
+selector re-enables with the new model's options once the runtime answers.
+The wake replays the session, and a viewer whose live log subscription falls
+behind that burst is closed by the server; the client reopens it at once and
+refetches the log, so the answer still arrives live. If it is missed anyway,
+the client reads the log after 10 seconds, and after a minute it takes back an
+unconfirmed change, so the selector shows the runtime's model again and stays
+usable. `agent.session.confirm_control` records whether the live feed or the
+reread settled it, and `agent.session.log.follow_resumed` each reopened
+subscription.
Macro's in-process agent opens each reply with a line from a fast model
(`gpt-5.4-mini`), usually within half a second of Enter. Small talk