Skip to content

fix(session): define List order as last update time ascending - #1919

Merged
wolo-lab merged 6 commits into
google:mainfrom
anzal1:fix/session-list-order
Nov 7, 2026
Merged

wolo-lab merged 6 commits into
google:mainfrom
anzal1:fix/session-list-order

Conversation

@anzal1

@anzal1 anzal1 commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Linked issue

Problem:
session.Service.List documents no order, and each backend returns its own: key order in memory, primary key order in the database, and whatever the ListSessions RPC 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 on Service.List and ListResponse.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") before Find. The names are the GORM column names of storageSession (UpdateTime, UserID, ID).
  • session/vertexai/vertexai_client.go: sort the collected slice client-side with sortSessionsByLastUpdate. The RPC request is unchanged, so recorded rpcreplay requests still match.

The exported conformance suite in session/sessiontestsuite is 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?

List returns 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:

  • All unit tests pass locally.

nice -n 15 go test -p 2 ./session/... passes (session, session/compaction, session/database, session/vertexai), and gofmt and go vet are clean on the touched packages.

New tests:

  • TestInMemoryService_ListOrderedByLastUpdateTime and TestInMemoryService_ListTieBreaksByUserThenID in session/inmemory_test.go
  • TestDatabaseService_ListOrderedByLastUpdateTime in session/database/service_test.go (SQLite)
  • TestSortSessionsByLastUpdate in session/vertexai/session_test.go (unit test of the sort helper)

With your source change reverted and your tests kept, which test fails?

  • In-memory sort removed: TestInMemoryService_ListOrderedByLastUpdateTime fails ([a b c], want [b c a]).
  • Database Order(...) removed: TestDatabaseService_ListOrderedByLastUpdateTime fails ([a b c], want [b a c]).
  • Vertex helper's session ID tie-break removed: TestSortSessionsByLastUpdate fails.
  • Not covered: removing the sortSessionsByLastUpdate(sessions) call from listSessions stays green. vertexAiClient holds 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

  • I have read the CONTRIBUTING.md document.
  • I have performed a self-review of my own code.
  • I have commented my code, particularly in hard-to-understand areas.
  • I have added tests that prove my fix is effective or that my feature works.
  • New and existing unit tests pass locally with my changes.
  • I have manually tested my changes end-to-end.
  • Any dependent changes have been merged and published in downstream modules.

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
@anzal1
anzal1 force-pushed the fix/session-list-order branch from 9dba69e to de835a0 Compare October 21, 2026 09:27

@ROM4n2 ROM4n2 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I read the diff against main and checked all three backends. No blocking findings.

What I verified

  • In-memory: List sorts the slice it builds from copySessionWithoutStateAndEvents, which copies updatedAt, so LastUpdateTime() is the stored value rather than the zero time.
  • Database: storageSession has no column tags, so the GORM default snake_case names in Order("update_time, user_id, id") are exactly the columns, and List always filters by app name, so the user_id, id tie-break is unambiguous.
  • Vertex: sortSessionsByLastUpdate sorts the slice built in listSessions, 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.

@indurireddy-TF

Copy link
Copy Markdown
Contributor

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.
image
image
image
image

Equal update times across two users must list by user_id, then id.

Refs google#1919
@anzal1

anzal1 commented Oct 31, 2026

Copy link
Copy Markdown
Contributor Author

@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 wolo-lab 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.

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.

Comment thread session/inmemory_test.go Resolved
Comment thread session/vertexai/session_test.go Resolved
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.
@anzal1

anzal1 commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

@wolo-lab thanks for the probe. Fixed in 1bcd4ef, on top of a merge of main (cfc1ef4).

  • Database: List no longer uses ORDER BY. It sorts the rows in Go after Find, with the same comparator as the other backends, so rows already stored with any mix of offsets come back in instant order. This also settles the column-naming question. TestDatabaseService_ListOrdersMixedOffsetsByInstant is your probe run through List. With the old ORDER BY it fails with [late early]. The existing tie-break test still fails if the user or session ID comparison is dropped.
  • In-memory: the comparator is now compareByLastUpdate, and TestCompareByLastUpdate tests it directly with input the sort has to reorder. Swapping the user and session ID comparisons fails it. I removed TestInMemoryService_ListTieBreaksByUserThenID, since it could not fail.
  • Vertex AI: the test now ties u2/a with u1/a and u1/b, so the session ID order disagrees with the user order. Deleting the user ID comparison fails it.

Written with the help of an agent (Claude Code, claude-opus-5-5).

@anzal1

anzal1 commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

One note I left out above: the event order in the database Get (timestamp DESC, id DESC) has the same text comparison on SQLite. I kept this PR to List, and can open an issue for Get if that helps.

Written with the help of an agent (Claude Code, claude-opus-5-5).

@wolo-lab wolo-lab 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.

LGTM, thanks!

@wolo-lab
wolo-lab merged commit 8be7e25 into google:main Nov 7, 2026
21 of 27 checks passed
wolo-lab added a commit that referenced this pull request Nov 16, 2026
, #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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

session: Service.List has no defined order

4 participants