Skip to content

Share optimizer embeddings across sessions and replicas - #7008

Merged
ChrisJBurns merged 10 commits into
stacklok:mainfrom
aron-muon:vmcp-shared-embeddings
Nov 25, 2026
Merged

ChrisJBurns merged 10 commits into
stacklok:mainfrom
aron-muon:vmcp-shared-embeddings

Conversation

@aron-muon

@aron-muon aron-muon commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The optimizer embeds a tool only when no stored vector matches its content key (#5847). That reuse sees only rows already committed in the same process, so two cases still embed one catalogue several times:

  • Builds that start together on a cold store, as the first sessions after a rollout do, all miss and all embed the full catalogue.
  • Each replica has its own in-memory store, so every replica embeds the catalogue again after each restart.

Measured on a two-replica vMCP serving about 400 tools through TEI, the first session after a rollout took 52 s to set up. initialize (26 s) and tools/list (25 s) landed on different replicas, each building its own index. A client-abandoned initialize kept embedding at the same time, so identical batches reached TEI two or three times and queued behind each other: single batches took up to 14 s against 1 to 3 s uncontended. Aggregation took about 3 s, and warm reconnects take 0.3 to 2 s.

What changed:

  • One embedding turn per store, with any session storage. A build that needs new vectors waits up to 30 s for the turn, looks again, and reuses whatever the build before it committed, so concurrent cold builds of one catalogue embed it once. Builds whose tools are all stored never wait. A build that times out embeds without the turn, so a hung embedding backend delays the others by 30 s at most.
  • Vectors shared across replicas. With Redis session storage, the optimizer also writes vectors to that Redis under the session key prefix, with a fixed 7-day TTL. A replica reads Redis for the vectors it lacks before embedding them. Only vectors embedded under a verified model identity are published. A build reads Redis at most once, before it waits for the turn, and writes at most once, after it commits, so no build calls Redis while it holds the turn.
  • Failures cost reuse only. Shared values pass the same checks as local rows (non-empty, whole float32s, current width), and a lookup reads at most 64 KiB of a value. Semantic search skips a NaN distance, which only a replaced vector can produce. A Redis error after startup is logged at WARN and the build embeds locally.
  • Embedding keys do not answer as sessions. Redis session storage reports a value that is not session metadata as ErrUndecodableSessionData, and the vMCP ownership lookup answers a session ID that names one with the same 404 as a missing session.

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Dependency update
  • Documentation
  • Other (describe):

Test plan

  • Unit tests (task test)
  • E2E tests (task test-e2e)
  • Linting (task lint-fix)
  • Manual testing (describe below)

task test passes for every vMCP, optimizer and session package. Three tests fail on my machine with or without this change, the same three on a fresh checkout of main: TestDetectProjectRoot (pkg/client), TestResolve (pkg/skills/identitytoken) and TestTransparentProxy_HealthCheckFailureWithNilCallback (pkg/transport/proxy/transparent). task lint is clean, and task gen and task docs leave the tree unchanged.

New tests cover cold concurrent builds, the bounded turn wait and a caller that gives up while waiting, a slow publish that must not hold the turn, the look after the turn staying off Redis, cross-replica reuse, unverified vectors staying local, unusable and oversized shared values, NaN and Inf vectors in search, a failing Redis, turn release after a failed build, a session ID naming an embedding key, the factory option checks, the factory publishing through a stub TEI, and the Serve wiring.

Changes

File Change
pkg/vmcp/optimizer/internal/toolstore/embedding_cache.go EmbeddingCache and its Redis implementation, with capped reads
pkg/vmcp/optimizer/internal/toolstore/sqlite_store.go Bounded embedding turn, shared lookup before the turn, publish after commit, NaN guard, WithEmbeddingCache
pkg/vmcp/optimizer/optimizer.go WithSharedEmbeddings factory option
pkg/vmcp/server/sessionmanager/factory.go, session_manager.go FactoryConfig.OptimizerOptions, rejected where nothing would use them; LookupOwner answers non-session keys as missing
pkg/transport/session/session_data_storage_redis.go ErrUndecodableSessionData
pkg/vmcp/server/serve_optimizer.go, serve.go Enable sharing when session storage is Redis
pkg/vmcp/server/server.go Extract sessionRedisConfig from buildSessionDataStorage, unchanged
docs/arch/13-vmcp-scalability.md Optimizer embeddings section, Redis connections, limits table

Does this introduce a user-facing change?

Yes, for a vMCP that runs the optimizer with an embedding service.

With any session storage:

  • Before: concurrent builds on a cold replica each embedded the full catalogue.
  • After: they take turns, so the catalogue is embedded once. A build waits at most 30 s for its turn. A session with one new tool can wait that long behind a build that is embedding a whole catalogue.

With Redis session storage as well:

  • Before: each replica embedded the full catalogue on its first sessions after every restart, and Redis held only session data.
  • After: Redis also holds <keyPrefix>optimizer:embedding:<sha256> keys. Each is a raw float32 vector with a fixed 7-day TTL, about 1.7 KB at 384 dimensions including key and overhead. Each pod opens one more Redis client for them, mostly idle. A vMCP that cannot connect that client fails at startup, right after its session storage connected to the same Redis. A request whose Mcp-Session-Id names one of these keys gets 404, as for any unknown session.

There is no CRD or config change.

Implementation plan

Approved implementation plan
  1. Add a per-store semaphore. A build with misses waits for it up to a bound, re-reads the local store, and holds it until its rows commit, so a waiter's re-check sees them. On timeout the build embeds without it.
  2. Add an EmbeddingCache interface with a Redis implementation. Pipeline single-key reads and SETs so Redis Cluster works, with a TTL on every key and a cap on bytes read.
  3. Look up local rows first, then the shared cache for the rest, before the turn. Publish only verified fresh vectors, after the commit and outside the turn. Treat shared errors as misses.
  4. Thread a typed factory option through sessionmanager.FactoryConfig. Serve sets it from the session-storage Redis config, so no new config surface is needed.
  5. Answer session IDs that name non-session keys as missing sessions.
  6. Document key layout, sizing, eviction, failure behavior and the trust model.

Special notes for reviewers

  • Evidence for the optimization. The numbers above come from production traces. Anti-pattern 9 asks for that, and anti-pattern 8 is why sharing reuses session storage rather than adding config.
  • The 30 s turn wait. A cold embed of a few hundred tools on CPU TEI takes about that long, so waiters usually find the holder's rows instead of joining it on the backend. With a hung TEI a waiter spends at most 30 s before calling TEI itself, instead of waiting out one request timeout per build ahead of it.
  • Trust. Anyone who can write the keyspace can replace vectors and so change find_tool ranking. Results are still limited to the caller's tools, and call_tool is still admission-checked. A replaced vector a replica already read stays in its local store until the tool text or model changes or the pod restarts. The scalability doc puts this next to the existing Redis access-control guidance. Keys sit under the session key prefix, so an ACL scoped to that prefix keeps working.
  • Not coordinated across replicas. Two replicas that miss the same vectors at the same moment both embed them. A distributed lock would close that, but the leftover duplication is bounded by the replica count and happens once per catalogue change, so I left it out.
  • Separate Redis client. The session storage type does not expose its client, and sharing one would tie the two shutdown orders together.
  • Modern requests never read Mcp-Session-Id into session storage: classifyingHandler and dispatchModern call the core with the caller's identity only, so the non-session-key fix concerns the Legacy ownership lookup.
  • Size. 547 added lines of non-test Go, 164 of them comments.

🤖 Generated with Claude Code

The optimizer reuses a stored vector only when it is already committed in
the same process. Builds that start together on a cold store, as the first
sessions after a rollout do, each embed the full catalogue, and every
replica embeds it again after each restart. On a two-replica vMCP with
about 400 tools, the first session after a rollout took 52 seconds to set
up, mostly duplicate embedding batches queued behind each other.

Builds that need new vectors now take turns on a store: one that waited
looks again and reuses what the build before it committed. With Redis
session storage, vectors embedded under a verified model identity are also
written to that Redis under the session key prefix with a 7-day TTL, and a
replica reads them before embedding. A Redis error after startup is logged
and costs only reuse.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aron <[email protected]>
@aron-muon

Copy link
Copy Markdown
Contributor Author

The one failing test is TestMiddlewareFunc_HopByHopHeadersExcludedFromSignature in pkg/auth/awssts (502 instead of 200). That package does not import anything this PR changes, and the test passes on repeated local runs. Could a maintainer rerun the job?

@aron-muon

Copy link
Copy Markdown
Contributor Author

More production data from today, on the same two-replica vMCP right after a rollout restarted both pods:

  • One client fired several tool calls in parallel. Three of its requests landed on the replica that had not built its index yet, and each started its own full-catalogue build within the same 100 ms.
  • The embedding batches those builds sent to TEI slowed from about 2 s to 35 s each as they queued behind one another.
  • Two call_tool requests waited 180 s, the configured embedding timeout, before failing. The client had already given up at its 60 s request timeout.
  • Once the index existed, the same tool calls took 54 ms to 2.7 s.

With this PR, the three builds would take turns and the second and third would reuse the first one's rows. The second replica would also read the vectors the first replica had already published, instead of embedding the catalogue at all.

@codecov

codecov Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.30769% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.06%. Comparing base (0facc72) to head (ea2f377).

Files with missing lines Patch % Lines
.../vmcp/optimizer/internal/toolstore/sqlite_store.go 91.17% 9 Missing ⚠️
pkg/vmcp/optimizer/optimizer.go 80.95% 4 Missing ⚠️
...cp/optimizer/internal/toolstore/embedding_cache.go 96.29% 1 Missing ⚠️
pkg/vmcp/server/serve.go 75.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7008      +/-   ##
==========================================
- Coverage   82.09%   82.06%   -0.03%     
==========================================
  Files         927      928       +1     
  Lines       93959    94109     +150     
==========================================
+ Hits        77132    77235     +103     
- Misses      16822    16869      +47     
  Partials        5        5              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@jhrozek jhrozek left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for this, the trace numbers in the description make the case well and the reuse logic is careful.

Two things I'd like to see before merge, both small: bounding the turn wait (sqlite_store.go:401) and keeping the Redis calls out of the turn (sqlite_store.go:353). The session keyspace one (embedding_cache.go:50) is cheap to close now, before the key layout is out in real Redis instances. The rest are docs and nits.

One thing outside the diff: the comment at serve_optimizer.go:95 still says a rebuild costs an embedding round-trip per tool, which hasn't been true since #5847.

CI is green after re-running a flaky awssts test.

Comment thread docs/arch/13-vmcp-scalability.md Resolved
Comment thread docs/arch/13-vmcp-scalability.md Resolved
Comment thread docs/arch/13-vmcp-scalability.md Resolved
Comment thread docs/arch/13-vmcp-scalability.md Resolved
@jhrozek

jhrozek commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

Sorry it took us so long to get to this one, and thanks for your patience. The review above should give you something concrete to work with, and I'm happy to talk through any of it if something doesn't make sense or you see it differently.

aron-muon and others added 9 commits November 25, 2026 18:20
Serve now assembles the Server before the vMCP session manager so the
cache sweep can drop health-resync registrations. The shared-embeddings
config is resolved right before sessionmanager.New on that new path.

Signed-off-by: Aron Gates <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
A build that needs new vectors waited for the embedding turn with no
bound but its own context, which has no deadline on the Serve path. With
a hung embedding backend each holder spent the full request timeout
before handing over, so the last of N cold builds failed after about N
timeouts instead of one.

A build now waits at most 30 seconds for the turn and then embeds without
it, as every build did before the turn existed. It tries once per build.

Signed-off-by: Aron Gates <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
A build published its vectors to the shared cache while it still held the
embedding turn, and read the cache again after taking the turn. A slow
Redis, rather than a down one, then held up every other cold build on
the replica for the Redis timeouts.

The vectors are now published after the rows commit and the turn is given
back, so a build whose commit fails publishes nothing. The look after the
turn reads only the local store, which is where the previous holder's
rows are. A build now calls Redis at most twice, never under the turn.

Signed-off-by: Aron Gates <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The shared optimizer embeddings live under the session key prefix, so an
ACL scoped to that prefix keeps covering them. A client could name one
as its Mcp-Session-Id: the ownership lookup read the vector, failed to
decode it, and answered 503 with a WARN. Any authenticated caller could
raise WARNs at request rate and tell which keys exist.

Redis session storage now marks a value that is not session metadata
with ErrUndecodableSessionData, and the vMCP ownership lookup answers it
as a missing session: the same 404, logged at DEBUG. Load and Terminate
share the decoder and keep treating it as an error.

Signed-off-by: Aron Gates <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
A stored vector with NaN or Inf components, which only a replaced shared
value can carry, gives a NaN cosine distance. NaN compares false against
the distance threshold, so the tool matched every query and the sort got
an inconsistent comparator. Semantic search now skips such a distance.

Signed-off-by: Aron Gates <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
A plain GET pulled a shared value into the replica whatever its size, so
a planted 100 MB value reached every replica before the width check
rejected it. Lookups now use GETRANGE and read at most 64 KiB plus one
byte, which is enough to reject anything longer. GETRANGE reads an
absent key as empty, so empty values count as absent.

The connect error is no longer wrapped twice on its way to the caller.

Signed-off-by: Aron Gates <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
FactoryConfig.OptimizerOptions reach only an optimizer built from
OptimizerConfig. Set together with a pre-built OptimizerFactory, or with
no optimizer, they were silently dropped. New now rejects both, as it
already rejects an optimizer without AdvertiseFromCore.

Signed-off-by: Aron Gates <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The factory test only checked that the shared cache connected, so it
passed even if the store never got the cache. It now builds an optimizer
against a stub TEI that reports a model id and checks that each tool's
vector lands in Redis under the session prefix.

Signed-off-by: Aron Gates <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The scalability doc said the shared embedding TTL counts from the last
write, which reads like a sliding window, and sized each vector by its
value alone. It now states the fixed 7-day TTL, per-key overhead, the
width rule, which settings split the keyspace, the eviction behavior,
the connection count next to rate limiting, the bounded turn wait, and
that a replaced vector a replica already read stays in use there.

The Serve comment that a rebuild costs an embedding round-trip per tool
predates embedding reuse and now says what a rebuild embeds.

Signed-off-by: Aron Gates <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@aron-muon

Copy link
Copy Markdown
Contributor Author

Sorry for the slow turnaround on this one. I merged main in (33c1d60). The one real conflict was Serve now building the Server before the session manager, so the shared-embeddings config now resolves right before sessionmanager.New.

Each review point has its own commit and a reply on its thread. The serve_optimizer.go comment you flagged outside the diff now says a rebuild embeds only the tools whose text or model changed (ea2f377). The description covers the bounded turn and says the turn applies with memory session storage too. Thanks for re-running the awssts job.

@ChrisJBurns
ChrisJBurns merged commit e7570b0 into stacklok:main Nov 25, 2026
69 of 70 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants