ai-compaction: checkpoint never reused when the store returns message keys in another order

Abierto
#2,050 0 comentarios 0 reacciones 1 asignado Ver en GitHub

Los mantenedores suelen responder en 1 día

@tombeckenham ya está trabajando en esto.

Desde el 5/11/2026.

  • #2056 de @pcbeingused333 — abierto

Evaluación

Este issue todavía no se ha evaluado.

Descripción

has-pr waiting-on: maintainer
TanStack AI version

@tanstack/ai-compaction 1.0.0, @tanstack/ai 1.0.1, @tanstack/ai-persistence 1.0.1

Framework/Library version

TanStack Start 1.169.4, React 19.3.1, Node 26. Messages and checkpoints stored in PostgreSQL jsonb.

Describe the bug and the steps to reproduce it

A compaction checkpoint is never reused when the message store gives messages back with their keys in a different order. Every request past the limit then runs the summarizer again over the same history.

hashMessages (packages/ai-compaction/src/usage-count.ts) hashes JSON.stringify(messages), and that output depends on key order. The checkpoint check compares stored.sourceHash with hashMessages(messages.slice(0, stored.sourceMessageCount)), where messages are the ones the store just loaded (dist/esm/index.js:562 in 1.0.0). The same applies to prefixHash and to lastCoveredHash in the usage count.

Key order isn't preserved by common stores:

  • PostgreSQL jsonb reorders an object's keys: shorter keys first, then by bytes. An assistant message built as { role, content, metadata, toolCalls, id, createdAt } comes back as { id, role, content, metadata, createdAt, toolCalls }.
  • Validating a loaded row with a schema library reorders keys too. Zod's looseObject returns the declared keys first.

The messages are equal by value, which is what the persistence conformance tests check with toEqual. But they hash differently, so the checkpoint looks stale.

Steps:

  1. Use withCompaction with a checkpoint store and a summarizeOldest strategy, and a message store whose load returns each message with its keys in another order. For example, round-trip each message through Object.fromEntries(Object.entries(m).sort()).
  2. Send messages until the thread passes the limit. One summary runs and a checkpoint is saved.
  3. Send two more messages.

Expected: the two later requests reuse the checkpoint, so no new summary runs.
Actual: each request runs the summarizer again over the same history. In our app, the summary request was the same ~287 KB request on every message after the limit. Counted per message after the limit, the summary runs were [1, 1, 1].

The smallest form of the cause:

import { createHash } from 'node:crypto'
const hash = (v) => createHash('sha256').update(JSON.stringify(v)).digest('hex')
const saved = { role: 'user', content: 'hi', id: 'm1' }
const loaded = { id: 'm1', role: 'user', content: 'hi' } // same message, as jsonb returns it
console.log(hash([saved]) === hash([loaded])) // false

A fix that worked for us: hash a canonical form, with object keys sorted at every depth.

function sortedKeys(_key: string, value: unknown): unknown {
  return typeof value === 'object' && value !== null && !Array.isArray(value)
    ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
    : value
}
// in hashMessages:
const bytes = new TextEncoder().encode(JSON.stringify(messages, sortedKeys))

With that change, the runs per message after the limit were [1, 0, 0]. Checkpoints saved before the change miss once, and the next summary overwrites them.

Your Minimal, Reproducible Example

The snippet above shows the cause. The steps reproduce it with any store that reorders keys. We're running the fix above as a pnpm patch of 1.0.0.

Lenguaje dominante
TypeScript
Estrellas
3.3k
Forks
378
Merge medio
1 d 2 h
PR fusionados (30 d)
254

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de TanStack/ai

Todos los issues de TanStack/ai

Issues similares

Más issues de TypeScript

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.