Skip to content

test(runtime): add persistence observer streaming benchmarks - #4077

Closed
salignatmoandal wants to merge 4 commits into
docker:mainfrom
salignatmoandal:bench/persistence-observer-streaming
Closed

salignatmoandal wants to merge 4 commits into
docker:mainfrom
salignatmoandal:bench/persistence-observer-streaming

Conversation

@salignatmoandal

Copy link
Copy Markdown
Contributor

Summary

Adds characterization tests and benchmarks for PersistenceObserver streaming persistence — the path that mirrors assistant token deltas (AgentChoice / AgentChoiceReasoning) into a single growing message row in the session store.

This establishes a baseline before any future optimization (e.g. debounced flushes) and documents the per-chunk store write contract that the observer currently implements.

Context

During a streaming assistant turn, the runtime emits one AgentChoiceEvent per delta. PersistenceObserver.persistStreamingContent keeps a single in-flight row and:

  1. INSERT (AddMessage) on the first chunk
  2. UPDATE (UpdateMessage) on every subsequent chunk
  3. UPDATE again on MessageAddedEvent to finalise the row with the canonical payload

This behaviour is easy to regress when refactoring persistence or the store layer, but was not previously covered by a focused unit test or benchmark.

Changes

New file: pkg/runtime/persistence_observer_bench_test.go

Tests

Test What it pins
TestPersistenceObserver_UpdateCountPerChunk 1 AddMessage + (N-1) UpdateMessage calls for N streaming chunks, plus one final UpdateMessage on MessageAdded
TestPersistenceObserver_StreamingContentAccumulates Mid-stream reload shows accumulated assistant text ("hel" + "lo" → "hello")

Both tests use a countingStore wrapper around InMemorySessionStore to assert store call counts without mocking the observer.

Benchmarks

Each iteration simulates a long assistant turn: 500 AgentChoice deltas + 1 MessageAdded finalisation (streamingBenchChunks = 500).

Benchmark Store Purpose
BenchmarkPersistenceObserver_StreamingChunks InMemorySessionStore CPU / alloc cost of observer logic + in-memory clone path
BenchmarkPersistenceObserver_StreamingChunks_SQLite SQLite :memory: Realistic cost including json.Marshal + UPDATE session_items per chunk

Sample results (darwin/arm64, Apple M3 Pro)

BenchmarkPersistenceObserver_StreamingChunks-12          ~2.0 ms/op    502 KB/op    2515 allocs/op
BenchmarkPersistenceObserver_StreamingChunks_SQLite-12   ~3.1 ms/op   1558 KB/op    8714 allocs/op

Per chunk (500 chunks/iter): ~4 µs in-memory, ~6 µs SQLite, ~5 vs ~17 allocs.

SQLite is ~1.5× slower and ~3× more alloc-heavy — expected given JSON marshal + SQL per update.

Known benchmark caveats

  • In-memory drift: the in-memory benchmark reuses the same session across b.N iterations, so UpdateMessage eventually scans an ever-growing message list (O(messages) per update). Later iterations are slower than the first. SQLite stays flat because updates are keyed by message_id.
  • Migration logs: SQLite setup calls NewSQLiteSessionStoreFromDB, which logs migration info before b.ResetTimer() — noisy stdout but not included in ns/op.

These caveats are acceptable for a baseline but worth keeping in mind when comparing future numbers.

Why now?

Streaming persistence is on the hot path for every assistant response when a session store is configured. Having explicit tests + benchmarks makes it safer to:

  • change the flush strategy (per-chunk vs debounced)
  • optimize persistStreamingContent (avoid strings.Builder.String() copies on every delta)
  • compare in-memory vs SQLite store performance under realistic chunk counts

Test plan

  • go test ./pkg/runtime -run TestPersistenceObserver_UpdateCountPerChunk -v
  • go test ./pkg/runtime -run TestPersistenceObserver_StreamingContentAccumulates -v
  • go test ./pkg/runtime -run=^$ -bench=BenchmarkPersistenceObserver -benchmem -count=1
  • task test (full suite)
  • task lint

@salignatmoandal
salignatmoandal requested a review from a team as a code owner August 30, 2026 20:58
@salignatmoandal
salignatmoandal force-pushed the bench/persistence-observer-streaming branch from 36cfbd2 to 084471c Compare August 30, 2026 21:00
@aheritier aheritier added area/runtime Runtime engine, agent loop execution, tool dispatch, loop detection kind/test Test-only changes status/needs-signed-commits Some commits in the PR are signed with a valid SSH/GPG key labels Aug 30, 2026
@aheritier

Copy link
Copy Markdown
Collaborator

👋 Some commits in this PR are not signed and verified by GitHub. Please sign your commits with a GPG or SSH key registered in your GitHub account, then force-push.

Commits that are not verified: 084471c

See GitHub's guide on signing commits for setup instructions. I've added status/needs-signed-commits; it will be removed automatically once every commit in this PR carries a valid GitHub-verified signature.

@salignatmoandal
salignatmoandal force-pushed the bench/persistence-observer-streaming branch 2 times, most recently from 5cbf63a to e40f6b6 Compare August 30, 2026 21:13
@salignatmoandal

Copy link
Copy Markdown
Contributor Author

Hi @aheritier, thanks for the heads-up.

I've signed the commit with my SSH signing key and force-pushed (e40f6b6). GitHub now shows it as verified on my side.

Happy to adjust anything else if needed.

@aheritier aheritier removed the status/needs-signed-commits Some commits in the PR are signed with a valid SSH/GPG key label Aug 30, 2026
@Sayt-0 Sayt-0 self-assigned this Aug 31, 2026

@Sayt-0 Sayt-0 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.

Useful addition: the streaming persistence contract (1 AddMessage + N-1 UpdateMessage per turn) was not pinned by any focused test, and both characterization tests verify correctly against persistStreamingContent. Tests pass locally and follow the surrounding conventions (t.Parallel, t.Context, testify, :memory: + SetMaxOpenConns(1) pattern from pkg/session/store_memory_test.go).

Main issue: the in-memory benchmark result is a function of b.N (details inline), which defeats the stated goal of establishing a baseline. The SQLite benchmark is fine (reproduced ~2.9 ms/op, stable across benchtime values).

Area Status
Characterization tests correct, verified against persistence_observer.go
SQLite benchmark stable, no change needed
In-memory benchmark numbers depend on b.N, needs fix (inline comment)
Conventions, vet clean

Non-blocking: the file name persistence_observer_bench_test.go also hosts two unit tests; moving them to persistence_observer_streaming_test.go would keep the bench file benchmark-only, matching pkg/tui/components/message/bench_test.go.

@salignatmoandal

Copy link
Copy Markdown
Contributor Author

Good catch — confirmed in InMemorySessionStore.UpdateMessage: it ranges over every session and scans Messages, so cost is O(sessions × messages). With a shared session the store grew with b.N, so ns/op wasn't a usable baseline.

Fixed in a0ddcd4 with your suggested harness: each iteration does AddSession → work → DeleteSession (a fresh session alone isn't enough because of the session Range). Also simplified the helper to (obs, store).

Re-measured on darwin/arm64 (Apple M3 Pro):

benchtime before (unbounded) after (bounded)
200x ~203 µs 165 µs
2000x ~673 µs 160 µs
8000x ~2575 µs 160 µs

ns/op is now flat (~160 µs), in line with your ~175 µs result. Allocs stay ~2522/op.

Happy to follow up on the slog io.Discard nit and moving the unit tests to persistence_observer_streaming_test.go if you'd like those in this PR too.

@aheritier aheritier left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The benchmark behavior looks sound, but this branch is 592 commits behind main and does not compile against it due to the helper collision and stale UpdateMessage signature above. There is also a lint failure. Please rebase onto current main, address these items, and rerun CI.

@aheritier
aheritier marked this pull request as draft September 14, 2026 17:08
@salignatmoandal
salignatmoandal force-pushed the bench/persistence-observer-streaming branch from 29b4b7f to f66e8b1 Compare September 16, 2026 09:21
Document the per-chunk AddMessage/UpdateMessage contract and establish
in-memory vs SQLite baselines for streaming assistant persistence.
Reset the session each iteration so UpdateMessage's O(sessions×messages)
scan cannot make ns/op a function of b.N.
Discard the default slog handler during SQLite store setup so harness
re-invocations do not interleave migration INFO with -bench output.
Rename countingStore to avoid colliding with generated_file_test.go,
forward sessionID through UpdateMessage, and satisfy embeddedstructfieldcheck.
@salignatmoandal
salignatmoandal force-pushed the bench/persistence-observer-streaming branch from f66e8b1 to cfe2f18 Compare September 16, 2026 09:24
@salignatmoandal
salignatmoandal marked this pull request as ready for review September 16, 2026 09:30

@aheritier aheritier left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The bounded-store fix addresses the benchmark harness issue. The ~2.0 ms/op figure and related caveats still in the PR description describe the old unbounded harness, while your follow-up reports ~160 µs/op after the fix. Please rerun both benchmarks at the current head and refresh the sample results, per-chunk figures, store ratio, and resolved caveats. Include the SHA, Go version, hardware, and benchmark command so the comparison is reproducible. I have not independently reproduced these numbers; the improvement should be described as a harness correction, not a production-code speedup.


finalizeStreamingMessage(ctx, obs, sess)
// MessageAdded with an existing streaming row issues one more UpdateMessage.
assert.Equal(t, int64(chunks), store.updateCalls.Load())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nonblocking: this checks the final UpdateMessage count, but not the canonical persisted payload or the next-turn reset. Please reload after MessageAdded and assert exactly one assistant row containing the final "done" payload, with no additional AddMessage. Then emit a second turn using the same observer/session and verify a new row and one additional AddMessage, preserving the first row and excluding prior-turn content/reasoning.

require.NoError(t, err)
require.Len(t, reloaded.Messages, 2) // user + streaming assistant
require.NotNil(t, reloaded.Messages[1].Message)
assert.Equal(t, "hello", reloaded.Messages[1].Message.Message.Content)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nonblocking: both new tests emit only AgentChoice text deltas, although the PR includes reasoning deltas in its characterization scope. Please add a reasoning-first sequence followed by interleaved reasoning/text deltas, asserting one AddMessage on the first delta, an UpdateMessage for each subsequent delta, exactly one assistant row, and independently accumulated Content and ReasoningContent after reload.


b.ReportAllocs()
b.ResetTimer()
// Bound the store each iteration: UpdateMessage scans every session's

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Optional: this comment describes the old Store implementation. UpdateMessage now loads the specified session and scans its messages, rather than scanning every session. Please explain that reusing a session grows its message list, while creating/deleting a session per iteration bounds the per-session scan and retained store state.

@aheritier
aheritier self-requested a review October 7, 2026 15:46
@aheritier
aheritier marked this pull request as draft October 14, 2026 09:29
@TDnorthgarden

Copy link
Copy Markdown
Contributor

Hi @salignatmoandal — are you still planning to continue with this PR? It's been quiet since September, but the value is still there: the streaming per-chunk write contract (1 AddMessage + N-1
UpdateMessage) isn't covered anywhere else — the new sub-session tests from #4903 exercise a different path — and the benchmarks are the baseline for any future flush-strategy work on persistStreamingContent.

If you're not able to come back to it, I'd be happy to take it over and finish the remaining review items, with you credited as the original author of course. To make that concrete, I rebased your branch
onto current main (6353277a5): the rebase is clean, all four commits apply, and go test ./pkg/runtime -count=1 passes. Fresh benchmark numbers on that tree (linux/amd64, Intel i5-9400 @ 2.90GHz, Go 1.
27.4, go test ./pkg/runtime -run='^$' -bench='BenchmarkPersistenceObserver' -benchmem -count=1):

BenchmarkPersistenceObserver_StreamingChunks-6 4989 233217 ns/op 416003 B/op 1528 allocs/op
BenchmarkPersistenceObserver_StreamingChunks_SQLite-6 122 9774698 ns/op 1672625 B/op 9544 allocs/op

(SQLite is ~3× the original report — possibly hardware, possibly the store changes from #4903 landing after your last rebase; pinning that down would be part of the numbers refresh anyway.)

Remaining from @aheritier's October review: rerun and refresh the description numbers at the new head, the two non-blocking test additions (final canonical payload + next-turn reset; reasoning-delta
accumulation), and the stale comment about the old store scan.

Let me know either way — and if you'd rather finish it yourself, the rebase and numbers above might save you some time.

@TDnorthgarden

Copy link
Copy Markdown
Contributor

@salignatmoandal — following up on the takeover inquiry from Nov 12: with no response, I've opened #4938 carrying your branch rebased onto current main, with the remaining October review items addressed (fresh benchmark numbers at the final head, the two test additions, and the stale comment). You're credited as the original author of the four commits — thanks for the groundwork. @aheritier — feel free to close this one in favor of the new PR, or let me know if you'd rather handle it differently.

@aheritier aheritier closed this Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/runtime Runtime engine, agent loop execution, tool dispatch, loop detection kind/test Test-only changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants