Skip to content

Fix: Default session.client_affinity to on - #1204

Merged
huang195 merged 2 commits into
rossoctl:mainfrom
huang195:fix/client-affinity-default
Oct 1, 2026
Merged

huang195 merged 2 commits into
rossoctl:mainfrom
huang195:fix/client-affinity-default

Conversation

@huang195

@huang195 huang195 commented Oct 1, 2026 •

Copy link
Copy Markdown
Member

Problem

session.client_affinity was off unless the config turned it on, and only the --local built-in config did. That file is written once (install.sh writes it only when it is missing) and never regenerated. So every laptop installed before the key existed still files header-less requests under whichever session spoke last. docs/laptop-service.md told those users to add the line themselves.

Seen on a laptop running Claude Code and Bob Shell side by side: Bob's startup probes (/admin/v1/profile, /inference/v1/model/info) and both task-classifier completions were filed inside the Claude Code session. Those completions are real inference priced in Bob's unit, so the Claude session's cost column read (mixed). The installed config had no session: block.

The cost ledger had the same problem with its own default (see the comment at cmd/authbridge-proxy/main.go:581): a default that only the template supplies never reaches an installed laptop.

Fix

  • SessionConfig.ClientAffinity becomes a *bool, read through a new ClientAffinityEnabled(). Unset means on, the same shape as session.enabled.
  • An explicit client_affinity: false still turns it off. A live edit to it is still refused by the reloader as needing a restart, since session.* is compared whole.
  • Both mains that wire the forward proxy (authbridge-proxy, authbridge-cpex) read the accessor.
  • docs/laptop-service.md and the --local template comment now describe the new default.

In-cluster resolution is unchanged. With affinity on, traffic from no known coding agent falls through to ActiveSession() exactly as before. TestClientAffinity_InClusterResolutionIsUnchanged runs those cases with the knob on. id_headers: [], the documented setting wherever attribution is a trust boundary, still disables affinity along with header bucketing.

Before / after

Real-binary smoke test: an isolated proxy started from a config with no session: block, receiving Claude- and Bob-shaped requests (User-Agents and headers copied from the laptop) in the order observed:

BEFORE (main afb60cdd)
  [BOB-T]    bob-shell /inference/v1/chat/completions
  [CLAUDE-S] claude /v1/messages, bob-shell /admin/v1/profile, bob-shell /inference/v1/model/info,
             bob-shell /inference/v1/chat/completions, claude /v1/messages
AFTER (this branch)
  [BOB-T]    bob-shell /admin/v1/profile, bob-shell /inference/v1/model/info,
             bob-shell /inference/v1/chat/completions, bob-shell /inference/v1/chat/completions
  [CLAUDE-S] claude /v1/messages, claude /v1/messages

The pre-header calls wait in pending:bob-shell, and Bob's first X-Task-Id request moves them into its session.

Not fixed here (#1187)

CONNECT rows are not addressed. They usually carry no User-Agent, so affinity cannot tell whose they are, and they still go to the session that spoke last, in both directions. A replay of the same laptop session through the TLS bridge with affinity on still files 3 Bob CONNECTs under Claude and 3 Claude CONNECTs under Bob. #1187 covers that.

This change is still a prerequisite for #1187: its per-process attribution is planned as a re-keying of affinity, which would otherwise never run on an existing install.

Testing

  • TestSessionConfig_ClientAffinity: no session block, empty block, block without the key, explicit true all mean on; explicit false means off. The unset cases were seen failing before the default changed.
  • TestLoad_PreAffinityLaptopConfigGetsClientAffinity: a pre-affinity laptop config, run through Load, comes back with affinity on. Seen failing first.
  • TestReloader_RefusesSessionChange: new client_affinity false case. Under the old plain bool, false was indistinguishable from unset, so this case could not be written.
  • core: go vet is clean and all packages pass. cmd/authbridge-proxy and cmd/authbridge-envoy vet and build with GOWORK=off, and the proxy's tests pass. cmd/authbridge-cpex vets with -tags cpex. cmd/abctl builds. gofmt -l is clean on every touched path.

Also: unflake Go CI (README demo)

The second commit fixes the red TestCommittedAssetIsCurrent on this PR. This PR didn't cause it: the same failure reproduces on clean main with TZ=UTC on the 1st of the month. The demo fixture is laid out relative to the wall clock and places one turn per session 26 hours back. On the 1st, and early on the 2nd, that turn falls into the previous month, so THIS MONTH drops and the committed SVG reads as stale. A rerun can't clear it.

The demo now runs its whole stack on one shifted clock anchored mid-month at midday: session store, session API, usage aggregator, ledger and the TUI's UPDATED column. session, sessionapi and tui each gain an additive WithClock option; nil means time.Now, so production behaviour doesn't change.

To verify, run TZ=UTC go -C scripts/readme-demo test -run TestCommittedAssetIsCurrent ./... on the 1st of a month (red on main, green here). To check that each clock hookup matters, remove it from scripts/readme-demo/tuicapture.go and rerun. Removing the ledger's hookup changes nothing in the output; the commit message explains why it stays.

Assisted-By: Claude (Anthropic AI) [email protected]

Summary by CodeRabbit

  • New Features
    • Client affinity is now enabled by default, including for existing configurations that omit the setting. Set session.client_affinity: false to disable it and restore timing-based attribution. Changing this setting requires a restart.
    • Requests without session headers are attributed by agent rather than by session when client affinity is enabled.
  • Documentation
    • Updated the session-attribution guidance to explain how header-less requests are attributed and clarify the default behavior, opt-out setting, and restart requirement.

Client affinity was off unless the config said otherwise, and only the
--local built-in config said otherwise. That file is written once and
never regenerated, so a laptop installed before the key existed still
files every header-less request under whichever session spoke last.
Observed: Bob Shell's startup probes and task-classifier completions,
priced in Bobcoins, landed inside a concurrent Claude Code session,
whose cost column then read "(mixed)".

ClientAffinity becomes a *bool read through ClientAffinityEnabled(),
nil meaning on, the same shape as session.enabled. An explicit
`client_affinity: false` still turns it off, and a live edit to it is
still refused by the reloader as needing a restart.

In-cluster resolution is unchanged with affinity on: traffic from no
known coding agent falls through to ActiveSession() exactly as before
(TestClientAffinity_InClusterResolutionIsUnchanged), and
`id_headers: []` still disables it along with header bucketing.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
@coderabbitai

coderabbitai Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: 078631f8-c9d2-48d3-991a-88231283d82d

📥 Commits

Reviewing files that changed from the base of the PR and between 4f49070 and d8a01cc.

📒 Files selected for processing (7)
  • cmd/abctl/tui/app.go
  • cmd/abctl/tui/sessions_pane.go
  • core/session/affinity.go
  • core/session/store.go
  • core/sessionapi/server.go
  • core/sessionapi/usage.go
  • scripts/readme-demo/tuicapture.go

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

Client affinity now defaults to enabled when its configuration value is unset. Proxy entry points use the effective setting. Session, API, and TUI components can use configurable clocks, and the README demo supplies a shared clock to its components.

Changes

Client affinity configuration and integration

Layer / File(s) Summary
Define and validate the default
core/config/config.go, core/config/config_test.go, core/reloader/reloader_test.go
ClientAffinity distinguishes an unset value from explicit false. ClientAffinityEnabled() returns true when the value is unset. Tests cover configuration loading and reload behavior.
Use the effective setting
cmd/authbridge-cpex/main.go, cmd/authbridge-proxy/main.go, cmd/authbridge-proxy/local.go, cmd/authbridge-proxy/local_test.go, docs/laptop-service.md
Both proxy entry points use ClientAffinityEnabled(). Built-in configuration comments, a proxy test, and the laptop service documentation describe the default and opt-out.

Configurable clocks

Layer / File(s) Summary
Add configurable clocks to session, API, and TUI components
core/session/store.go, core/session/affinity.go, core/sessionapi/server.go, core/sessionapi/usage.go, cmd/abctl/tui/app.go, cmd/abctl/tui/sessions_pane.go
Session storage, session selection, usage-window parsing, and TUI session rendering use configurable clocks. The session store, session API, and TUI provide clock options with real-time fallbacks.
Pass a shared clock through the README demo
scripts/readme-demo/tuicapture.go
The demo creates a clock relative to a fixed local-time anchor and passes it to its ledger, session store, usage aggregator, session API, and TUI. Fixture event timestamps use the same clock.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Suggested reviewers: pdettori

Merge Risk: ⚪ Minimal · up to d8a01

No actionable merge-blocking issue is established. Client affinity now defaults on while preserving explicit opt-out; the demo shares a configured clock across its components. Merge after normal checks pass.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to d8a01

Default-enabled agent attribution broadens exposure to an existing lifecycle gap: after a conversation is removed and its identifier reused, later events and costs can be attributed to the wrong conversation. Explicit opt-out remains available, but applying it requires a restart.

Retained concerns

  • Medium · reliability · inferred: Default-enabled affinity broadens exposure to adoption redirects that survive session deletion. After a pending bucket is adopted, expiry cleanup or capacity eviction removes its target session and owner but leaves the redirect. If that identifier is recreated before another pending append, the redirect sends the event into the new incarnation without checking ownership. This can mix conversation histories and cost attribution, and make recorded state diverge from the session identity supplied to plugins. The lifecycle defect predates this PR; its activation for previously unset configurations is the relevant change. Redirect removal when the target is absent protects only the ordering where the pending append arrives before recreation.
Security review details

Security Blast Radius

  • inferred — Potential attribution contamination is bounded by the shared in-process session state of a proxy instance. For a shared or standalone proxy, that can encompass all clients reaching that instance; sidecar exposure follows the workload boundary. Actual deployed reachability and tenant separation were not supplied.

Security Findings and Attack Paths

  • inferred — A reachable lifecycle sequence is pending adoption, target cleanup or eviction, target identifier recreation, and a subsequent pending append. The surviving redirect accepts the recreated target solely because it exists, allowing old pending traffic to enter the new conversation's history and accounting. This sequence does not establish privilege escalation, but compromises provenance of state that plugins can later consume.

Trust Boundaries and Controls

  • observed — Explicit false disables affinity; an empty id_headers list disables both header selection and affinity. Explicit headers retain precedence, and first claim wins ownership while the session exists. These controls limit the new selection behavior but do not authenticate sessions or replace the remaining global active-session fallback with tenant isolation.

Resilience and Maintainability Implications

  • observed — Adoption, append, and cleanup are serialized by the store mutex, and a redirect is removed when its destination is absent. These safeguards prevent concurrent partial mutations and handle some cleanup orderings, but neither invalidates a redirect across deletion followed by identifier reuse.

Hardening Proposals

  • proposed — Bind adoption redirects to the target session incarnation, or invalidate inbound redirects atomically when their destination is removed, so pending traffic cannot cross a deletion-and-recreation boundary.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 87.50% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 16 functions across 14 files.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the primary change: enabling session.client_affinity by default.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pdettori pdettori left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed and verified.

  • All ClientAffinity consumers audited: both proxy mains now read through the new accessor; the forwardproxy server keeps its plain bool, which is correct since it's set once at wiring time.
  • The reloader's reflect.DeepEqual on session.* (reloader.go:422) handles the *bool nil↔present distinction, and the new client_affinity false refusal test pins it.
  • Ran core/config, core/reloader, cmd/authbridge-proxy, and core/listener/forwardproxy test suites on the PR head locally — all pass.
  • The failing Go CI (README demo) / TestCommittedAssetIsCurrent check is a flake: the demo feeds synthetic events directly into the session store (tuicapture.go), bypassing the forward proxy, so the affinity default cannot change the SVG. The test passes locally on this branch. Worth a re-run.

The *bool mirroring session.enabled is the right shape — a template-supplied default never reaches installs written before the key existed, and explicit false keeps the off switch.

Comment thread docs/laptop-service.md
`session.client_affinity: true` files a header-less request under the newest session of
the same agent (by `User-Agent`). An agent's calls before its first header wait in a
- **Header-less requests are attributed by agent, not by session.** MCP tool calls,
Claude Code's WebFetch, and Bob's startup probes and task-classifier completions carry

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: The new heading says requests are "attributed by agent, not by session", but the next sentence describes the old timing behavior as though it were current. Since affinity is now the default, consider "attributed by agent, not by timing" — or keep the timing sentence but open it with "Before affinity" / "Without it" so the paragraph doesn't read as asserting two contradictory defaults at once.

TestCommittedAssetIsCurrent failed on every run on the 1st of the month
and early on the 2nd, and in the first minutes of each UTC day. The
fixture is laid out relative to the wall clock: one turn per session
sits 26 hours back, so that 7 DAYS and THIS MONTH exceed TODAY. On the
1st that turn lands in the previous month, THIS MONTH drops from $0.79
to $0.65, and the committed asset reads as stale. A rerun cannot clear
it. Reproduced on clean main with TZ=UTC on Oct 1, while the same tree
passed in local EDT, where it was still Sep 30.

The demo now builds a single clock: real time shifted to start at noon
on Sep 15, local time. The ledger, the usage aggregator, the session
store, the session API and the TUI's UPDATED column all read it, so the
output no longer depends on the date or the zone the generator runs in.

Four of the five are load-bearing. Removing the clock from the
aggregator, the session API or the TUI each turns the test red under
TZ=UTC on Oct 1. With only the ledger and aggregator shifted, the
session store still stamped UpdatedAt from the real clock: every row
rendered "just now" (a negative age) and the usage chart's bars moved.
The ledger's clock is not observable in the output, even with the
anchor 21 months back, because it is queried with explicit bounds from
the clocked session API. It stays wired so that no component of the
stack reads a different clock. The anchor is five seconds past the minute because the newest
turn sits on the minute boundary, and an anchor exactly on it renders
"just now", which the masking does not rewrite.

session, sessionapi and tui each gain an additive WithClock option. nil
means time.Now, so no production caller changes.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
@huang195
huang195 merged commit c990c43 into rossoctl:main Oct 1, 2026
28 checks passed
@huang195
huang195 deleted the fix/client-affinity-default branch October 1, 2026 02:36
huang195 added a commit to huang195/kagenti-extensions that referenced this pull request Oct 1, 2026
There is no abctl alias, so an abctl left in ~/.local/bin would keep
managing the same launchd/systemd unit as agentop while disagreeing about
which build wrote it. install.sh and make dev-install now delete it — but
only when the file is ours, judged by the module path Go embeds rather than
by running it: that works on stripped release builds (v0.7.0's carries the
path several hundred times) and never executes someone else's tool that
happens to share the name. install_test.sh covers both release layouts, a
foreign abctl whose --version would have fooled a version check, and that
none of them is run.

Also:
- regenerates docs/assets/cortex-demo.svg: the 9 frames that show the
  title bar or the install line, each two cells wider. The usage frame's
  chart also changes: it is the first regeneration since rossoctl#1204 pinned the
  demo's clock, and the committed chart predates that (the staleness test
  elides the frame, which is why it never went red);
- adds a release-notes line saying abctl is now agentop;
- records the rename in CLAUDE.md's naming rules.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants