Skip to content
Source
Sign inSign up
TanStack/ai

fix(ai-persistence): an activity row started before the merge goes after its turn #2252

Draftozolcar(GitHub profile, opens in a new tab)wants to merge 4 commits intomain fromrefs/pull/2252/headopened View on GitHub

ozolcar(GitHub profile, opens in a new tab)commented

With withPersistence, an activity row that a run starts before the stored thread is merged kept the wrong index. On reload, that row showed near the top of the thread. This happens on every run with an event sent from setup, for example withSandbox's sandbox.starting. Now withPersistence.onConfig puts each new row that comes after the last request message at the end of the merged thread.

🎯 Changes

  • packages/ai-persistence/src/middleware.ts: one block in onConfig moves those rows to the end of the merged thread.
  • packages/ai-persistence/tests/with-persistence.test.ts: four new tests, and one existing test now also asserts the index.
  • .changeset/persistence-early-activity-index.md: a patch for @tanstack/ai-persistence.

✅ Checklist

  • I have followed the steps in the Contributing guide.
  • I have tested code changes locally with pnpm run test:pr, or these tests do not apply to this pull request. (Not run. See Testing.)
  • I fully understand the code in this pull request, including any code generated with AI assistance.
  • Docs: I updated docs/ for this change, or this change is not user-facing. (No page in docs/ tells how activity rows get their index.)
  • Changeset: I added a changeset (pnpm changeset), or this PR does not change a published package.

🚀 Release Impact

  • This change affects published code, and I have generated a changeset.
  • This change is docs/CI/dev-only (no release).

Root cause

Issue. A middleware that starts an activity row on RUN_STARTED stores that row at the wrong index if an earlier middleware sends an event from setup. Over three turns, the stored indexes are [1, 1, 1], and the correct indexes are [1, 4, 7]. If the request carries the full transcript, the indexes are [1, 3, 5].

Cause. The event from setup makes runWhileYielding send a synthetic RUN_STARTED in the init phase, before withPersistence.onConfig merges the stored thread. The engine gives the new row an index against interleaveActivityRecords(modelMessagesToUIMessages(this.messages), this.activities). At that time, this list has only the request. Then onConfig keeps that index, because the store does not have the row (byId.get(record.id)?.index ?? record.index).

Fix. onConfig finds each new row that comes after the last request message, with the same test that keptActivities uses: sort by index, then keep the rows where index - earlier >= modelMessagesToUIMessages(ctx.messages).length. It counts ctx.messages, the request as received, because that is what the engine indexed against; config.messages may already be changed by an earlier middleware. The run adds its output at the end of the merged thread, so these rows go there too. Each row gets the length of the merged thread plus the number of rows before it. Stored rows and inbound rows inside the request keep their index.

Possible alternatives

  • The patch in the issue. It tests record.index >= requestEnd, but index also counts activity rows. Its mergedEnd counts only stored rows, so a request that carries its own activity row is off by one. The test counts the activity rows that the request carries gets 3 with that patch and 4 with this one.
  • Hold RUN_STARTED until the engine applies the init config. This delays sandbox.starting, which shows a pending state early on purpose.
  • Change the index in the engine after applyMiddlewareConfig. This adds state to a class of 7,700 lines. Also, the fix is then far from the middleware that changes the transcript.

Testing

Commands run. I ran the same command at two commits, each in a new detached worktree: efe3b1cb (the tests on main's source) and 86cc18c4 (the fix).

pnpm exec vitest run tests/with-persistence.test.ts -t "activity started before the stored thread is merged|merges an inbound row instead"

At efe3b1cb:

× merges an inbound row instead of replacing the stored rows
× puts the row after its turn when the request has only that turn
× puts the row after its turn when the request has the full transcript
AssertionError: expected [ [ 'act-1', 1 ], [ 'act-2', 3 ] ] to deeply equal [ [ 'act-1', 1 ], [ 'act-2', 4 ] ]
AssertionError: expected [ 1, 1, 1 ] to deeply equal [ 1, 4, 7 ]
AssertionError: expected [ 1, 3, 5 ] to deeply equal [ 1, 4, 7 ]
Tests  3 failed | 1 passed | 44 skipped (48)

The test that passes there is counts the activity rows that the request carries. It passes on main and fails only with the patch in the issue.

At 86cc18c4:

Tests  4 passed | 44 skipped (48)

A later commit, 358d5c6c, counts ctx.messages instead of config.messages and adds the test counts the request as received when an earlier middleware trims its messages. Before that commit the new test failed with act-inbound at 3; at 358d5c6c all 49 tests in with-persistence.test.ts pass.

In packages/ai-persistence at 358d5c6c:

  • pnpm test:lib: 28 files, 654 passed, 291 skipped.
  • pnpm test:types: passes.
  • pnpm test:oxlint: 0 errors. The 9 warnings are on lines that this PR does not change.

Not run:

  • pnpm run test:pr. It needs the full workspace, and I worked in a sparse checkout.
  • An E2E test in testing/e2e/middleware.spec.ts. The E2E app needs about 40 workspace packages, and its postinstall downloads Chromium. That did not fit on my disk. The unit tests run the real chat() engine with memoryPersistence and reconstructChat, which is the path of the bug.

Manual test.

  1. Build @tanstack/ai with pnpm --filter "@tanstack/ai-persistence^..." run build.
  2. Check out efe3b1cb. In packages/ai-persistence, run the command above. Three tests fail, as shown.
  3. Check out the branch head and run the command again. All four tests pass.

How this PR makes testing easy. The repro is in the tests on this branch. The first commit has only the tests, so a reviewer can see them fail before the fix.

Linked issues

Fixes #2246

Risk / rollback

  • Risk is low. The change is in one block of onConfig and changes only the index of a row the store does not have that comes after the last message of the request as received.
  • A behavior change: an inbound row that the request carries after its last message also moves to the end of the merged thread. On main, the test merges an inbound row instead of replacing the stored rows stored act-2 at 3, which reconstructs before u2. Now it is at 4.
  • Rollback: revert this PR.
    1. Pushed358d5c6

    2. 🦋 Changeset detected

      Latest commit: 358d5c6c8f3a0c663b8f3a292817160cb5a56412

      The changes in this PR will be included in the next version bump.

      This PR includes changesets to release 1 package
      NameType
      @tanstack/ai-persistencePatch

      Not sure what this means? Click here to learn what changesets are.

      Click here if you're a maintainer who wants to add another changeset to this PR

Sign in to join this conversation.