Skip to content

fix(infra): the load balancer keeps a browser on one host - #798

Merged
allisonmahmood merged 2 commits into
mainfrom
fix/749-balancer-stickiness
Oct 19, 2026
Merged

allisonmahmood merged 2 commits into
mainfrom
fix/749-balancer-stickiness

Conversation

@allisonmahmood

@allisonmahmood allisonmahmood commented Oct 19, 2026 •

Copy link
Copy Markdown
Owner

What changed

Subscription POSTs sometimes reached the host that doesn't hold the document's stream, got a 409 stream_replaced, and the shell tore the stream down and reconnected (8 of the last 15 production document opens). The target group stuck on our patchy_stream_affinity application cookie, scoped to /api/runtime. ALB app-cookie stickiness only holds when a request carries both that cookie and the ALB's own AWSALBAPP-* cookie, which is Path=/. Every other request (the page, its scripts, the frame's ~content) carried only the ALB cookie, so the ALB round-robined it and its response cleared stickiness (AWSALBAPP-n=_remove_). When the frame's content response landed after the stream opened, the subscription POSTs that followed alternated hosts.

The load balancer now owns stickiness with its own cookie, and ours is gone:

  • Infra. The Hosts target group uses duration-based stickiness (stickiness.type=lb_cookie, the ALB's AWSALB cookie), still one day. The ALB sets AWSALB on the page's own response, before the shell sends anything else. Once a browser holds that cookie and its host is healthy, every request from it reaches that host. Two tabs opened at once without a cookie, or a drain, can briefly put a stream on another host than the cookie names; on target loss the ALB picks a healthy host and updates the cookie. The existing 409 → immediate reconnect (perf(serving): a stream lost to a misrouted subscription reconnects at once #776) covers those gaps. The tier 2 spike script gets the same attributes.
  • Server. The stream no longer sets patchy_stream_affinity. The subscription request event drops affinityCookie/affinityMatched and keeps balancerCookie, now keyed on the AWSALB name, never its value. documentConnected: false plus replica still identifies a misroute. Wire bodies are unchanged. Without the cookie the stream API needs no secure flag, so its layer and layerLocal become one layer.
  • Docs. The runtime stream description and docs/API.md, ADR-0010's stickiness contract (with why app-cookie stickiness failed), ADR-0012's production topology, the Operations refusal query and spike notes, and the Analytics glossary.

Closes #749

How it was verified

  • pnpm check and pnpm verify pass locally (format, lint, typecheck, synth, tests, postgres-concurrency, cli-smoke, tier2-smoke, browser).
  • Updated tests: the infra stack test pins the new attributes; the stream API and wide event tests cover the remaining balancerCookie field.

The synthesized Hosts target group:

deregistration_delay.timeout_seconds  = 90
stickiness.enabled                    = true
stickiness.type                       = lb_cookie
stickiness.lb_cookie.duration_seconds = 86400

A read-only curl -s -D - -o /dev/null https://cloud.patchyhq.com/api/release shows the cause today: the response sets AWSALBAPP-0..3=_remove_; Path=/.

The ALB's routing can't be exercised locally. This rests on the synthesized template and AWS's documented duration-based stickiness. After the deploy, the refusal query in docs/OPERATIONS.md should show the stream_replaced misroutes stop, with balancerCookie = true on subscription POSTs.

Release impact

  • Breaking — requires action from anyone already running this
  • Not breaking — no action required

Only for a multi-replica deployment whose ingress keyed on patchy_stream_affinity: the server no longer sets it, so that ingress must switch to its own stickiness cookie on every path (for ALB, lb_cookie). This PR does that for production's stack. Single-replica setups and the local dev loop need nothing.

  • What does a revert leave behind? Browsers keep an AWSALB cookie, which app-cookie stickiness ignores. Deploying the older commit puts the target group back on app_cookie and the server sets patchy_stream_affinity again. No schema or data changes.
  • Does the release before it still work with that? Yes, with the misroutes this PR fixes.

Made by Claude Opus 5.5 via Claude Code; reviewed with GPT-6.1-Sol.

@github-actions github-actions Bot added area:server Touches the server area area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area area:docs Touches the docs area size:m 100-500 changed lines labels Oct 19, 2026
allisonmahmood and others added 2 commits October 19, 2026 22:20
The target group stuck on our patchy_stream_affinity application cookie,
scoped to /api/runtime. ALB app-cookie stickiness needs both that cookie
and its own Path=/ AWSALBAPP cookie, so every request outside
/api/runtime was round-robined and its response cleared stickiness. When
the frame's content request landed after the stream, the next
subscription POSTs alternated hosts and got stream_replaced.

The Hosts target group now uses duration-based stickiness (AWSALB, one
day), which the ALB sets on the page's own response. The server no
longer sets a routing cookie; the subscription request event keeps only
balancerCookie, keyed on the AWSALB name.

Closes #749

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Two tabs opened at once without a cookie, or a drain, can briefly put a
stream on another host than the cookie names; the next POST's 409
reconnects it. Say so in ADR-0010 and the runtime stream description.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@allisonmahmood
allisonmahmood force-pushed the fix/749-balancer-stickiness branch from d709286 to 4a1c706 Compare October 19, 2026 20:20
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Acceptance: PASS with notes

Checked 4a1c706c4a90ef3c17852ce7fcabb611e4e116f6 (base b5e43dbc4150803894cd2a664bdb6d2e1a7917e9) on fresh brightline scenario data, by GPT-6.1-Sol in T3 Code through the Codex harness. I did not write this change.

Done means

  • Diagnose before choosing the fix: passed. The measured-cause report is already on Subscription POSTs get 409 and the shell reconnects the stream #749; this diff addresses the cookie-path failure it describes.
  • Fix the routing configuration: passed, offline. The synthesized target group enables lb_cookie stickiness for 86400 seconds, retains the 90-second deregistration delay, contains no application-cookie attributes, and does not disable cross-zone balancing. The spike script matches. This is consistent with AWS's duration-based stickiness contract; live routing was not run below.
  • Keep the server and dev runtime working without their routing cookie: passed. The independent browser flow checked a successful SSE response without patchy_stream_affinity and verified that neither viewer's browser acquired it. Packed tier 2 smoke passed through both local dev mounts and the hosted runtime.
  • Preserve subscription diagnostics without cookie values: passed. The runtime event test checks balancerCookie: true with AWSALB, false without it, and distinguishes stale_sequence from stream_replaced, including documentConnected: false. It also asserts that cookie values are absent from recorded events. The wide-event schema tests passed.
  • Keep reconnecting cheaper and bounded: passed. Browser cases passed for one immediate current-generation reconnect, backing off during repeated misroutes, resetting after reconciliation, and preserving session, principal and rate-limit handling.
  • Align the docs: passed. The API source/generated docs, ADRs, Operations query and Analytics glossary reflect ingress-owned stickiness and the one-day setting.

Golden journeys

  • Use a tier 2 tool: passed. New Business opened with sample deals for Jordan and Allison. Jordan moved Saltwater Hotels from Lead to Discovery; Allison's already-open board updated without reloading. Jordan moved it back and Allison saw the reverse update. Spend refused Allison approving her own newly submitted request with “You can't approve your own request.”
  • Find and open a tool: passed. Jordan searched Home for Kudos and opened its frame.
  • Use a tier 1 tool live: passed. Jordan sent kudos and Priya's already-open wall received it without reloading.

The head-only pnpm dev film acceptance flow finished successfully in 19.7 seconds on a throwaway instance, which was taken down. Its assertions covered all three journeys and the missing server routing cookie. Sanitized result:

PASS: sample deals, two-viewer move and reverse move, self-approval refusal,
Home search, live Kudos, no server routing cookie

Independent local pnpm verify result:

PASS  format
PASS  lint
PASS  typecheck
PASS  synth
PASS  test                  193 files, 2004 tests
PASS  postgres-concurrency  3 files, 28 tests
PASS  cli-smoke
PASS  tier2-smoke
PASS  browser               80 tests
All passed.

All PR checks were green on the checked head, including live Clerk, the Node matrix and rollback-rehearsal. The latter has no migration change to rehearse here.

Rollback answers: They match the diff. The breaking classification correctly identifies existing multi-replica ingresses that depend on the removed server cookie. A revert restores the former ingress configuration and server cookie; leftover AWSALB cookies do not prevent the older release working. There are no schema or data changes, so a one-way label is not needed. The former routing defect would return.

Not run

  • Live ALB routing, concurrent first-open races, target drain/failover and the post-deploy misroute rate: the local environment has no ALB. These are judged from the synthesized template and diff, not claimed as observed. No production access or AWS API calls were made.

Notes

  • No failures in the checks run. The live-ALB gap is the reason for “with notes.”
  • Surface walk: runtime API/docs, CLI dev runtime, analytics vocabulary and infrastructure applied. No migrations, company-resource changes, rendered UI changes or package-layout changes applied. The reverse deal move was exercised.

@allisonmahmood
allisonmahmood merged commit f88ed4a into main Oct 19, 2026
14 checks passed
@allisonmahmood
allisonmahmood deleted the fix/749-balancer-stickiness branch October 19, 2026 20:50
allisonmahmood added a commit that referenced this pull request Oct 19, 2026
)

## What changed

A tier 2 tab that stayed open held its company's server task, and its
version's process, for as long as it was connected, whether anyone used
it or not. In production one forgotten tab kept a company's task running
for 36.5 hours, until a deploy ended it.

Now an open document holds the company task and keeps its version warm
only while its viewer is active. After `execution.document.idle` (a new
operating limit: 10 minutes by default, per company, overridable)
without activity, it lets both go. The screen and the stream stay: the
document stays ready, live updates still arrive, and its next call binds
the company on demand.

- **Activity** is the document's first stream, a change to its logical
desired set (subscription ids, operations and canonical args, ignoring
order, revisions and vectors), or an admitted `server.call` from its
viewer for that version on this host. Reauthentication reconnects,
reconciliation and re-runs for other people's writes don't count.
`Subscriptions.update` now says whether an admitted request changed the
logical set. It compares a generation's first set with the one the
previous generation left, so the `replace` the shell sends after every
reconnect only counts when it carries changes. Runtime tells the streams
about each admitted `server.call` through a new `called` option.
Activity lands on whichever generation of the document is connected when
it runs, so a reauthentication that replaces the stream in between
doesn't lose it; a document that disconnected meanwhile keeps none.
- **One warm-hold owner per document.** `RuntimeStream` keeps an
activity record per document across generations. The owner is one fiber
holding `ExecutionLifecycle.connect` and `ConnectedVersions.connect`
until the window passes or its generation ends. Expiry gives up
ownership in the same step that decides it, and finalizers only clear
their own owner. An old generation's expiry, acquisition or finalizer
therefore never touches its replacement's holds. Reactivation re-holds
in the background with `warm: false` and sends no frames; if it fails,
the next activity retries.
- **Reconnects and readiness.** An idle document's reconnect or resume
opens dispatch, sends `ready` and reconciles, without connecting or
warming. If the window outlasts a startup, the startup still ends in
`ready`, so held calls always settle through `ready`, `start_failed` or
closure. A document the host has no record of starts active.
- **Bounded records.** Disconnected records wait in a cache of 4096,
longest gone first, for at most an hour. Those defaults sit beside the
cache, and tests lower them through a `Context.Reference`. Connected
records are never evicted, and a record leaves the cache when it
reattaches.
- **Wide events.** The `keepalive` event gains `endReason` (`idle` or
`left`). A tier 2 stream event beside the fleet counts `idled` and
`reactivated`. Its `limits` carry `execution.document.idle` with the
window, its configuration revision and, as `peak`, the longest stretch
without activity.
- **Docs.** Updated ADR-0010's readiness contract, ADR-0012 › Fleet
controller and its idle-release decision, and OPERATIONS › Keeping open
versions warm, which gains a tuning query. Also updated: the
`execution.company.idle` description, the generated limits docs and
server-skill table, the runtime stream description with `docs/API.md`,
the analytics and runtime glossaries (a new **Active** entry) and
`docs/product.md`.

Closes #800

## Look at

**1. A visible tab lets go, and comes back on use.** This ran on the
local instance with a second, local-fleet host, an 8 s window and a 5 s
company idle. A real browser opened the starter tier 2 patch, left it
visible for 20 s, added a note and stayed another 15 s. Below is the
host's wide events, trimmed to the fields that matter, with seconds from
the open:

```
{"type":"request","at":"0.2","operations":["server.call","tables.list"],"handler":"notes.list"}
{"type":"keepalive","at":"0.2","dur":"8.0","endReason":"idle","peakDocuments":1,"touches":{"absent":1},"warmups":{"loaded":1}}
{"type":"binding","at":"0.1","dur":"13.7","releaseCause":"idle"}
{"type":"request","at":"20.3","operations":["server.call","tables.insert"],"handler":"notes.create"}
{"type":"keepalive","at":"20.3","dur":"8.2","endReason":"idle","peakDocuments":1,"touches":{"absent":1},"warmups":{}}
{"type":"binding","at":"20.3","dur":"13.4","releaseCause":"idle"}
{"type":"stream","at":"0.1","dur":"35.5","idled":2,"reactivated":1,"closeReason":"disconnected",
 "limits":[…,{"limitId":"execution.document.idle","value":8000,"peak":20103,…}]}
```

The company's task was released 13.7 s after the open while the tab was
still connected and visible. That is the window plus
`execution.company.idle`. The note bound a fresh task on demand, the
call made the document active again without a warmup, and the task was
released again once the tab went quiet.

**2. The browser test, red then green.** `starting.spec.ts` › *idle
documents* runs a real server and fleet, with an 8 s window and a 1 s
company idle.
- It checks that the visible tab's company is released.
- Then the tab is hidden, suspends and resumes, and a call held while
hidden must complete exactly once.
- From before that call, it watches Postgres for the company's activity
lock. Only an active document's hold takes that lock, never a call's own
admission, so seeing it shows the call reached the document's stream.
That doesn't depend on how fast the reply comes back.
- The company must then be released again once the document's window
passes, waited for with a deadline rather than a fixed sleep.

Each wiring point fails it on its own. With Runtime's call forwarding in
`RuntimeProduction.ts` removed, or with `Server.ts` back to merging
Runtime and the streams side by side:

```
Error: expect(received).toBe(expected)
Expected: true
Received: false      ← the company's lock never came back after the resumed call
```

With the window at 10 minutes, it fails at the first check, with no idle
release in 30 s. As committed it passes in 20 s, along with the rest of
the spec.

**3. Activity across a reconnect.** Two barrier tests construct a call's
activity, or hold an admitted set change before its activity lands, then
let reauthentication replace the generation. The replacement must take
the company back. Before activity was forwarded to the current
generation, both stalled waiting for that hold, and the replacement
stayed idle.

## How it was verified

- New TestClock tests in `RuntimeStream.test.ts` cover the following. An
active document holds both and lets both go after the window, the
keepalive saying idle. A non-empty set whose revisions and vectors
advance stays idle across 30 reconnects spanning two more windows. A set
change re-holds and a repeat doesn't. A call re-holds the caller's
connected documents, not a colleague's or a hidden one. Another viewer's
write reaches an idle document through an on-demand admission. An
unknown document starts active, and a startup the window outlasts ends
in `ready`. A barrier-controlled race covers expiry against reactivation
against generation replacement, with the old owner's lock finalizer
landing after the new owner took over. Two more cover a call's and a set
change's activity landing on the generation that replaced their document
meanwhile, and not on one that left. The cache tests evict the
longest-disconnected first, never a connected record, and never one that
reattached.
- `Subscriptions.test.ts` covers the logical set across order,
revisions, vectors, stale, repeated and buffered deltas, and across
generations. `ConnectedVersions.test.ts` covers `endReason`.
`InvocationAdmission.test.ts` checks that only an admitted call reaches
`called`. `Fleet.test.ts` now shows that an active holder alone, then an
admitted invocation alone, on another host prevents release.
- One locked `pnpm verify` passed on the review-fix commit: format,
lint, typecheck, synth, test (1,965 offline tests),
postgres-concurrency, cli-smoke, tier2-smoke and browser. The two later
commits only change tests: the activity tests wait for background holds
to settle, and the idle browser case watches for the company lock. `pnpm
check` and the full browser suite (81 tests) passed on the last one.
- Not checked here: multi-host behaviour beyond what sticky routing
gives (#798), since activity records aren't replicated. The production
window is a starting value to tune from the new stream fields.

## Release impact

- [ ] **Breaking** — requires action from anyone already running this
- [x] **Not breaking** — no action required. The stream wire and API
shapes are unchanged; documents just let go sooner.

- **What does a revert leave behind?** Nothing durable: activity lives
in each host's memory, and the new limit is a registry entry with a
default. If `PATCHY_LIMITS_JSON` names `execution.document.idle` by
then, take it out first, because an older release refuses an unknown
limit id at startup. A per-company override row for it is ignored.
- **Does the release before it still work with that?** Yes. Open
documents hold their company again for as long as they're connected.

Made by Claude Opus 5.5 via Claude Code; reviewed with GPT-6.1-Sol.

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
allisonmahmood added a commit that referenced this pull request Oct 19, 2026
…connection (#814)

Release 15's What's new entry, written from `9e4b0df`. It covers
everything merged since release 14's `through` (`7694bab`), and sets the
`patchy` release to `0.15.0` (`packages/patchy/package.json` and
`CURRENT_RELEASE`).

| Change | PRs |
| --- | --- |
| New: Your agent can read a tool's log | #786 |
| Fixed: Tools with server code keep one steady connection | #798 |
| Behind the scenes: an unused open tool lets its server rest | #802 |

#783 is release 14's own entry, so it's left out. #795, #796, #797,
#799, #803, #804, #806 and #807 are agent docs, CI and dev tooling, with
no line.

None of the PRs in the range are `one-way`; #786 and #798 predate the
rollback questions, and their diffs leave nothing an older release can't
run with (a new read-only route and CLI command, and the load balancer's
stickiness setting, which the older commit restores).

If this release misbehaves, roll back to `03891e4` (release 14).

Made by Claude Opus 5.5 via Claude Code.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area area:docs Touches the docs area area:server Touches the server area size:m 100-500 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Subscription POSTs get 409 and the shell reconnects the stream

1 participant