Repository navigation
Deliver outbound messages concurrently across sessions - #60
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub. 1 Skipped Deployment
|
A burst of busy sessions could exhaust the server's default budget for cluster API requests, which is sized for a command-line tool. Once that happened, agent replies and approval prompts reached the chat channel many minutes late, long enough for prompts to expire unseen. The default budget is now sized for a server; an explicitly configured limit is still respected.
95547d3 to
f68eb6d
Compare
b20de72 to
e86fd06
Compare
Delivering any outbound message, including each piece of streamed text, required a fresh lookup against the cluster, which capped how quickly messages could be delivered. Those lookups are now served from a local cache that stays in sync with the cluster. Changes the service makes itself are read back directly for a short while, so it never acts on a copy older than its own update. The service's permissions are extended to keep the cache in sync.
Outbound messages for every session were delivered one at a time, so a single slow delivery delayed every other session's replies and approval prompts. Sessions are now delivered concurrently, up to a bound, while each session's own messages keep their order. A session whose backlog keeps growing is logged. Two behaviors that relied on one-at-a-time delivery are fixed: sessions starting together on one channel could end up with duplicate plan cards, a never-ending elapsed-time counter, or a second streaming message; and a channel's delivery status could get stuck in the wrong state.
A delivery that never returned kept its concurrency slot forever, so enough stuck sessions at once would block everyone else again, and a stuck session's queued messages could grow without limit. Each message's delivery now has a deadline, after which it is abandoned and logged, freeing its slot. Each session's queue is capped; beyond the cap its newest messages are dropped and logged. Shutdown now waits for messages already queued to be delivered, up to the caller's deadline.
f68eb6d to
8aea492
Compare
839eaa2 to
7188f51
Compare
Shutdown cancelled the context every delivery was running under, so messages still queued or in flight were cut off, and the wait for them was given an already-cancelled deadline and returned at once. Deliveries are now bounded only by their own deadline, and shutdown waits a fixed grace period for queued messages to go out.
The session cache this branch was built on has since merged to main in a reworked form. Main's version of it is taken as is, and concurrent delivery sits on top: the per-channel delivery-status lock now wraps main's conflict-retrying status write.
Three comments said the relay handles every session on a single goroutine. Sessions are now delivered concurrently, so they describe the bounded concurrency instead.
samkim
left a comment
There was a problem hiding this comment.
What this does. Stacked on #59, it makes the outbound relay deliver different sessions concurrently (bounded lanes, one ordered queue per session), adds a per-delivery deadline and a capped queue per session, and drains queued messages on shutdown. The concurrency and ordering design checks out; the failure paths around the new deadline and the queue cap do not fully hold up.
Verdict: ready after the inline fixes, and after a rebase.
Rebase needed. #59 merged to main as a1ae02f in a substantially revised form (resourceVersion-tracked writes through trackingClient, and noteDeliveryOutcome now uses RetryOnConflict with an optimistic lock). The first three commits on this branch (583dbe0, 4aa711a, 8aea492) are the older #59 and should drop out. Expect conflicts in deliverable.go and relay.go. The per-Channel lock this PR adds has to wrap main's retry loop, not replace it. This review covers only the PR's own commits (48530b1, 7188f51, 5cdb904).
Issues, highest impact first
- A delivery that hits the 2 minute deadline is never reported to the user. The failure notice and the Channel's Deliverable status both run on the already-expired context, so they fail immediately. A slow file upload on a
respond_to_userends in silence. See inline onrelay.go. - A full session queue drops the newest envelope of any kind, which can be the final reply or an approval card. Only a log line remains. I could not show the trigger (it needs about 10,000 queued envelopes behind a stalled head), so this is plausible, not confirmed. See inline on
session_lanes.go. - Nit: the per-Channel lock is taken before the "outcome unchanged" check, so sessions on one Channel wait on each other while holding concurrency slots. See inline on
deliverable.go. - Nit: the comment in
pkg/platform/kube/config.go:15-17still says the relay runs "on a single serialized goroutine". Reword it as history once lanes land. It is not in this PR's own diff, so no inline comment.
Questions for the author
- When a session's queue is full, should human-directed envelopes (user messages, approval and interaction cards) ever be dropped? Options are exempting them from the cap, dropping or coalescing stream deltas first, or posting a delivery-failure notice when a non-delta is dropped. The right trade between memory bound and never losing a reply is your call.
- For the per-Channel lock: is it acceptable that sessions on one Channel serialize while one writes status, or should the memo check come first? The memo-first version can skip a success that races an in-flight failure, leaving the condition False until the next success. Which do you prefer?
- Is the declared limitation (a delegated child's approval can post at channel level while the parent's lane is still opening its thread) tracked in an issue, and is the fallback strictly one-time per delegation? I found no deadlock and no permanent misroute in the code (
relay.go:190keys lanes by publishing session).
Everything confirmed is anchored inline, except item 4 above.
This review was drafted by an automated pipeline and checked before submission.
| r.lanes = newSessionLanes(ctx, r.MaxConcurrentSessions, r.MaxLaneBacklog, func(msg *nats.Msg) { | ||
| hctx, cancel := context.WithTimeout(deliveryCtx, timeout) | ||
| defer cancel() | ||
| r.handle(hctx, msg) |
There was a problem hiding this comment.
[important] An envelope abandoned at the 2m deadline can never surface its failure
Problem: hctx (a 2m deadline, line 180) is passed to handle, which uses it for sender.Send (relay.go:913), noteDeliveryOutcome (:918), surfaceDeliveryFailure (:929) and its fallback sender.Send (:1000). When a slow Slack upload hits the deadline, Send returns context.DeadlineExceeded, and then the fallback "couldn't deliver" notice and the Deliverable status Get/Patch run on the same expired context and fail at once. The user sees no reply and no notice, and the Channel condition is not updated; only log lines remain. Before this PR the context was the process root, so the fallback could run. DefaultHandleTimeout's doc claims the abandoned delivery "fails through the ordinary send-error path", which is false for this case.
Fix: in handle, once sender.Send has returned an error, run noteDeliveryOutcome and surfaceDeliveryFailure on a fresh short-lived context derived from context.WithoutCancel(ctx) with its own small timeout (for example 10s), so the notice gets its own budget. Leave the first send bounded by hctx. Update the DefaultHandleTimeout comment to match.
Test: in pkg/channels/channelsd/outbound/session_lanes_test.go or relay_test.go, add TestRelay_DeadlineExceededSendStillSurfacesFailureNotice: a fake sender whose first Send blocks until ctx is done and returns ctx.Err(), a short HandleTimeout, a KindUserMessage envelope; assert the fake received a second Send carrying deliveryFailureNotice with a live ctx, and that the Deliverable condition was patched. Run go test -race ./pkg/channels/channelsd/outbound/ -run DeadlineExceededSend.
Constraints: CLAUDE.md "Never silently drop errors" (surface a user-visible message when the failure affects something the user is waiting for).
There was a problem hiding this comment.
Fixed in 0dcc4c6: after a failed send, the Deliverable write and the failure notice now run on their own 10s context (detached from the expired delivery deadline), so a delivery abandoned at 2m is recorded and the user gets the notice, and the lane then moves on. DefaultHandleTimeout's comment is corrected, and TestRelay_DeliveryAbandonedAtDeadlineIsStillReported covers it with a context-honouring client (it fails on the previous code).
There was a problem hiding this comment.
Verified at e8f4c56: after a failed send, noteDeliveryOutcome and surfaceDeliveryFailure run on a 10s context detached from the expired delivery deadline (relay.go:1017-1038), and the DefaultHandleTimeout comment now matches. TestRelay_DeliveryAbandonedAtDeadlineIsStillReported covers it.
| l.lanes[key] = ln | ||
| } | ||
| if len(ln.pending) >= l.maxBacklog { | ||
| ln.dropped++ |
There was a problem hiding this comment.
[important] A full lane drops the newest envelope of any kind, including the final reply or an approval card
Problem: when len(ln.pending) >= l.maxBacklog, dispatch drops the arriving message whatever it is, and the only trace is a log on the 1st and every 500th drop. Stream deltas arrive one per token on the same lane, so if a lane's head stalls (up to 2m per envelope) and 10,000 deltas queue, the turn's user_message or an approval card is dropped and nothing reaches the user. This is plausible, not demonstrated: it needs about 10,000 queued envelopes behind a stalled head.
Verify: confirm the real delta rate against a stall of two or three consecutive deadlines. The envelope kind is available without decoding via channelevents.ParseOutSubjectKind (channelevents/envelope.go:682), so dispatch can tell deltas from other kinds.
Fix: this is a design decision, so no single fix is prescribed (see the review's question 1). The options are to exempt human-directed kinds from the cap, to drop or coalesce stream deltas first, or to surface a delivery-failure notice when a non-delta is dropped. Whichever is chosen, a dropped non-delta must leave more than a log line.
Test: extend TestSessionLanes_FullLaneDropsNewestAndKeepsOthersFlowing in session_lanes_test.go with a case that fills a lane with deltas and then dispatches a user_message, asserting the chosen behaviour. Run go test -race ./pkg/channels/channelsd/outbound/ -run FullLane.
Constraints: CLAUDE.md "Never silently drop errors" (log at INFO+ with context, or surface a user-visible message).
There was a problem hiding this comment.
Fixed in 5f95681: a full lane now drops by kind rather than by position. Progress (stream deltas, tool_activity, turn_progress, operation_activity) is dropped on arrival and evicted oldest-first to admit anything else; user_message and the interaction family are admitted past the cap into a reserve of the same size and dropped only beyond that, so memory stays bounded at twice the cap. Every overflow episode logs session and kind and posts one notice to the session's channel; blocking instead was not an option because the subscription is core NATS (no ack or redelivery), so it would only move the drop into the client for every session.
There was a problem hiding this comment.
Verified at e8f4c56 (fixed differently): the lane drops by kind, protects user_message and the interaction family in a 2x reserve, logs every protected drop and posts one notice per episode (session_lanes.go:166-184, humandirected.go:56-101). Tests at session_lanes_test.go:341, :445, :481. Two follow-ups on the classification are new inline comments (humandirected.go:76, session_lanes.go:179).
| // then record in opposite orders — leaving the memo disagreeing with the | ||
| // live condition, which then suppresses every later write that would fix | ||
| // it. Writes happen only when the outcome changes, so this rarely waits. | ||
| unlock := r.lockDeliveryChannel(key) |
There was a problem hiding this comment.
[nit] Per-Channel lock is taken before the "outcome unchanged" check, so unchanged outcomes still queue
Problem: every noteDeliveryOutcome takes lockDeliveryChannel(key) before reading the memo (lines 73-81). While one session does its Get+Patch (up to the 2m deadline, and longer once main's RetryOnConflict loop is rebased in), every other session on that Channel blocks on a plain sync.Mutex that ignores ctx, even if its outcome equals the memo, and each holds one of the relay's concurrency slots while it waits.
Fix: this is a trade-off, so choose deliberately (review question 2). Option A: keep the lock as is. Option B: check the memo first and take the lock only on a difference, rechecking inside the lock; note this can skip a success racing an in-flight failure, leaving the condition False until the next success. Whichever is chosen, make the lock acquisition honour ctx (for example a chan struct{} of size 1 with a select on ctx.Done()) so a waiter cannot outlive its deadline. After the rebase onto main, the lock must wrap main's RetryOnConflict + MergeFromWithOptimisticLock loop.
Test: in deliverable_test.go, add a case where one outcome's patch blocks and a second session with an unchanged outcome and a short ctx returns promptly (or errors on ctx) instead of waiting. Run go test -race ./pkg/channels/channelsd/outbound/ -run Deliverab.
There was a problem hiding this comment.
Fixed in 205d7b1: the memo is checked first and again under the lock (option B), and the lock is now a one-slot channel whose wait ends with ctx. The trade you describe is accepted and documented at the check: a success overlapping an in-flight failure is skipped and the condition reads False until the next success, while the memo still always agrees with the live condition. The lock wraps main's RetryOnConflict + optimistic-lock loop.
There was a problem hiding this comment.
Verified at e8f4c56: memo checked first and again under the lock, the lock gives up with ctx (deliverable.go:77-104, :164-180), and it wraps the RetryOnConflict loop. The trade is documented at deliverable.go:68-76. TestNoteDeliveryOutcome_DoesNotWaitBehindAnotherSessionsWrite covers both paths.
…annel A delivery that ran out its deadline was followed by a failure notice and a delivery-status write on the same, already expired, context, so both failed at once and the user saw nothing. What follows a failed send now runs on a short budget of its own, so the notice and the status write are attempted for real and the session's next message goes out after them.
…or the Channel's status lock Every delivery took its Channel's status lock before checking whether its outcome was already the recorded one, so sessions sharing a Channel waited on each other's status writes while holding a concurrency slot. The recorded outcome is now checked first and again under the lock, and waiting for the lock ends with the delivery's own context.
… tell the channel what was skipped A full session queue dropped whatever arrived next, which behind a slow delivery is the reply or an approval prompt, and left only a log line. A full queue now gives up progress updates first: they are dropped on arrival, and queued ones make room for anything else. Replies and interaction prompts are admitted past the cap, up to as much again, and dropped only beyond that. Each drop is logged with its session and kind, and the session's channel is told once per overflow that updates were skipped.
|
On the review body:
|
samkim
left a comment
There was a problem hiding this comment.
Round 2 review, commits 5cdb904..e8f4c56 (author's own: bc56f29, 0dcc4c6, 205d7b1, 5f95681, e8f4c56, plus the main merge).
All three earlier threads are verified fixed: 3 of 3, plus the config.go comment and the rebase concern. The abandoned delivery is now reported on its own 10s context (relay.go:1017-1038), a full lane sheds progress and protects replies and approval cards (session_lanes.go, humandirected.go), and the delivery-status lock is checked memo-first and honours ctx (deliverable.go).
Verdict: ready after the inline fixes. The new queue classification has one real defect and a few nits.
Open issues, highest first:
- [minor] Stream "stop" events are classified as sheddable, so a full lane can drop the event that finalises a Slack streaming bubble, leaving a stale bubble and misplaced later replies. See inline on humandirected.go:76.
- [nit] The overflow notice goes out as a
user_messageand can overwrite a streaming bubble on Slack. See inline on relay.go:1199. - [nit] A newer progress snapshot is dropped in favour of older queued ones. See inline on session_lanes.go:179.
- [nit] Hand-rolled lock where
semaphore.Weightedfits, and a two-row table test. See inline on deliverable.go:164 and deliverable_test.go:284.
Question still open:
- Is the delegated-approval limitation from the earlier round tracked anywhere, and is there a one-time fallback? You said you would follow up; this does not block the PR.
The reserve size for protected envelopes (2x the cap) is your call; nothing in the review depends on it.
This review was drafted by an automated pipeline and checked before submission.
| // transition the silence watchdog cannot infer), and the tool_session stream | ||
| // (output, not progress — a gap corrupts it). | ||
| var sheddableKinds = map[channelevents.Kind]struct{}{ | ||
| channelevents.KindAssistantStreamDelta: {}, |
There was a problem hiding this comment.
[minor] A full lane can drop the stream "stop" event, leaving Slack with a stale streaming bubble
Problem: sheddableKinds lists KindAssistantStreamDelta wholesale, but that kind also carries eventType: "stop", a state transition and not superseded progress. The Slack sink only finalises a bubble on "stop" (pkg/channels/channelkinds/slack/stream_delta_sink.go:164-176). A sheddable arriving at a full lane is dropped on arrival (session_lanes.go:179), and the "stop" ending the LLM call whose deltas filled the lane arrives last, so it is the likeliest to be dropped. Result on Slack: the user_message is admitted (protected), ConsumeFinalTarget returns "" (stream_delta_sink.go:190-203), so the reply posts as a new message under a stale partial bubble. placeholder and buf survive, so the next turn's deltas edit the old bubble and the next reply is chat.updated far up the thread. The exclusion list in this file (tool_progress Done=true, turn_activity) applies the same rule this entry breaks.
Fix: in backlogClassOf (humandirected.go:87), for KindAssistantStreamDelta peek at the payload's eventType and return backlogOrdinary for anything other than a text_delta (at least "stop"; tool_use_start/stop too). The classify hook runs in the NATS callback, so keep the peek to a cheap partial JSON decode of the envelope's payload field. Update the comment above sheddableKinds to say only text deltas are shed. An alternative is to make the Slack sink treat an unfinalised placeholder as the final target when a user_message arrives; that touches another package, so prefer the classify fix.
Test: extend TestSessionLanes_FullLaneDropsByKindAndReportsOncePerEpisode (session_lanes_test.go:341) or add a backlogClassOf test: a stream-delta subject with a "stop" payload is not shed while a "text_delta" one is. Run go test -race ./pkg/channels/channelsd/outbound/ -run 'FullLane|BacklogClass'.
There was a problem hiding this comment.
Fixed in b9139e4: only text_delta is shed now; stop is classed as protected rather than ordinary, because the protected reply is placed by whether the bubble was finalised, and it is published once per model call so it cannot spend the reserve. Other stream events (tool_use_start/tool_use_stop, unknown types, undecodable bodies) are ordinary, and going through the rest of the list turned up one more finalising event: an operation_activity with cleared set is no longer shed either. Covered by TestBacklogClassOf_ShedsProgressButNotTheEventThatEndsIt and TestRelay_FullBacklogKeepsTheEventThatEndsAStream, both failing on the previous code.
There was a problem hiding this comment.
Verified at b9139e4: only text_delta is shed; stop is protected (humandirected.go:146), tool_use_*, unknown types and undecodable bodies are ordinary (:157-160), and a cleared operation_activity is ordinary (:138). Protected is the right class: Slack finalises the bubble only on stop (slack/stream_delta_sink.go:164-176) and it is published once per model call. Covered by TestBacklogClassOf_ShedsProgressButNotTheEventThatEndsIt (session_lanes_test.go:573) and TestRelay_FullBacklogKeepsTheEventThatEndsAStream (:532). One comment nit is on humandirected.go:74.
| logger.Info("outbound relay: build backlog-overflow notice failed", "err", err.Error()) | ||
| return | ||
| } | ||
| _, err = sender.Send(ctx, sessionInfoFor(&sess, binding), notice) |
There was a problem hiding this comment.
[nit] Backlog-overflow notice is sent as KindUserMessage and can overwrite a streaming bubble
Problem: senders treat user_message as the turn's final reply. The Slack sender consumes finalizedTS and chat.updates the streaming bubble with the response-ready emoji plus the notice text (pkg/channels/channelkinds/slack/sender.go:316-330); the browser chat clears its live draft on it (pkg/web/webui/chat/ui/ChatView.tsx:508-520). The notice is sent mid-turn, ahead of the queue, so after an intermediate LLM call's "stop" it replaces that call's streamed text. surfaceDeliveryFailure uses the same kind, but only after the reply itself failed, where finalising is correct.
Fix: in surfaceBacklogOverflow, build the notice with a notice-shaped kind (for example KindNotification, or whichever kind the channel kinds already render as a mid-turn notice) instead of KindUserMessage. If no suitable kind exists for human channels, keep this and document the trade in the function comment.
Test: extend TestRelay_FullBacklogShedsProgressNotTheReplyAndTellsTheChannel (session_lanes_test.go:481) to assert the notice's envelope kind. Run go test -race ./pkg/channels/channelsd/outbound/ -run FullBacklog.
There was a problem hiding this comment.
Changed in b9139e4: the overflow notice is now an interaction notice (interaction_request, existing internal_error category) instead of a user_message, handed to handle on the lane so it is routed, recorded in interaction history and rendered like every other notice. KindNotification was not the fit: it is the transient status caption, not a durable message. Two things to check: it reuses internal_error rather than adding a category row, and because it now takes the human-directed route, a delegated child's overflow reaches the nearest human-readable channel in its lineage where it was previously only logged.
There was a problem hiding this comment.
Verified at b9139e4 (fixed differently): the overflow notice is an internal_error interaction notice handed to handle on the lane goroutine (relay.go:1146, :1174-1205; drain runs onOverflow between envelopes, session_lanes.go:218-222), so it is serialized with that session's lane and no longer overwrites a streaming bubble. Your two questions: (1) Reusing internal_error is fine: Degraded, retry is the remedy. Optionally add a line to its doc comment (pkg/channels/channelinteractions/categories/notices.go:20-25), which says inbound paths only. (2) Routing a delegated child's overflow through the lineage to the nearest human channel is acceptable: its approval cards already go there and the notice is attributed to the child. Test: session_lanes_test.go:488.
| return true | ||
| case class == backlogProtected && len(ln.pending) < 2*l.maxBacklog: | ||
| return true | ||
| default: |
There was a problem hiding this comment.
[nit] A sheddable arrival at a full lane is dropped even when older sheddables are queued
Problem: makeRoomLocked case 1 only evicts for class != backlogSheddable, so a newer progress snapshot is dropped and the stalest kept, the reverse of the "each snapshot replaces the last" rationale at humandirected.go:69-71. A lane holding early-turn turn_progress drops the turn's final one, so after the drain the channel shows early progress as the last snapshot. It is also what makes the stream "stop" drop (see the comment at humandirected.go:76) likely.
Fix: drop the class != backlogSheddable condition in case 1 (session_lanes.go:168) for the eviction branch, so a sheddable arrival with ln.sheddable > 0 evicts the oldest sheddable and is admitted; keep the on-arrival drop only when nothing sheddable is queued. Update the backlogSheddable comment (session_lanes.go:43-46).
Test: add a case to TestSessionLanes_FullLaneDropsByKindAndReportsOncePerEpisode (session_lanes_test.go:341): progress arrives at a lane full of progress, the oldest is evicted and the arrival handled. The existing "progress arrives at a lane full of progress: the arrival is dropped" case must change with it. Run go test -race ./pkg/channels/channelsd/outbound/ -run FullLane.
There was a problem hiding this comment.
Fixed in b9139e4: a sheddable arrival at a full lane now evicts the oldest queued sheddable and is admitted, and is dropped on arrival only when nothing sheddable is queued. The existing table case changed with it (s1..s5 at cap 3 now delivers s3, s4, s5) and a case was added for the nothing-to-evict path.
There was a problem hiding this comment.
Verified at b9139e4: case ln.sheddable > 0 (session_lanes.go:170) evicts the oldest sheddable for any arrival, and an arrival is dropped only when nothing sheddable is queued (:178-181). Table case changed (session_lanes_test.go:358) and a new case added. One side effect: evicting to admit kept a full lane at exactly the cap, so the "session backlog growing" line fired per token. Fixed in bdcc4e2 (pushed to this branch): the line now logs only when the queue grows, covered by TestSessionLanes_BacklogGrowthIsLoggedOnlyWhenTheQueueGrows.
| // giving up with ctx's error if ctx ends first. A one-slot channel rather than | ||
| // a sync.Mutex so that waiting can be abandoned. The lock map is bounded like | ||
| // delivOutcomes, by the Channels actually routed through. | ||
| func (r *Relay) lockDeliveryChannel(ctx context.Context, key string) (unlock func(), err error) { |
There was a problem hiding this comment.
[nit] Hand-rolled ctx-abandonable lock
Problem: lockDeliveryChannel builds a one-slot channel plus select on ctx.Done(), which is semaphore.NewWeighted(1).Acquire(ctx, 1). golang.org/x/sync v0.22.0 is already a direct dependency (go.mod:68). Low value; the current code is correct.
Fix: optional. Store *semaphore.Weighted in delivLocks and release with Release(1). Skip if you prefer to avoid the first semaphore use in the repo.
Test: no new test; go test -race ./pkg/channels/channelsd/outbound/ -run NoteDeliveryOutcome must stay green.
Constraints: CLAUDE.md "Prefer a library over a hand-rolled utility".
There was a problem hiding this comment.
Done in f787389: delivLocks now holds *semaphore.Weighted and the lock is Acquire(ctx, 1) / Release(1); golang.org/x/sync was already a direct dependency, so no module was added.
There was a problem hiding this comment.
Verified at b9139e4: delivLocks holds *semaphore.Weighted with Acquire(ctx, 1) / Release(1) (deliverable.go:165-180); no module added.
| // each hold a concurrency slot while they record their own outcome. Neither an | ||
| // outcome that is already recorded nor one whose delivery has run out of time | ||
| // may sit behind another session's write in flight. | ||
| func TestNoteDeliveryOutcome_DoesNotWaitBehindAnotherSessionsWrite(t *testing.T) { |
There was a problem hiding this comment.
[nit] Two-row table in TestNoteDeliveryOutcome_DoesNotWaitBehindAnotherSessionsWrite
Problem: the table has exactly two cases. CLAUDE.md says "Two tests is not a table."
Fix: optional. Split into two t.Run subtests sharing a local helper for the setup, keeping the descriptive names.
Test: go test -race ./pkg/channels/channelsd/outbound/ -run DoesNotWaitBehind.
Constraints: CLAUDE.md "Test conventions: testify + table-driven, where it makes sense".
There was a problem hiding this comment.
Done in 6a45544: the table is now two t.Run subtests sharing a local helper, with the same names.
There was a problem hiding this comment.
Verified at b9139e4: two t.Run subtests over a shared helper (deliverable_test.go:331, :334), same names.
| r.lanes = newSessionLanes(ctx, r.MaxConcurrentSessions, r.MaxLaneBacklog, func(msg *nats.Msg) { | ||
| hctx, cancel := context.WithTimeout(deliveryCtx, timeout) | ||
| defer cancel() | ||
| r.handle(hctx, msg) |
There was a problem hiding this comment.
Verified at e8f4c56: after a failed send, noteDeliveryOutcome and surfaceDeliveryFailure run on a 10s context detached from the expired delivery deadline (relay.go:1017-1038), and the DefaultHandleTimeout comment now matches. TestRelay_DeliveryAbandonedAtDeadlineIsStillReported covers it.
| l.lanes[key] = ln | ||
| } | ||
| if len(ln.pending) >= l.maxBacklog { | ||
| ln.dropped++ |
There was a problem hiding this comment.
Verified at e8f4c56 (fixed differently): the lane drops by kind, protects user_message and the interaction family in a 2x reserve, logs every protected drop and posts one notice per episode (session_lanes.go:166-184, humandirected.go:56-101). Tests at session_lanes_test.go:341, :445, :481. Two follow-ups on the classification are new inline comments (humandirected.go:76, session_lanes.go:179).
| // then record in opposite orders — leaving the memo disagreeing with the | ||
| // live condition, which then suppresses every later write that would fix | ||
| // it. Writes happen only when the outcome changes, so this rarely waits. | ||
| unlock := r.lockDeliveryChannel(key) |
There was a problem hiding this comment.
Verified at e8f4c56: memo checked first and again under the lock, the lock gives up with ctx (deliverable.go:77-104, :164-180), and it wraps the RetryOnConflict loop. The trade is documented at deliverable.go:68-76. TestNoteDeliveryOutcome_DoesNotWaitBehindAnotherSessionsWrite covers both paths.
… send the overflow notice as a notice A full queue shed every stream delta alike, including the "stop" that finalises a streamed message, so the reply that followed could land in the wrong place. Only text deltas are shed now; the stop is kept alongside the reply, and an operation_activity marked cleared is no longer shed either. Newer progress now replaces the oldest queued progress instead of being dropped on arrival, so what survives is the latest snapshot. The notice that updates were skipped went out as a user_message, which surfaces treat as the agent's reply. It is now an interaction notice, delivered and recorded the way every other notice is.
|
On the question still open from round 2 (the delegated-approval limitation):
Round-2 inline items are addressed in f787389, 6a45544 and b9139e4, with replies on each thread. |
A full lane admits newer progress by evicting the oldest queued progress, which leaves the queue at its cap. The cap (10000 by default) is a multiple of laneBacklogWarnEvery, so the growth line fired on every arrival, once per token for the whole overflow, defeating the throttling noteDropLocked applies to the drops themselves. Growth into the protected reserve still logs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
samkim
left a comment
There was a problem hiding this comment.
Round 3 review, commits e8f4c56..b9139e4 (author's own: f787389, 6a45544, b9139e4), plus bdcc4e2 pushed by the reviewer.
Earlier threads: 8 of 8 are verified fixed. The five round-2 issues are all fixed in this round's changes: the stream stop event is no longer shed (it is protected, and only text_delta is shed), the overflow notice is now an interaction notice routed like every other notice instead of a user_message, a newer progress update now replaces an older queued one at a full lane, the delivery-status lock uses semaphore.Weighted, and the two-case table test is two subtests. The outbound package tests pass under -race.
Verdict: ready. The one new issue this round turned up is fixed in bdcc4e2, which I pushed to this branch: once a full lane started dropping older progress to admit newer progress, the "session backlog growing" log line fired on every incoming token. It now logs only when the queue actually grows, with a test (TestSessionLanes_BacklogGrowthIsLoggedOnlyWhenTheQueueGrows) that fails without the fix. CI was still running on it when this review was submitted.
Remaining, optional:
- [nit] The comment on
sheddableKindsoverstates what a shedtext_deltacosts: only a turn's last bubble is rewritten by the reply. See inline on humandirected.go:74.
Questions for the author: none open. The delegated-approval question from the earlier rounds was answered (tracked only in the PR description, no fallback). Filing an issue for it is your call and does not block this PR.
On your two explicit asks for the overflow notice: reusing internal_error is fine (Degraded, retry is the remedy). Routing a delegated child's overflow through the lineage to the nearest human channel is acceptable and matches where its approval cards already go. One optional line: the doc comment on InternalError in pkg/channels/channelinteractions/categories/notices.go:20-25 still says it is only for inbound paths.
This review was drafted by an automated pipeline and checked before submission.
| // them apart. | ||
| // | ||
| // - KindAssistantStreamDelta's text_delta is the live rendering of a reply | ||
| // whose full text arrives in the user_message that finalises it. It is |
There was a problem hiding this comment.
[nit] Comment overstates what shedding a text_delta costs
Problem: this says a text_delta's "full text arrives in the user_message that finalises it". On Slack the sink finalises per model call on stop, and each later stop overwrites finalizedTS (pkg/channels/channelkinds/slack/stream_delta_sink.go:164-176, :190-203), so only the turn's last bubble is rewritten by the user_message. Narration streamed before a tool call is never rewritten, and a shed text_delta leaves a permanent gap in that earlier bubble. This loss is accepted (it existed before this change), but the comment should not claim it is harmless.
Fix: reword the KindAssistantStreamDelta bullet (humandirected.go:74-76) to say that the reply's full text arrives in the final user_message only for the turn's last model call, and that a shed text_delta from an earlier call is a permanent gap in that earlier bubble, accepted because the alternative is dropping a reply or approval card.
Test: none, comment only. go vet ./pkg/channels/channelsd/outbound/ must stay green.
| // transition the silence watchdog cannot infer), and the tool_session stream | ||
| // (output, not progress — a gap corrupts it). | ||
| var sheddableKinds = map[channelevents.Kind]struct{}{ | ||
| channelevents.KindAssistantStreamDelta: {}, |
There was a problem hiding this comment.
Verified at b9139e4: only text_delta is shed; stop is protected (humandirected.go:146), tool_use_*, unknown types and undecodable bodies are ordinary (:157-160), and a cleared operation_activity is ordinary (:138). Protected is the right class: Slack finalises the bubble only on stop (slack/stream_delta_sink.go:164-176) and it is published once per model call. Covered by TestBacklogClassOf_ShedsProgressButNotTheEventThatEndsIt (session_lanes_test.go:573) and TestRelay_FullBacklogKeepsTheEventThatEndsAStream (:532). One comment nit is on humandirected.go:74.
| logger.Info("outbound relay: build backlog-overflow notice failed", "err", err.Error()) | ||
| return | ||
| } | ||
| _, err = sender.Send(ctx, sessionInfoFor(&sess, binding), notice) |
There was a problem hiding this comment.
Verified at b9139e4 (fixed differently): the overflow notice is an internal_error interaction notice handed to handle on the lane goroutine (relay.go:1146, :1174-1205; drain runs onOverflow between envelopes, session_lanes.go:218-222), so it is serialized with that session's lane and no longer overwrites a streaming bubble. Your two questions: (1) Reusing internal_error is fine: Degraded, retry is the remedy. Optionally add a line to its doc comment (pkg/channels/channelinteractions/categories/notices.go:20-25), which says inbound paths only. (2) Routing a delegated child's overflow through the lineage to the nearest human channel is acceptable: its approval cards already go there and the notice is attributed to the child. Test: session_lanes_test.go:488.
| return true | ||
| case class == backlogProtected && len(ln.pending) < 2*l.maxBacklog: | ||
| return true | ||
| default: |
There was a problem hiding this comment.
Verified at b9139e4: case ln.sheddable > 0 (session_lanes.go:170) evicts the oldest sheddable for any arrival, and an arrival is dropped only when nothing sheddable is queued (:178-181). Table case changed (session_lanes_test.go:358) and a new case added. One side effect: evicting to admit kept a full lane at exactly the cap, so the "session backlog growing" line fired per token. Fixed in bdcc4e2 (pushed to this branch): the line now logs only when the queue grows, covered by TestSessionLanes_BacklogGrowthIsLoggedOnlyWhenTheQueueGrows.
| // giving up with ctx's error if ctx ends first. A one-slot channel rather than | ||
| // a sync.Mutex so that waiting can be abandoned. The lock map is bounded like | ||
| // delivOutcomes, by the Channels actually routed through. | ||
| func (r *Relay) lockDeliveryChannel(ctx context.Context, key string) (unlock func(), err error) { |
There was a problem hiding this comment.
Verified at b9139e4: delivLocks holds *semaphore.Weighted with Acquire(ctx, 1) / Release(1) (deliverable.go:165-180); no module added.
| // each hold a concurrency slot while they record their own outcome. Neither an | ||
| // outcome that is already recorded nor one whose delivery has run out of time | ||
| // may sit behind another session's write in flight. | ||
| func TestNoteDeliveryOutcome_DoesNotWaitBehindAnotherSessionsWrite(t *testing.T) { |
There was a problem hiding this comment.
Verified at b9139e4: two t.Run subtests over a shared helper (deliverable_test.go:331, :334), same names.
Summary
Outbound messages for every session were delivered one at a time, so one session's slow delivery delayed every other session's replies and approval prompts.
Sessions are now delivered concurrently (up to a limit), while each session's own messages still arrive in the order they were sent. A session whose backlog keeps growing is logged.
A single stuck session is also contained: each delivery has a deadline, after which it is abandoned so it cannot hold up others indefinitely, and the user is told the reply could not be delivered. Each session's queue is capped so a stuck session cannot grow without limit: beyond the cap, progress updates are dropped first, replies and approval prompts are kept unless the queue grows to twice the cap, and the channel is told once that updates were skipped. Shutdown waits for messages already queued to go out.
Two things that only worked because delivery was one-at-a-time are fixed along the way:
Known limitation: if a delegated agent raises an approval while its parent is still posting its very first message, the approval can appear at channel level rather than in the parent's thread.
Testing