Repository navigation
fix(session): define List order as last update time ascending - #1919
Conversation
Service.List documented no order, and each backend returned its own: key order in memory, primary key order in the database, and whatever the RPC returned on Vertex AI. Document last update time ascending (ties by user ID, then session ID), matching adk-python, and make every backend produce it. Closes: google#1874
9dba69e to
de835a0
Compare
ROM4n2
left a comment
There was a problem hiding this comment.
I read the diff against main and checked all three backends. No blocking findings.
What I verified
- In-memory:
Listsorts the slice it builds fromcopySessionWithoutStateAndEvents, which copiesupdatedAt, soLastUpdateTime()is the stored value rather than the zero time. - Database:
storageSessionhas nocolumntags, so the GORM default snake_case names inOrder("update_time, user_id, id")are exactly the columns, andListalways filters by app name, so theuser_id, idtie-break is unambiguous. - Vertex:
sortSessionsByLastUpdatesorts the slice built inlistSessions, so the RPC response is not mutated and the recorded replay is unaffected.
One question (non-blocking)
Order hardcodes column names, while the service accepts a caller-supplied gorm.Config and TableName honors schema.Namer. If a caller overrides NamingStrategy.ColumnName, this ORDER BY would name a column that does not exist. Is column renaming in scope? If not, a sentence in the doc would settle it; if it is, sorting after Find the way the Vertex path does would avoid the coupling.
One test suggestion (non-blocking)
The in-memory tie-break has TestInMemoryService_ListTieBreaksByUserThenID, but the SQL tie-break (user_id, id) has no equivalent. A database case with equal update_time across two users would pin it; without one, dropping that part of the Order would stay green.
The listSessions call-site gap you disclosed is fine by me; recording it in the description is better than adding a heavy fake, though a small fake ListSessions server would also close it if maintainers prefer.
Nice change overall — the backends now agree and the doc states the contract.
|
Hi @anzal1 I’ve tested the changes locally, and the session ordering now follows the expected last-update-time order. The behavior looks consistent with the intended fix. |
Equal update times across two users must list by user_id, then id. Refs google#1919
|
@ROM4n2 thanks for checking all three backends. On your question: column renaming isn't in scope. The database service already uses raw column names in several queries on main (app_name = ?, user_id = ?, session_id = ? and the timestamp DESC, id DESC order in Get), so this Order follows the existing convention rather than adding a new limit. Happy to open an issue if you think renamed columns should be supported. On the test: added TestDatabaseService_ListTieBreaksByUserThenID in db18dc5, with equal update times across two users. One catch: SQLite serves the app_name filter from the composite primary key index and its sort is stable, so ties already come out in (user_id, id) order, and dropping the whole tie-break would still pass. The test adds a test-only index on (app_name, update_time) so ties arrive in insertion order. With it, dropping the whole tie-break, only user_id, or only id each fails the test. |
wolo-lab
left a comment
There was a problem hiding this comment.
One thing needs fixing before merge: on SQLite the new ORDER BY update_time sorts by text, not by time, so the documented order breaks when stored timestamps carry different UTC offsets. The in-memory and Vertex AI paths look right, and the order matches adk-python. Two test gaps are noted inline.
SQLite orders update_time as text. The SQLite driver stores time.Time as an RFC 3339 string that keeps the value's own offset, and the update_time column (storage_session.go#L37) is compared as text by the new Order call (service.go#L286). The service writes values in mixed zones: Create uses platform.Now, which is local time (storage_session.go#L50), and AppendEvent stores whatever zone the caller's event.Timestamp carries (service.go#L503). So on a host whose local zone is not UTC, a session created locally and a session updated by a UTC-stamped event come back in the wrong order. The same happens in a single zone across a daylight-saving fall-back. With one offset everywhere the text order happens to match time order, which is why the new tests (all UTC) pass. adk-python's SQLite service stores update_time as REAL epoch seconds (sqlite_session_service.py#L118-L126), so it orders by instant. Whatever the fix, List must return instant order for any mix of offsets already stored in existing databases, not only for rows written after the change. Sorting after Find with the same comparator the in-memory path uses would meet that, and would also settle the column-naming question raised earlier.
Reproduction (rows written through the service on main, then queried with this PR's ORDER BY)
// session/database, package database. Run: go test -run TestOrderProbe -v ./session/database/
func TestOrderProbe(t *testing.T) {
svc := emptyService(t)
instant := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)
for _, c := range []struct {
id string
at time.Time
}{
{"early", instant.In(time.FixedZone("CEST", 2*3600))}, // one hour before "late"
{"late", instant.Add(time.Hour)},
} {
ctx := platform.WithTimeProvider(t.Context(), func() time.Time { return c.at })
if _, err := svc.Create(ctx, &session.CreateRequest{AppName: "app", UserID: "u", SessionID: c.id}); err != nil {
t.Fatal(err)
}
}
var rows []storageSession
if err := svc.db.Order("update_time ASC, user_id ASC, id ASC").Find(&rows).Error; err != nil {
t.Fatal(err)
}
for _, r := range rows {
t.Log(r.ID)
}
}late
early
The stored values are 2026-01-01T13:00:00Z and 2026-01-01T14:00:00+02:00, so "early" sorts last. With both rows in UTC the same query returns early, then late.
# Conflicts: # session/inmemory_test.go
SQLite stores update_time as RFC 3339 text with the value's own offset, so ORDER BY update_time compared text and mixed offsets came back out of order. Sort the rows in Go after Find with the same comparator as the other backends, which also works for rows already stored. Test the in-memory comparator directly, since List's ordered map already yields ties in tie-break order, and give the Vertex AI test a tie across users whose session ID order disagrees with their user order.
|
@wolo-lab thanks for the probe. Fixed in 1bcd4ef, on top of a merge of main (cfc1ef4).
Written with the help of an agent (Claude Code, claude-opus-5-5). |
|
One note I left out above: the event order in the database Written with the help of an agent (Claude Code, claude-opus-5-5). |
, #1919, #2189, #2285) (#2346) * fix(session/vertexai): drop temp: keys from the initial state on Create (#2100) (cherry picked from commit 0c109f7) * fix(session): keep in-memory Get from returning events before After (#2089) (cherry picked from commit 10395f0) * fix(session/database): lock app and user state rows in Create (#1930) (cherry picked from commit 2f3b2c2) * fix(session/database): delete a session's events explicitly in Delete (#1774) (cherry picked from commit 7af0f5f) * fix(session): define List order as last update time ascending (#1919) (cherry picked from commit 8be7e25) * fix(session): skip nil parts in IsFinalResponse classification (#2189) (cherry picked from commit 75ae920) * fix(session): count a final error event as a final response (#2285) (cherry picked from commit d9ecb34)




Linked issue
Problem:
session.Service.Listdocuments no order, and each backend returns its own: key order in memory, primary key order in the database, and whatever theListSessionsRPC returns on Vertex AI. A caller that wants the most recently active session has to sort the result itself, and cannot rely on any particular order across backends.Solution:
Define the order and make every backend produce it: last update time ascending, ties broken by user ID and then session ID, so the last session is the most recently active. This matches adk-python (commit 53e1afbc), and the scope was agreed in the issue discussion.
session/service.go: document the order onService.ListandListResponse.Sessions.session/inmemory.go: stable sort by (last update time, user ID, session ID).session/database/service.go:.Order("update_time ASC, user_id ASC, id ASC")beforeFind. The names are the GORM column names ofstorageSession(UpdateTime,UserID,ID).session/vertexai/vertexai_client.go: sort the collected slice client-side withsortSessionsByLastUpdate. The RPC request is unchanged, so recorded rpcreplay requests still match.The exported conformance suite in
session/sessiontestsuiteis intentionally left unchanged, per the issue discussion, because third-party implementations run it. The order tests live in each backend's own test file instead.Behavior change
What behaves differently for someone already on the current release?
Listreturns sessions in update-time order (oldest update first) instead of key or heap order. Nothing that was documented changes, since no order was documented before. Callers that depended on the previous incidental order, for example in-memory sessions sorted by app, user and session ID, will see a different order. The set of sessions returned is the same, and the result now matches adk-python.Testing Plan
Unit Tests:
nice -n 15 go test -p 2 ./session/...passes (session,session/compaction,session/database,session/vertexai), andgofmtandgo vetare clean on the touched packages.New tests:
TestInMemoryService_ListOrderedByLastUpdateTimeandTestInMemoryService_ListTieBreaksByUserThenIDinsession/inmemory_test.goTestDatabaseService_ListOrderedByLastUpdateTimeinsession/database/service_test.go(SQLite)TestSortSessionsByLastUpdateinsession/vertexai/session_test.go(unit test of the sort helper)With your source change reverted and your tests kept, which test fails?
TestInMemoryService_ListOrderedByLastUpdateTimefails ([a b c], want [b c a]).Order(...)removed:TestDatabaseService_ListOrderedByLastUpdateTimefails ([a b c], want [b a c]).TestSortSessionsByLastUpdatefails.sortSessionsByLastUpdate(sessions)call fromlistSessionsstays green.vertexAiClientholds a concrete gRPC client, and the replay tests do not pin order, so the call site has no test without a fake gRPC server. The helper itself is tested.Checklist