service_test.go
Overview
The service_test.go file contains comprehensive unit tests for the Database Session Service, a GORM-backed SQL database implementation of session management within the system. The tests verify the correctness and robustness of session lifecycle operations including creation, retrieval, listing, deletion, and event appending with state management.
This file ensures that the database-backed session service adheres strictly to the session service contract and correctly implements:
Session creation with both client-specified and auto-generated session IDs,
Session retrieval with filtering and event pagination,
Listing of sessions per user or application-wide,
Deletion of sessions with correct error handling,
Appending of events with complex state delta updates and filtering of partial/temporary events,
Proper merging and segregation of application, user, and session state scopes,
Handling of concurrency scenarios such as stale session updates,
Persistence and retrieval of events with detailed metadata.
The tests rely on helper functions (emptyService and serviceDbWithData) to instantiate the database service and populate it with sample data. They use various Go testing and comparison utilities, including go-cmp for deep comparison and GORM's in-memory SQLite driver for isolated test environments.
Detailed Explanations of Functions and Methods
Test_databaseService_Create
Tests the Create method of the databaseService.
Purpose: Verify session creation behavior, including:
Creation with full session key (AppName, UserID, SessionID),
Auto-generation of session ID when omitted,
Failure when session already exists (in database backend, unlike in-memory).
Parameters:
t *testing.T: The testing context.
Test Cases:
"full key": Creates session with provided session ID and state."generated session id": Creates session with generated session ID."when already exists, it fails": Expects error when creating a session that already exists.
Assertions:
Session fields (
AppName,UserID,SessionID) match expectations.Session state matches expected key-value pairs.
Proper error handling on duplicate session creation.
Test_databaseService_Delete
Tests the Delete method of the databaseService.
Purpose: Verify session deletion behavior.
Parameters: Same as above.
Test Cases:
"delete ok": Deletes an existing session successfully."no error when not found": Deleting a non-existent session returns no error.
Assertions:
Proper deletion without error.
No error when deleting sessions that do not exist.
Test_databaseService_Get
Tests the Get method of the databaseService.
Purpose: Validate session retrieval with correct filtering of events, state merging, and user isolation.
Parameters: Same as above.
Setup Functions:
setupGetRespectsUserID: Ensures sessions respect user ID isolation by appending events to one user and verifying another user’s session does not see them.
setupGetWithConfig: Creates a session with multiple events to test event filtering and limits.
Test Cases:
"ok": Basic retrieval returns correct session and empty event list."error when not found": Retrieval of missing session returns an error."get session respects user id": Confirms user-level session isolation."with config_no config returns all events": Returns all events when no filters are set."with config_num recent events": Limits events returned to the most recent N."with config_after timestamp": Returns events after a certain timestamp."with config_combined filters": Combines timestamp and recent event filters.
Assertions:
Session state matches expected merged state.
Event lists match expected filtered and sorted events.
No cross-user event leakage.
Test_databaseService_List
Tests the List method of the databaseService.
Purpose: Verify listing of sessions per user or app.
Parameters: Same as above.
Test Cases:
"list for user1": Lists sessions for user1."empty list for non-existent user": Returns empty list for unknown user."list for user2": Lists sessions for user2."list all users for app": Lists all sessions for the app regardless of user.
Assertions:
Returned session lists match expected sessions without event histories.
Correct filtering by user ID or app-wide listing.
Stable sorting and field ignoring for comparison.
Test_databaseService_AppendEvent
Tests the AppendEvent method of the databaseService.
Purpose: Validate appending events to sessions, state delta application, and persistence behaviors.
Parameters: Same as above.
Test Cases:
Append new event to session without existing events.
Append new event to session with existing events.
Append event to non-existent session (expect error).
Append event with content as bytes (including grounding metadata).
Append event with all possible fields filled.
Append partial event (should not persist).
Assertions:
Event counts in storage match expected.
Session state merged correctly with event
StateDelta.Partial events are not persisted.
Complex event metadata is stored and retrieved correctly.
Errors returned appropriately for invalid cases.
Test_databaseService_StateManagement
Tests the scoping and persistence of session state at different levels.
Purpose: Verify that state prefixed with app:,
user:, and non-prefixed keys behave as expected in persistence and sharing.Sub-tests:
"app_state_is_shared": App-scoped state is shared across users/sessions in the same app.
"user_state_is_user_specific": User-scoped state is shared only among sessions of the same user.
"session_state_is_not_shared": Session-specific state is isolated per session.
"temp_state_is_not_persisted": Temporary state keys (
temp:prefix) are not persisted and are filtered out from events.
Assertions:
State maps after event appends reflect correct scoping and merging.
Temporary state keys are excluded from persistence and storage.
Cross-user state isolation is enforced.
Helper Functions
serviceDbWithData
Purpose: Provides a
databaseServiceinstance pre-populated with sample sessions and events.Usage: Used to set up a test database state for test cases requiring existing data.
Implementation Details:
Calls
emptyServiceto create fresh service.Creates multiple
localSessioninstances with predefined app/user/session IDs and state.Appends events to sessions if present.
Uses
CreateandAppendEventto persist data.
emptyService
Purpose: Creates a fresh
databaseServicewith an in-memory SQLite database for isolated testing.Usage: Used as setup for tests needing an empty database.
Implementation Details:
Opens SQLite connection with shared cache.
Calls NewSessionService to instantiate service.
Runs GORM automigration.
Registers cleanup function to delete all rows from tables and close DB connection after test.
Deletes tables in child-to-parent order to satisfy foreign key constraints.
Closes underlying SQL DB connection on cleanup.
Important Implementation Details and Algorithms
Transactional Operations: All database mutations (
Create,AppendEvent) are performed inside GORM transactions to ensure atomicity and consistency.State Delta Extraction: State deltas are separated into app, user, and session scopes based on key prefixes (app:,
user:, or none). Temporary keys (temp:prefix) are filtered out before persistence.Event Filtering: Events can be filtered by timestamp (After) and limited by count (NumRecentEvents) when retrieved.
Partial Event Handling: Events marked as partial (
Partial: true) are ignored and not persisted to prevent storing incomplete data.Session Staleness Check: Appending events includes a check against session's last update time to avoid overwriting more recent changes, ensuring concurrency correctness.
State Merging: On retrieval, app and user states are merged with session state with prefixed keys to provide a unified view.
Event Ordering: Events are stored and retrieved in timestamp order; tests sort events before comparison to handle potential order changes.
Interaction with Other Parts of the System
This test file validates the core database-backed session service implementation described in the Database Session Service subtopic.
It indirectly exercises components of the Session Management topic by ensuring persistence, retrieval, and state management correctness.
The service under test is a backend used by higher-level components such as the Agent Execution Runner, which relies on session state and events for agent context.
The stored session events may contain references and metadata related to artifacts handled by the Artifact Management system.
The tests ensure compliance with protocols and data structures defined in the broader session and event models within the system.
Visual Diagram of the File Structure and Test Workflow
flowchart TD
A[Test_databaseService_Create]
B[Test_databaseService_Delete]
C[Test_databaseService_Get]
D[Test_databaseService_List]
E[Test_databaseService_AppendEvent]
F[Test_databaseService_StateManagement]
G[Helper: emptyService]
H[Helper: serviceDbWithData]
A --> G
B --> H
C --> H
C --> G
D --> H
E --> H
E --> G
F --> G
F --> H
Each test function represents a core session service operation tested.
emptyServiceandserviceDbWithDataare shared helpers used for test setup.Tests depend on these helpers to provide clean or pre-populated database states.
The diagram highlights the modular structure of tests and their shared setup dependencies.
Usage Example Snippet
The following illustrates an example usage of Create and AppendEvent tested in this file:
ctx := context.Background()
s := emptyService(t)
// Create a new session with initial state
createResp, err := s.Create(ctx, &session.CreateRequest{
AppName: "my_app",
UserID: "user1",
State: map[string]any{"k1": "v1"},
})
if err != nil {
t.Fatal(err)
}
sess := createResp.Session.(*localSession)
// Append an event with state delta
event := &session.Event{
ID: "evt1",
Actions: session.EventActions{
StateDelta: map[string]any{"k2": "v2"},
},
LLMResponse: model.LLMResponse{},
}
err = s.AppendEvent(ctx, sess, event)
if err != nil {
t.Fatal(err)
}
// Retrieve session and verify state
getResp, err := s.Get(ctx, &session.GetRequest{
AppName: "my_app",
UserID: "user1",
SessionID: sess.ID(),
})
if err != nil {
t.Fatal(err)
}
state := maps.Collect(getResp.Session.State().All())
// state should include "k1":"v1" and "k2":"v2"
This example corresponds closely to the tested flows in the file, demonstrating session lifecycle and event-driven state updates.
This documentation references the broader Session Management topic for core concepts and the Database Session Service for backend implementation details. The tests in this file directly verify the database-backed service's compliance with the session service interface and correctness in state/event management.