Repository navigation
Description
Redis chat/runtime records have nested shapes and multi-day TTLs, so schema changes hang around after deploy. SQL remains the durable history authority. Redis should only hold bounded operational state that is safe to expire. OAuth tokens/sessions are out of scope.
Goals
- Redis schema changes must not require multi-day compatibility code.
- Durable conversation history and metadata have one authority in SQL.
- Redis holds only bounded operational state that is safe to expire.
- Terminal state is deleted quickly or kept only for a short diagnostic grace period.
- Redis records avoid embedding shared nested plugin/API contracts when stable ids or an authoritative lookup suffice.
A mailbox or idempotency record can still be authoritative in Redis while work is in flight. The test is whether loss/expiry is an accepted operational outcome—not whether the data is "history."
Exit criteria
- No chat Redis record uses the chat-sdk 30d TTL.
- Every key family documents authority, loss behavior, active TTL, and terminal TTL/deletion.
- SQL-owned conversation metadata is not duplicated into Redis except during a named rollout.
- Redis schemas do not store full
Source/Destination/ actor contracts unless that store explicitly owns the bounded operational record. - Dashboard/reporting reads SQL, not Redis indexes.
- Compatibility code has a release/date removal condition and an owning TODO.
- User-authored configuration and user-visible context do not silently disappear because a scratch TTL elapsed.
- Tests prove terminal cleanup and authoritative reconstruction without legacy Redis fields.
Cutover rule
- Deploy readers that use the canonical authority (usually SQL).
- Dual-write only while old readers may still be running.
- Once canonical readers are deployed, remove the Redis write path and obsolete schema fields immediately. Do not wait for old Redis TTLs.
- Put cleanup TODOs beside temporary dual-write/schema code and reference this tracker (
#1267).
Target model for thread scratch
Redis holds active thread state only:
processing(activeTurnId,pendingAuth)- maybe
sandboxRefwhile a sandbox is still useful
Cold start rebuilds from SQL. Do not keep a long-lived idle bag for nostalgia.
Vision summaries are a disposable, rebuildable cache outside shared scratch. Keep them bounded and versioned; expiry may cause re-analysis but does not lose product state.
Artifacts are not product state. Canvas and list objects live in Slack. Their ids and URLs already exist in durable tool results. The artifact bag is an implicit tool contract, not an authority. Remove it instead of moving it to SQL.
Do not ship adaptive multi-TTL schemes on a mixed bag. That papers over two jobs in one key. #1361 explored that path and was closed without merge. After the bag was thinned, dual active/terminal TTLs on the remaining thin record were also skipped (#1369).
Done
Turn sessions — complete
Resume lease over SQL history. Nested routing/actors and ops metadata are out of Redis; TTLs are short; dashboard indexes are gone.
- #1268 — resume routing from SQL only
- #1286 — stop nested
source/destinationwrites; explicit strip schemas - #1298 — stop actor writes
- #1308 — 24h unfinished / 1h terminal; drop
runtimeContexton terminal - #1313 — thin recovery indexes; remove global dashboard list
- #1315 — remove ops metadata from Redis records
- #1356 — drop dead turn-cursor model metadata
- #1266 closed without merge once Redis no longer owned nested source
Thread/channel scratch — complete enough
- #1320 — Junior 7d TTL instead of chat-sdk 30d
- #1323 — drop rebuildable conversation stats/backfill from Redis
- #1357 — location configuration in SQL (durable; Redis only temporary import)
- #1367 — remove artifact bag; list targets explicit
- #1368 — vision summaries as a separate bounded cache
Still in Redis scratch today: processing / pendingAuth and optional sandboxRef. The bag already TTLs at 7d and cold-starts from SQL. Further dual-TTL / terminal-grace churn on this thin record is not worth it.
Closed without merge
- #1361 — adaptive/split scratch TTL. Wrong model while artifacts/vision share the bag.
- #1369 — active-only / dual TTL after the bag was already thin. No meaningful product gain once artifacts and vision left; existing 7d expiry is enough.
Remaining
Decide authority and loss behavior before thinning each store. Do not move fields to SQL only to satisfy the slogan, and do not keep accidental durability in Redis.
1. Thin the conversation work mailbox
junior:conversation:* still mixes in-flight mailbox/control with duplicated durable conversation metadata (destination, actor, channel name, source, title) under a 7d TTL.
- Remove schema-v1 mailbox compatibility (
TODO(v0.110.0)) once aged out - Keep mailbox entries, execution status/lease, dedupe ids, recovery cursors
- Stop mirroring SQL-owned conversation metadata
- Define terminal/idle deletion or short grace instead of refreshing whole records for 7d
- Decision: must pending messages survive Redis loss? If yes, Redis cannot be their sole authority.
2. Redesign agent dispatch deliberately
junior:agent_dispatch:* still stores strict 7d records embedding actor, credential subject, destination, visibility, source, input, metadata, attribution, and status, plus legacy rollout fields through v0.116.0.
Before coding:
- Is a dispatch a durable product/API object whose idempotency/status must survive Redis loss or a >7d delay? If yes, SQL is canonical and Redis keeps locks/wake indexes only.
- If it is bounded operational state, document the 7d expiry contract and thin nested routing/authority via lookups where possible.
- Remove legacy execution fields and key/input compatibility after the stated release window.
- Split terminal retention from active retention.
Working order
- Remove the artifact bag and make list tool targets explicit. — complete in refactor(chat): Remove thread artifact state #1367
- Keep vision summaries as a bounded, versioned cache outside shared thread scratch. — complete in ref(chat): Separate vision cache from thread scratch #1368
- Reduce thread scratch to active-only state with short TTL. — skipped; bag is already thin (
processing/ optionalsandboxRef), 7d TTL expires it, cold start is SQL. Dual TTL closed without merge in ref(chat): Bound thread scratch to active-only TTL #1369. - Thin mailbox metadata; remove schema-v1 compatibility.
- Decide whether pending mailbox work must survive Redis loss; move only if yes.
- Define dispatch durability/idempotency guarantees; SQL-canonicalize or explicitly bound/thin the Redis record.
- Add terminal deletion/grace and remove expired compatibility code for mailbox and dispatch.
Out of scope
- OAuth user tokens and auth sessions
- SQL conversation history / events (already durable authority)
- Further dual-TTL ceremony on thin thread scratch after artifacts/vision left the bag
Activity
sentry-junior commentedon Aug 6, 2026
Inventory: agent turn sessions (item 1)
Owner:
packages/junior/src/chat/state/turn-session.ts(+turn-session-keys.ts)Keys / TTL
junior:agent_turn_session:{conversationId}:{sessionId}junior:agent_turn_session:index(cap 5_000)junior:agent_turn_session:conversation:{conversationId}:indexTHREAD_STATE_TTL_MS(AGENT_TURN_SESSION_TTL_MS = THREAD_STATE_TTL_MS)JUNIOR_THREAD_STATE_TTL_MSWhat redis stores
Full record (
storedAgentTurnSessionRecordSchema,.strict()):conversationId,sessionId,sliceId,version,state,startedAtMs,lastProgressAtMs,updatedAtMs,surface,traceId,resumeReason,resumedFromSliceId,errorMessagecommittedSeq,historyVersion?,turnStartSeq?source(sourceSchema),destination(destinationSchema),actor/actors(actorSchema)dispatchId?,dispatchOutcome?,resultMessageId?channelName?,modelId?,reasoningLevel?,loadedSkillNames?,cumulativeDurationMs,cumulativeUsage?runtimeContext?: PiMessage[](AGENTS.md /<runtime-turn-context>parts retained for unfinished resumes; not full transcript)Summary indexes store the same summary fields (no
committedSeq/runtimeContext/ actors list), also strict-parsed.On read,
piMessagesare not taken from redis — they are re-projected from SQL viacommittedSeq(+ optionalruntimeContextrestore whilerunning/awaiting_resume).Readers / writers (schema-coupled)
upsertAgentTurnSessionRecord,recordAgentTurnSessionSummary,updateAgentTurnSessionStategetAgentTurnSessionRecordForResume→agent-continue-runner, slack resume, oauth callbacks, reply-executorlistAgentTurnSessionSummaries*Resume requires stored nested
source/destination/actortoday (agent-continue-runnerfails closed ifsourcemissing).Why shape changes hang around
source/destination/actor) live in redis, not just ids — same class as open temporary compat #1266Density vs need (inventory only)
committedSeq/historyVersion/turnStartSeq/ status / sliceruntimeContextsource/destination/actorfull objectsRelated
sentry-junior commentedon Aug 6, 2026
Analysis: turn sessions — ephemeral vs not, and what to improve
Lens: what must survive a pause, what can be rebuilt from SQL/other authority, what only exists because redis is currently the resume bag.
Already authoritative elsewhere (rebuildable)
piMessages/ provenancejunior_conversation_eventsviacommittedSeqdestinationjunior_conversations.destination/ destination rowrecordActivitysource(session-stable parts)sessionSource(source_json)messageTsactor(slack user)actors[]channelName, usage, durationrecordExecution)modelId/ skills / reasoningTruly ephemeral (cannot honestly rebuild today)
These are the only turn-session bits that are ops state for an in-flight run, not history:
state+resumeReasonversionsliceId/resumedFromSliceIdcommittedSeq+historyVersion+turnStartSeqruntimeContextdispatchId/resultMessageId/dispatchOutcomeImportant: even the ephemeral set is only needed while the turn is non-terminal (
running/awaiting_resume). Aftercompleted/failed/abandoned, redis is mostly a 30d ops cache of things SQL already got.Pretends to be ephemeral but is treated as durable bag
Resume currently requires nested redis
source(and uses redisdestination/actor) even though SQL already holds conversation-level copies:agent-continue-runnerfails closed ifactiveSessionRecord.sourceis missinggetAwaitingAgentContinueRequestrequiressessionRecord.destinationconversationId+sessionId+expectedVersion+ destination on the continue request — so redis (or a rebuild step) must rehydrate routingThat is the core design smell: short-lived control plane fields are co-located with long-lived nested platform contracts, then given a 30d TTL and strict parse.
What “good” looks like for turn sessions
Keep in redis (short TTL, hours / low days, only while unfinished):
conversationId,sessionIdstate,resumeReason,version,sliceIdcommittedSeq,historyVersion,turnStartSeqruntimeContext(drop on terminal)dispatchId?,resultMessageId?Do not keep as nested redis contracts:
source/destination/actor/actors— rebuild from SQL conversation + events at resumeTTL policy:
THREAD_STATE_TTL_MS(30d)Parse policy:
.strict()fail-closed on resume for additive field driftImprovement order (turn sessions only)
sourcesource(fix(plugin-api): Coerce legacy source visibility on read #1266 becomes unnecessary for this store)Non-goals / traps
junior_conversations+ events are forBottom line
Turn sessions should be a small resume lease over SQL history, not a 30-day mirror of routing + ops metadata. Most of the hangover surface is duplicated, rebuildable data; the irreducible ephemeral core is cursors + control + short-lived
runtimeContext.sentry-junior commentedon Aug 6, 2026
Slice 1 in progress: resume rebuild from SQL
Implementing the first turn-session improvement from the analysis:
source/destinationwhen presentjunior_conversations.sessionSource/destinationOut of this slice: shrinking writes, TTL split, dropping summary indexes, stop writing nested contracts.
Tracked call sites:
getAwaitingAgentContinueRequestcontinueSlackAgentRun/ stranded recoverysentry-junior commentedon Aug 6, 2026
Slice 1 PR
Draft PR: #1268
Implemented resume rebuild from SQL for missing turn-session
source/destination:resolveTurnSessionRoutingStill later slices: shrink writes, TTL split, drop summary-list fat copies, stop writing nested contracts.
sentry-junior commentedon Aug 6, 2026
Slice 1 update: SQL is the only routing authority
PR #1268 now always loads destination + session source from
junior_conversationson resume. No redis-prefer / SQL-fallback dual path.Still later: stop writing nested contracts into turn-session redis, TTL split, drop fat summary indexes.
ref(chat): Load turn-session routing from SQL on resume (#1268)
fix(api): Skip slack source urls without threadTs
ref(chat): Stop writing nested routing into turn-session Redis
test(chat): Stop expecting nested routing on redis turn sessions
ref(chat): Clean turn-session projections and write paths
fix(chat): Preserve SQL source when abandon lacks destination
ref(chat): Stop writing nested routing into turn-session Redis
test(chat): Stop expecting nested routing on redis turn sessions
ref(chat): Clean turn-session projections and write paths
fix(chat): Preserve SQL source when abandon lacks destination
27 remaining items
fix(chat): Keep pause boundaries above lagging running summaries
fix(chat): Prefer higher session version in recovery-index collapse
test(chat): Prune recovery-index collapse cases to two outcomes
ref(chat): Keep recovery-index policy out of metadata cleanup
sentry-junior commentedon Aug 8, 2026
Correction to the residual note above: #1328 no longer changes recovery-index collapse policy. Repeated lifecycle eval failures showed that summary ordering interacts with continuation recovery more broadly than this metadata-cleanup slice, so those changes and their added coverage were removed in 6118d73.
The follow-up remains: review the fire-and-forget turn-start
runningsummary together with continuation discovery/recovery ownership. Treat that as a separate vertical slice with the existing lifecycle evals as its product coverage, rather than extending #1328.sentry-junior commentedon Aug 9, 2026
Superseded the stale #1328 cleanup with a fresh PR on current main after #1344: turn-cursor honesty only (drop dead model/skills/reasoning from checkpoint writes; rename runtimeMetadata → runtimeMetrics for SQL channel/metrics). No recovery-index changes. Fresh PR will be linked from this thread / the closed #1328 comment.
sentry-junior commentedon Aug 9, 2026
Fresh cleanup PR: #1356
ref(chat): Drop dead turn-cursor model metadata (#1356)
ref(chat): Persist location configuration in SQL (#1357)
refactor(chat): Remove thread artifact state (#1367)
ref(chat): Separate vision cache from thread scratch (#1368)
sentry-junior commentedon Aug 10, 2026
Slice: active-only thread scratch
Artifacts (#1367) and vision cache separation (#1368) are merged. Next remaining scratch item:
Draft PR: #1369
This slice
processing/ optionalsandboxRefactiveTurnIdorpendingAuthis setStill later
sentry-junior commentedon Aug 10, 2026
Active-only thread scratch — skipped
Closed #1369 without merge.
After artifacts (#1367) and vision (#1368) left the bag, dual active/terminal TTLs on the remaining thin record are ceremony. The bag already TTLs out; cold start is already SQL. No meaningful product gain.
Still remaining
sentry-junior commentedon Nov 9, 2026
Closing as done: about 15 slices merged (#1268–#1368). Open a narrow issue if a remaining leftover (mailbox metadata, agent-dispatch retention) matters.
Closed during a tracker cleanup. Reopen if this still matters.