Skip to content

feat(memory): Rank automatic recall with a reranker - #2585

Merged
thomasjiangcy merged 2 commits into
mainfrom
feat/memory-recall-rerank-main
Nov 3, 2026
Merged

thomasjiangcy merged 2 commits into
mainfrom
feat/memory-recall-rerank-main

Conversation

@sentry-junior

@sentry-junior sentry-junior Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Automatic memory recall no longer calls an LLM to pick relevant memories. It sends the up-to-20 retrieval candidates to one reranker call. It keeps the candidates that score at least 0.55, puts the highest score first, and packs them into the existing 4,000-character prompt budget. The LLM call added a lot of latency and cost to every turn. In live calls, voyage/rerank-2.5-lite over 20 candidates took about 184 ms (p50) and 237 ms (p90) and cost about $0.000004–0.000009 per call.

Core. Plugins get a provider-neutral reranker on the userPrompt hook context (ctx.reranker.rerank({ query, documents })). It returns one score per document, in input order. It runs through AI Gateway the same way that embeddings do. The model comes from the new rerankingModelId / AI_RERANKING_MODEL setting, which defaults to voyage/rerank-2.5-lite. Each call gets a gen_ai.rerank span with the model, the document count, and the cost. The span does not include query or document text.

Cost. AI Gateway returns the billed cost in providerMetadata.gateway.cost as a decimal string. I checked this with live calls. The reranker returns that value as costUsd. Recall adds it to the embedding cost in the existing costUsd field of memories_recalled, where the selector's cost used to go. The event schema is unchanged.

Failure. If the rerank call throws, recall logs memory_recall_rerank_failed and the turn continues without recalled memories, as it did when the selector failed. There is no "no reranker" state. The host always supplies a reranker, and a blank AI_RERANKING_MODEL falls back to the default. A bad model ID makes the call fail, so recall fails closed in the same way.

Threshold. Voyage does not document score calibration, so I measured it on 2026-11-03 with live calls. I used 28 queries against 20 memories taken from the memory test and eval fixtures, plus 11 small-talk queries such as "thanks!", "lol" and "who are you?":

threshold relevant pairs kept off-topic pairs admitted small-talk queries given a memory
0.50 13 / 19 4 1 / 11
0.55 12 / 19 3 0 / 11
0.60 11 / 19 1 0 / 11

Clear matches scored 0.63–0.93. Indirect matches, such as "what time is it" with a remembered Pacific Time preference, scored 0.37–0.60. The highest small-talk score was 0.547. At 0.55, the timezone memory (0.598) is still admitted. The admitted off-topic pairs are near neighbors, for example "release notes" and "release runbooks". Voyage instruction prefixes compressed all scores without separating them better, so the query goes in as plain text. voyage/rerank-2.5 gave about the same separation at roughly 2.5× the cost. The numbers are recorded next to the constant. Retune the threshold if the model changes.

Telemetry. Plugins can now add numeric attributes to their plugin.hook span with ctx.setSpanAttributes. Keys must start with app.<plugin name>.. Core drops other keys and non-finite values, so a plugin cannot overwrite host attributes or attach text. When automatic recall reaches the reranker, it sets these on the plugin.hook userPrompt span (app.plugin.name:memory). They hold counts and scores only, never query or memory text:

  • app.memory.recall.candidate.count: retrieval candidates sent to the reranker
  • app.memory.recall.admitted.count: candidates that score at least 0.55
  • app.memory.recall.injected.count: memories that fit the 4,000-character prompt budget
  • app.memory.recall.score.max: the highest rerank score

gen_ai.rerank is a child span of the hook span, and it records the reranker latency. When the call fails, the span gets error.type with the provider SDK error class. The memory_recall_rerank_failed warning (plugin.log.warn) now also has error.type, which is the class of the error that recall caught. There is no message text in either. Before, that warning was the only record of retryable provider errors, and it had no error details.

Example queries (Sentry Explore, project junior):

# Recall hook latency
dataset=spans query='span.op:plugin.hook app.plugin.hook:userPrompt app.plugin.name:memory'
fields=p50(span.duration),p95(span.duration),count()

# Reranker latency
dataset=spans query='span.op:gen_ai.rerank'
fields=p50(span.duration),p95(span.duration),count()

# Admitted-is-0 rate: divide the first count by the second
dataset=spans query='span.op:plugin.hook app.plugin.name:memory app.memory.recall.admitted.count:0'
fields=count()
dataset=spans query='span.op:plugin.hook app.plugin.name:memory has:app.memory.recall.admitted.count'
fields=count()

# Distribution of admitted counts and score headroom
dataset=spans query='span.op:plugin.hook app.plugin.name:memory has:app.memory.recall.admitted.count'
fields=app.memory.recall.admitted.count,count(),p50(app.memory.recall.score.max)

The hook span covers embedding, retrieval, and reranking. TELEMETRY.md has a recipe that lists recall spans with these attributes.

selectRelevantMemories, MEMORY_RECALL_SYSTEM, and the selector-only schemas and prompt are deleted. createMemoryAgent stays for review, extraction, and deduplication.

Evals did not run in my sandbox, because their setup could not open a Quick Tunnel. The memory recall evals will need new recordings for the rerank call.

Open question. The calibration set is small. Indirect matches near the threshold (such as the timezone eval case) have little margin. A larger production sample would be a better basis to tune it later. The new recall attributes give that sample without query or memory text.

via @thomasjiangcy.

--

View Session [Sentry]

Replace the LLM relevance selector in automatic memory recall with one
reranker call over the retrieval candidates. Candidates that score at
least 0.55 are packed into the prompt budget, highest score first.

Core adds a provider-neutral plugin reranker on the userPrompt hook
context, backed by AI Gateway, with rerankingModelId / AI_RERANKING_MODEL
(default voyage/rerank-2.5-lite) and a gen_ai.rerank span.

Co-Authored-By: Thomas Jiang <[email protected]>
@vercel

vercel Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
junior-docs Ready Ready Preview Nov 3, 2026 5:50am UTC

Request Review

@github-actions github-actions Bot added the risk: high PR risk score: high label Nov 3, 2026
@github-actions

github-actions Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

5 screenshot changes — 5 changed · 0 added · 0 removed

Review screenshots in Frameshift

Automation Page · Desktop
Automation Page · Desktop
Changed
Conversation Share Details · Desktop
Conversation Share Details · Desktop
Changed
Conversation Sidebar Collapsed · Desktop
Conversation Sidebar Collapsed · Desktop
Changed
Location Detail · Desktop
Location Detail · Desktop
Changed
Settings Mcp · Desktop
Settings Mcp · Desktop
Changed

Plugins can now add numeric diagnostics in their own app.<plugin>.
namespace to the plugin.hook span through ctx.setSpanAttributes. Core
drops other keys and non-finite values, so plugins cannot overwrite host
attributes or attach text.

Automatic recall records the candidate, admitted, and injected counts and
the top rerank score when it reaches the reranker. The
memory_recall_rerank_failed warning now includes error.type.

Co-Authored-By: Thomas Jiang <[email protected]>
@thomasjiangcy
thomasjiangcy merged commit 55c00b7 into main Nov 3, 2026
47 checks passed
@thomasjiangcy
thomasjiangcy deleted the feat/memory-recall-rerank-main branch November 3, 2026 05:58
sentry-junior Bot added a commit that referenced this pull request Nov 4, 2026
A request with two asks scored the memory for one ask below the 0.55 recall
threshold. The handoff integration eval has failed since #2585 for this reason:
the reranker scored its gut-check memory 0.48 against the whole message and
0.86 against "Gut check" alone.

Co-Authored-By: David Cramer <[email protected]>
dcramer added a commit that referenced this pull request Nov 4, 2026
)

Every agent Turn now runs on one model at one reasoning level. The
default is `anthropic/claude-opus-5.5` at `high`. Set the model with
`createApp({ modelId })` or `AI_MODEL`. Set the reasoning level with
`AI_REASONING_LEVEL`.

## Removed

- The `handoff` tool and `agent/handoff.ts`, with handoff compaction
(`compactContextForHandoff`, the `handoff` compaction mode, and the
`profile_changed` discard).
- The Turn router (`services/turn-router.ts`), its prompt blocks, and
the router attachment previews in `prompt.ts`.
- Model profiles: `model-profile.ts`, `createApp({ profiles,
defaultProfile })`, `AI_HANDOFF_MODEL`, `AI_MODEL_PROFILES`, and the
`spawnAgent` `profile` input.
- The router eval suite (`evals/router/`, `evals-router.yml`, the router
harness and config, `evals:router`) and
`evals/integration/coding/handoff.eval.ts`.
- `openspec/changes/model-handoff`.
- Dashboard rendering of handoff and Turn route rows, and profile and
reasoning fields on event models.

The fast, Guardian, reranker, vision, and web search models are
unchanged. `spawnAgent` keeps its `reasoning_level` input.

## Rollout and data

- Stored `handoff` and `turn_routed` rows stay readable. Replay applies
a legacy handoff's replacement history and skips routing rows, so
checkpoints still resume. The report API and dashboard skip both types.
New writes of either type are rejected.
- Auxiliary costs still count the router cost on old `turn_routed` rows.
- A resumed Turn ignores its stored route and uses the configured model.
- No schema change. `junior_agent_invocations.model_profile` stays in
the schema but code no longer reads or writes it. It is nullable with no
default, so new rows leave it NULL and old pods can still write it
during the rolling deploy. A follow-up PR drops the column after this
ships.

## Prod cost and latency

No change. Prod has run one `default` profile (Opus 5.5, `high`) with no
Turn router since getsentry/junior-prod#589. This PR makes that the only
path.

## junior-prod follow-ups when this ships

- `server.ts`: replace the #589 block (`defaultProfile: "default"` and
`profiles.default = { modelId: "anthropic/claude-opus-5.5",
reasoningLevel: "high" }`) with `modelId: "anthropic/claude-opus-5.5"`,
or drop it to use the default. `JuniorAppOptions` no longer has
`profiles` or `defaultProfile`, so typecheck fails until this changes.
- Check the Vercel env for `AI_MODEL`, `AI_REASONING_LEVEL`,
`AI_HANDOFF_MODEL`, and `AI_MODEL_PROFILES`. `AI_MODEL` now sets the
agent model when `createApp` omits `modelId`. Remove the two handoff and
profile variables.
- `app/skills/self-improve/SKILL.md` line 73 tells the agent to use
`handoff`. Remove that sentence.

## Known gap

The #2585 memory recall gap still exists. `handoff.eval.ts` was its only
eval, so this PR removes that coverage. Thomas owns the fix.

## Checks

- `pnpm typecheck` (junior, dashboard, evals), `pnpm lint` (includes
file length, test architecture, and migration metadata), and `pnpm
skills:check` pass.
- Dashboard vitest passes. `@sentry/junior` vitest: 3126 passed; only
`attachment-s3-storage.test.ts` fails here because the sandbox has no
local S3 endpoint (file untouched). Dashboard e2e and evals run in CI
only (no Chrome or gateway key in the sandbox).

<!-- junior-request-attribution:start -->
via @dcramer.
<!-- junior-request-attribution:end -->

<!-- junior-session-footer:start -->
<!-- junior-conversation-id:agent%3A74577fa5163472d173bf2a0bdfe8e39b -->

--

[View
Session](https://junior-prod.sentry.dev/conversations/agent%3A74577fa5163472d173bf2a0bdfe8e39b)
[[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3A74577fa5163472d173bf2a0bdfe8e39b/?project=4510944073809921)

<!-- junior-session-footer:end -->

---------

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: David Cramer <[email protected]>

This branch was successfully deployed

1 active deployment
Preview – junior-docs — 09096556 Deployed Nov 3, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk: high PR risk score: high

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant