diff --git a/README.md b/README.md index 4f89d29..383a24d 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ Runnable companion code for the Spring AI articles on [ankurm.com](https://ankur | [`structured-output/`](structured-output) | `ChatClient.entity()` mapping LLM responses to Java records, lists and maps; `StructuredOutputValidationAdvisor` retrying non-conforming JSON with a real enum-constrained schema, including a captured run that exhausts every retry without throwing. Spring Boot 4.1.1, Spring AI 2.0.1, Java 25. | [Structured Output in Spring AI 2.0](https://ankurm.com/spring-ai-2-0-structured-output/) | | [`ollama-local/`](ollama-local) | Chat and embeddings against a real local `qwen2.5:0.5b`/`all-minilm`, no API key, driven by a Testcontainers-managed Ollama container started from a baked image; a confirmed model unload via `keep_alive: 0` and `/api/ps`, not a scripted model anywhere. Spring Boot 4.1.1, Spring AI 2.0.1, Testcontainers 2.0.5, Java 25. | [Run LLMs Locally with Spring AI and Ollama](https://ankurm.com/spring-ai-2-0-ollama-local/) | | [`chat-memory/`](chat-memory) | `MessageChatMemoryAdvisor`, `MessageWindowChatMemory`, the JDBC and Redis `ChatMemoryRepository`, per-user conversation IDs and a token-budget memory of our own, with the traps reproduced against a real PostgreSQL 16 and Redis Stack: a 36-character `conversation_id`, tool messages dropped on save, concurrent writers, a 1.x table under the 2.0 repository, and a Redis repository that silently steps aside for a custom `ChatMemory`. Spring Boot 4.1.1, Spring AI 2.0.1, Java 25. | [Chat Memory in Spring AI 2.0: JDBC, Redis and Windowed Conversations](https://ankurm.com/spring-ai-2-0-chat-memory-jdbc-redis-windowed-conversations/) | +| [`session-memory/`](session-memory) | The Spring AI 2.1 Session API that replaces `ChatMemory`: the append-only event log, turn-aware windows, `WindowCompactionStrategy` with a `ChatModelSummarizer`, `SessionAdvisors` on a `ChatClient`, the JDBC repository on a real PostgreSQL 16, and the 2.0 `ChatMemory` deprecation warnings captured from `javac`. Spring Boot 4.1.1, Spring AI 2.1.0, Java 25. | [Chat Memory to Session Memory in Spring AI 2.1](https://ankurm.com/spring-ai-2-0-chat-memory-jdbc-redis-windowed-conversations/) | | [`advisors/`](advisors) | Three custom advisors -- a logger, a PII redactor (with a stream-safe restore) and a per-request / per-user token budget -- and tests for how the chain is ordered, what `BaseAdvisor` does on a stream, where an advisor sits relative to memory and the tool loop, and what a refusal looks like on a call, a stream and over HTTP (429). A recording stub model, no live model. Spring Boot 4.1.1, Spring AI 2.0.1, Java 25. | [Writing Custom Advisors in Spring AI 2.0: Logging, PII Redaction and Token Budgets](https://ankurm.com/spring-ai-2-0-custom-advisors-logging-pii-redaction-token-budgets/) | | [`vector-stores/`](vector-stores) | The same 30,000-document dataset behind `VectorStore` on pgvector, Redis, Qdrant and Elasticsearch: ingest time, recall@10, latency, metadata filtering and running cost, with the defaults that cost recall reproduced (Elasticsearch's quantised mapping, Redis `EF_RUNTIME`, pgvector post-filtering, Qdrant payload indexes). Spring Boot 4.1.1, Spring AI 2.0.1, Java 25. | [Choosing a Vector Store for Spring AI](https://ankurm.com/spring-ai-2-0-vector-store-comparison-pgvector-redis-qdrant-elasticsearch/) | | [`evaluation/`](evaluation) | Testing an LLM app: `RelevancyEvaluator` and `FactCheckingEvaluator` (exactly what they send and which judge replies they accept), a 12-case golden dataset with a pass-rate gate, a deterministic judge for CI, simulated judge noise, a 1-5 graded evaluator and a composite. Stub models only; the one live-judge test is skipped without a key. Spring Boot 4.1.1, Spring AI 2.0.1, JUnit 6, Java 25. | [Testing LLM Apps in Java: Spring AI Evaluators and LLM-as-Judge in JUnit 6](https://ankurm.com/spring-ai-2-0-testing-llm-apps-evaluators-llm-as-judge-junit-6/) | diff --git a/session-memory/.gitignore b/session-memory/.gitignore new file mode 100644 index 0000000..2f7896d --- /dev/null +++ b/session-memory/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/session-memory/README.md b/session-memory/README.md new file mode 100644 index 0000000..6f17a19 --- /dev/null +++ b/session-memory/README.md @@ -0,0 +1,34 @@ +# session-memory + +Companion code for [Chat Memory to Session Memory in Spring AI 2.1](https://ankurm.com/spring-ai-2-0-chat-memory-jdbc-redis-windowed-conversations/), part of the [Spring AI series](../README.md) on ankurm.com. + +The Spring AI 2.1 Session API that replaces `ChatMemory` (deprecated for removal in 3.0): an append-only event log, turn-aware windows, compaction with an optional summarizer, `SessionAdvisors` on a `ChatClient`, and the JDBC repository on PostgreSQL. Every claim in the article is a test that writes its own transcript under [`output/`](output). + +There is no live model anywhere: `FixedReplyModel` and `ScriptedChatModel` (under `src/test`) record the prompts they are sent, which is what a memory test has to prove -- *which messages reached the model*. The database is a real PostgreSQL 16. + +## Versions + +| Component | Version | +|---|---| +| Spring Boot | 4.1.1 | +| Spring AI | 2.1.0 (modules `spring-ai-session`, `spring-ai-session-advisor`, `spring-ai-session-jdbc`, starter `spring-ai-starter-model-session-jdbc`) | +| PostgreSQL | 16.15 | +| Java | 25 (LTS) | + +## Quickstart + +```bash +scripts/services-up.sh # PostgreSQL 16 (apt) on :5440 -- only for outputs 10 and 11 +scripts/run-all.sh # runs the tests and regenerates output/01 .. 14 +``` + +Tests that need PostgreSQL are **skipped with a message**, not failed, when nothing listens on 5440. Two consecutive full runs produce byte-identical files. + +## What's here + +| File | What it shows | +|---|---| +| [`SessionWiring.java`](src/main/java/com/ankurm/sessionmemory/SessionWiring.java) | The one-call replacement for `ChatMemory` + `MessageChatMemoryAdvisor` | +| [`ExpiredSessionCleaner.java`](src/main/java/com/ankurm/sessionmemory/ExpiredSessionCleaner.java) | The scheduler `deleteExpiredSessions` requires | +| [`src/broken/LegacyChatMemory.java`](src/broken/LegacyChatMemory.java) | The 2.0 setup; not part of the build, `scripts/capture-deprecations.sh` compiles it with `-Xlint:deprecation` | +| `src/test/.../*Test.java` | One test class per transcript in `output/` | diff --git a/session-memory/output/01-event-log.txt b/session-memory/output/01-event-log.txt new file mode 100644 index 0000000..aacd5c3 --- /dev/null +++ b/session-memory/output/01-event-log.txt @@ -0,0 +1,31 @@ +# A session is an append-only log; the active view is a projection of it + +After 5 turns, the log holds 10 events and the model would see 10 messages: + 1 MESSAGE U:u1 + 2 MESSAGE A:a1 + 3 MESSAGE U:u2 + 4 MESSAGE A:a2 + 5 MESSAGE U:u3 + 6 MESSAGE A:a3 + 7 MESSAGE U:u4 + 8 MESSAGE A:a4 + 9 MESSAGE U:u5 + 10 MESSAGE A:a5 + +compact(trigger: more than 3 turns, strategy: keep last 2 turns): + unchanged=false covered=6 preserved=4 pinned=0 + +The log now holds 11 events (nothing was removed, one COMPACTION boundary was appended): + 1 MESSAGE U:u1 + 2 MESSAGE A:a1 + 3 MESSAGE U:u2 + 4 MESSAGE A:a2 + 5 MESSAGE U:u3 + 6 MESSAGE A:a3 + 7 MESSAGE U:u4 + 8 MESSAGE A:a4 + 9 MESSAGE U:u5 + 10 MESSAGE A:a5 + 11 COMPACTION payload=[coveredEventCount, pinnedEventIds, preservedEventIds, strategy, summaryEventIds, tokensEstimatedSaved] + +The active view (what the next prompt starts from): U:u4 | A:a4 | U:u5 | A:a5 diff --git a/session-memory/output/02-turn-aware-window.txt b/session-memory/output/02-turn-aware-window.txt new file mode 100644 index 0000000..f7e5f0a --- /dev/null +++ b/session-memory/output/02-turn-aware-window.txt @@ -0,0 +1,8 @@ +# EventFilter.lastN extends back to the start of its turn + +Log: U:u1 | A:a1 | U:weather in Pune? | A:[tool call weather] | T:[tool result 31C] | A:31C in Pune. | U:u2 | A:a2 + lastN(1) -> 2 messages: U:u2 | A:a2 + lastN(2) -> 2 messages: U:u2 | A:a2 + lastN(3) -> 6 messages: U:weather in Pune? | A:[tool call weather] | T:[tool result 31C] | A:31C in Pune. | U:u2 | A:a2 + lastN(4) -> 6 messages: U:weather in Pune? | A:[tool call weather] | T:[tool result 31C] | A:31C in Pune. | U:u2 | A:a2 + lastN(5) -> 6 messages: U:weather in Pune? | A:[tool call weather] | T:[tool result 31C] | A:31C in Pune. | U:u2 | A:a2 diff --git a/session-memory/output/03-compaction-keeps-tool-turns.txt b/session-memory/output/03-compaction-keeps-tool-turns.txt new file mode 100644 index 0000000..c587ac1 --- /dev/null +++ b/session-memory/output/03-compaction-keeps-tool-turns.txt @@ -0,0 +1,6 @@ +# Compaction cuts between turns, so a tool call stays with its result + +Before: U:u1 | A:a1 | U:u2 | A:a2 | U:weather in Pune? | A:[tool call weather] | T:[tool result 31C] | A:31C in Pune. | U:u3 | A:a3 +compact(keep last 3 EVENTS): covered=8 preserved=2 +After: U:u3 | A:a3 +The last 3 events would have started at the assistant reply "31C in Pune.", which is mid-turn, so the cut moved forward to the next turn start (u3). diff --git a/session-memory/output/04-summarizer.txt b/session-memory/output/04-summarizer.txt new file mode 100644 index 0000000..9d1008c --- /dev/null +++ b/session-memory/output/04-summarizer.txt @@ -0,0 +1,15 @@ +# WindowCompactionStrategy with a ChatModelSummarizer + +covered=6 preserved=4 summary messages=2 + +Active view after compaction: + 1 MESSAGE U:Summarize the conversation we had so far. (synthetic) + 2 MESSAGE A:SUMMARY: user is Asha, asked about turns 1-3. (synthetic) + 3 MESSAGE U:u4 + 4 MESSAGE A:a4 + 5 MESSAGE U:u5 + 6 MESSAGE A:a5 + +Messages the summarizer model was sent (1 call): + S:You are a conversation summarizer. Your task is to create a concise summary of the conve ... + U:=== CONVERSATION TO SUMMARIZE === / User: u1 / Assistant: a1 / User: u2 / Assistant: a2 ... diff --git a/session-memory/output/05-advisors.txt b/session-memory/output/05-advisors.txt new file mode 100644 index 0000000..f9773fd --- /dev/null +++ b/session-memory/output/05-advisors.txt @@ -0,0 +1,15 @@ +# SessionAdvisors on a ChatClient, scripted model + +alice> My name is Asha +model< Nice to meet you, Asha. +bob> My name is Bala +model< Nice to meet you, Bala. +alice> What is my name? +model< Your name is Asha. +bob> What is my name? +model< Your name is Bala. + +Messages sent to the model on its 3rd call (alice's second question): + U:My name is Asha | A:Nice to meet you, Asha. | U:What is my name? + +Alice's stored log: U:My name is Asha | A:Nice to meet you, Asha. | U:What is my name? | A:Your name is Asha. diff --git a/session-memory/output/06-advisor-compaction.txt b/session-memory/output/06-advisor-compaction.txt new file mode 100644 index 0000000..fe28ed8 --- /dev/null +++ b/session-memory/output/06-advisor-compaction.txt @@ -0,0 +1,11 @@ +# TurnCountTrigger(3) + lastTurns(2) through the advisors + +after turn 1: log= 2 events, model would see 2 messages +after turn 2: log= 4 events, model would see 4 messages +after turn 3: log= 6 events, model would see 6 messages +after turn 4: log= 9 events, model would see 4 messages +after turn 5: log=11 events, model would see 6 messages +after turn 6: log=14 events, model would see 4 messages + +Prompt sent on turn 6: U:question 3 | A:Noted. | U:question 4 | A:Noted. | U:question 5 | A:Noted. | U:question 6 +Active view after turn 6: U:question 5 | A:Noted. | U:question 6 | A:Noted. diff --git a/session-memory/output/07-missing-session-id.txt b/session-memory/output/07-missing-session-id.txt new file mode 100644 index 0000000..46d0738 --- /dev/null +++ b/session-memory/output/07-missing-session-id.txt @@ -0,0 +1,4 @@ +# No session id on the request + +IllegalStateException: No session ID found in advisor context. Set SESSION_ID_CONTEXT_KEY on every request: .advisors(a -> a.param(SessionMemoryAdvisor.SESSION_ID_CONTEXT_KEY, sessionId)) +Model calls made: 0 diff --git a/session-memory/output/08-system-messages.txt b/session-memory/output/08-system-messages.txt new file mode 100644 index 0000000..c918def --- /dev/null +++ b/session-memory/output/08-system-messages.txt @@ -0,0 +1,6 @@ +# SystemMessage in a session + +allowSystemMessages(false) [default]: IllegalArgumentException: Storing a SystemMessage in session 'x' is disabled. System prompts are configuration: supply them on every request (e.g. ChatClient defaultSystem/.system, or your own prompt builder) and keep per-session settings in Session.metadata. To store system messages anyway, use DefaultSessionService.builder().allowSystemMessages(true) or set spring.ai.session.allow-system-messages=true. See the "System Messages" reference page. + +allowSystemMessages(true), 4 turns, then compact(lastTurns(1)): + active view: S:You are terse. | U:u4 | A:a4 diff --git a/session-memory/output/09-idempotent-and-versioned-appends.txt b/session-memory/output/09-idempotent-and-versioned-appends.txt new file mode 100644 index 0000000..df88904 --- /dev/null +++ b/session-memory/output/09-idempotent-and-versioned-appends.txt @@ -0,0 +1,8 @@ +# Retries and compare-and-swap appends + +version before append: 0, after append: 1, after retrying the SAME event: 1 +events in log: 1 + +appendEvents(expectedVersion = 0, which is stale): false +appendEvents(expectedVersion = 1, which is current): true +events in log: 2 diff --git a/session-memory/output/10-jdbc-round-trip.txt b/session-memory/output/10-jdbc-round-trip.txt new file mode 100644 index 0000000..6bbd9c8 --- /dev/null +++ b/session-memory/output/10-jdbc-round-trip.txt @@ -0,0 +1,22 @@ +# JdbcSessionRepository on PostgreSQL 16 + +service: DefaultSessionService, repository: JdbcSessionRepository +tables: [ai_session, ai_session_event, ai_session_index] + +select seq order, event_type, message_type, message_content, synthetic from ai_session_event: + 1 MESSAGE USER u1 false + 2 MESSAGE ASSISTANT a1 false + 3 MESSAGE USER u2 false + 4 MESSAGE ASSISTANT a2 false + 5 MESSAGE USER u3 false + 6 MESSAGE ASSISTANT a3 false + 7 MESSAGE USER u4 false + 8 MESSAGE ASSISTANT a4 false + 9 MESSAGE USER u5 false + 10 MESSAGE ASSISTANT a5 false + 11 COMPACTION null null false + +A second SessionService on the same repository (a stand-in for a restart): + active view: U:u4 | A:a4 | U:u5 | A:a5 + whole log: 11 events + findByMetadata(principalName, asha): [jdbc-1] diff --git a/session-memory/output/11-autoconfigured-defaults.txt b/session-memory/output/11-autoconfigured-defaults.txt new file mode 100644 index 0000000..71ec34b --- /dev/null +++ b/session-memory/output/11-autoconfigured-defaults.txt @@ -0,0 +1,4 @@ +# What the autoconfiguration gives you with no properties + +default time-to-live: 60 days +SystemMessage append: IllegalArgumentException diff --git a/session-memory/output/12-chatmemory-deprecations.txt b/session-memory/output/12-chatmemory-deprecations.txt new file mode 100644 index 0000000..4860fcb --- /dev/null +++ b/session-memory/output/12-chatmemory-deprecations.txt @@ -0,0 +1,19 @@ +# javac -Xlint:deprecation on the Spring AI 2.0 ChatMemory setup, compiled against Spring AI 2.1.0 + +$ javac -Xlint:deprecation -cp <2.1.0 classpath> src/broken/LegacyChatMemory.java +LegacyChatMemory.java:12: warning: [removal] ChatMemory in org.springframework.ai.chat.memory has been deprecated and marked for removal + ChatMemory memory = MessageWindowChatMemory.builder() + ^ +LegacyChatMemory.java:13: warning: [removal] InMemoryChatMemoryRepository in org.springframework.ai.chat.memory has been deprecated and marked for removal + .chatMemoryRepository(new InMemoryChatMemoryRepository()) + ^ +LegacyChatMemory.java:12: warning: [removal] MessageWindowChatMemory in org.springframework.ai.chat.memory has been deprecated and marked for removal + ChatMemory memory = MessageWindowChatMemory.builder() + ^ +LegacyChatMemory.java:17: warning: [removal] MessageChatMemoryAdvisor in org.springframework.ai.chat.client.advisor has been deprecated and marked for removal + .defaultAdvisors(MessageChatMemoryAdvisor.builder(memory).build()) + ^ +LegacyChatMemory.java:20: warning: [removal] ChatMemory in org.springframework.ai.chat.memory has been deprecated and marked for removal + .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, conversationId)) + ^ +5 warnings diff --git a/session-memory/output/13-migration-keys.txt b/session-memory/output/13-migration-keys.txt new file mode 100644 index 0000000..5e9213e --- /dev/null +++ b/session-memory/output/13-migration-keys.txt @@ -0,0 +1,9 @@ +# ChatMemory.CONVERSATION_ID against SessionMemoryAdvisor.SESSION_ID_CONTEXT_KEY + +ChatMemory.CONVERSATION_ID = chat_memory_conversation_id +MemoryAdvisor.CONVERSATION_ID = chat_memory_conversation_id +SessionMemoryAdvisor.SESSION_ID_CONTEXT_KEY = chat_memory_conversation_id + +Two calls with the 2.0 parameter name, SessionAdvisors on the client: + model< Your name is Asha. + session 'legacy-key' holds: U:My name is Asha | A:Nice to meet you, Asha. | U:What is my name? | A:Your name is Asha. diff --git a/session-memory/output/14-expiry.txt b/session-memory/output/14-expiry.txt new file mode 100644 index 0000000..d9999e9 --- /dev/null +++ b/session-memory/output/14-expiry.txt @@ -0,0 +1,6 @@ +# timeToLive and deleteExpiredSessions + +Two hours from now, 'short' (ttl 1h) is past its expiresAt; 'long' (ttl 30d) is not. +Before the cleaner: findById(short) = present, events = 2 +deleteExpiredSessions(now + 2h) removed 1 session(s) +After: findById(short) = null, findById(long) = present diff --git a/session-memory/pom.xml b/session-memory/pom.xml new file mode 100644 index 0000000..e795e38 --- /dev/null +++ b/session-memory/pom.xml @@ -0,0 +1,87 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.1.1 + + + + com.ankurm + session-memory + 1.0.0 + session-memory + Session memory in Spring AI 2.1: event log, turn-aware windows, compaction with a summarizer, SessionAdvisors and the JDBC repository, measured against ChatMemory. + + + 25 + 2.1.0 + + + + + + org.springframework.ai + spring-ai-bom + ${spring-ai.version} + pom + import + + + + + + + org.springframework.ai + spring-ai-client-chat + + + org.springframework.ai + spring-ai-session + + + org.springframework.ai + spring-ai-session-advisor + + + org.springframework.ai + spring-ai-starter-model-session-jdbc + + + org.postgresql + postgresql + runtime + + + com.h2database + h2 + runtime + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + + -Duser.timezone=UTC -Dstdout.encoding=UTF-8 -Dfile.encoding=UTF-8 + + + + + diff --git a/session-memory/scripts/capture-deprecations.sh b/session-memory/scripts/capture-deprecations.sh new file mode 100755 index 0000000..84fcc10 --- /dev/null +++ b/session-memory/scripts/capture-deprecations.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# Compiles src/broken/LegacyChatMemory.java (the 2.0 ChatMemory setup) against Spring AI 2.1.0 with +# -Xlint:deprecation and keeps the compiler's own words in output/12-chatmemory-deprecations.txt. +set -euo pipefail +cd "$(dirname "$0")/.." +mvn -q -B dependency:build-classpath -Dmdep.outputFile=target/cp.txt >/dev/null 2>&1 +mkdir -p target/legacy output +{ + echo "# javac -Xlint:deprecation on the Spring AI 2.0 ChatMemory setup, compiled against Spring AI 2.1.0" + echo + echo '$ javac -Xlint:deprecation -cp <2.1.0 classpath> src/broken/LegacyChatMemory.java' + javac -Xlint:deprecation -d target/legacy -cp "$(cat target/cp.txt)" src/broken/LegacyChatMemory.java 2>&1 \ + | grep -v '^Picked up' | sed 's#^src/broken/##' | sed 's/\.\.\. [0-9a-f]*$//' +} > output/12-chatmemory-deprecations.txt +cat output/12-chatmemory-deprecations.txt diff --git a/session-memory/scripts/run-all.sh b/session-memory/scripts/run-all.sh new file mode 100755 index 0000000..0ce9bfe --- /dev/null +++ b/session-memory/scripts/run-all.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# Regenerates every file under output/. The test suite writes 01-11, 13 and 14 through the Transcript +# helper; 12 comes from scripts/capture-deprecations.sh. Tests that need PostgreSQL are SKIPPED (not +# failed) when nothing listens on 127.0.0.1:5440 -- run scripts/services-up.sh first for 10 and 11. +set -euo pipefail +cd "$(dirname "$0")/.." +rm -rf target output +mvn -q -B test +scripts/capture-deprecations.sh >/dev/null +ls output diff --git a/session-memory/scripts/services-up.sh b/session-memory/scripts/services-up.sh new file mode 100755 index 0000000..a16f41b --- /dev/null +++ b/session-memory/scripts/services-up.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# Starts PostgreSQL 16 on 127.0.0.1:5440 (apt: postgresql-16, runs as the postgres user, database chatdb, role chat/chat). +# If you already have PostgreSQL, skip this and set SM_PG_URL to your JDBC URL. +set -euo pipefail +PGDATA="${PGDATA:-/tmp/pgchat/data}"; PGPORT="${PGPORT:-5440}"; SOCKDIR="$(dirname "$PGDATA")" +BIN="$(ls -d /usr/lib/postgresql/*/bin 2>/dev/null | sort -V | tail -1)" +as_pg() { if [ "$(id -u)" = 0 ]; then su postgres -c "$*"; else bash -c "$*"; fi; } +mkdir -p "$SOCKDIR"; [ "$(id -u)" = 0 ] && chown postgres "$SOCKDIR" +[ -d "$PGDATA/base" ] || as_pg "'$BIN/initdb' -D '$PGDATA' -A trust >'$SOCKDIR/initdb.log' 2>&1" +as_pg "'$BIN/pg_ctl' -D '$PGDATA' status" >/dev/null 2>&1 || \ + as_pg "'$BIN/pg_ctl' -D '$PGDATA' -o \"-p $PGPORT -c listen_addresses=127.0.0.1 -c unix_socket_directories=$SOCKDIR\" -l '$SOCKDIR/pg.log' -w start" +PSQL="$BIN/psql -h $SOCKDIR -p $PGPORT -U postgres -v ON_ERROR_STOP=1 -q" +as_pg "$PSQL -d postgres -tc \"select 1 from pg_roles where rolname='chat'\"" | grep -q 1 || as_pg "$PSQL -d postgres -c \"create role chat login superuser password 'chat'\"" +as_pg "$PSQL -d postgres -tc \"select 1 from pg_database where datname='chatdb'\"" | grep -q 1 || as_pg "$PSQL -d postgres -c 'create database chatdb owner chat'" +echo "postgres 127.0.0.1:$PGPORT (chatdb / chat / chat)" diff --git a/session-memory/src/broken/LegacyChatMemory.java b/session-memory/src/broken/LegacyChatMemory.java new file mode 100644 index 0000000..3b51548 --- /dev/null +++ b/session-memory/src/broken/LegacyChatMemory.java @@ -0,0 +1,23 @@ +import org.springframework.ai.chat.client.ChatClient; +import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor; +import org.springframework.ai.chat.memory.ChatMemory; +import org.springframework.ai.chat.memory.InMemoryChatMemoryRepository; +import org.springframework.ai.chat.memory.MessageWindowChatMemory; +import org.springframework.ai.chat.model.ChatModel; + +/** The 2.0 way of keeping a conversation. Compiles on 2.1.0, with deprecation warnings. Not part of the build. */ +class LegacyChatMemory { + + String ask(ChatModel model, String conversationId, String text) { + ChatMemory memory = MessageWindowChatMemory.builder() + .chatMemoryRepository(new InMemoryChatMemoryRepository()) + .maxMessages(20) + .build(); + ChatClient chat = ChatClient.builder(model) + .defaultAdvisors(MessageChatMemoryAdvisor.builder(memory).build()) + .build(); + return chat.prompt().user(text) + .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, conversationId)) + .call().content(); + } +} diff --git a/session-memory/src/main/java/com/ankurm/sessionmemory/ExpiredSessionCleaner.java b/session-memory/src/main/java/com/ankurm/sessionmemory/ExpiredSessionCleaner.java new file mode 100644 index 0000000..198a9a8 --- /dev/null +++ b/session-memory/src/main/java/com/ankurm/sessionmemory/ExpiredSessionCleaner.java @@ -0,0 +1,26 @@ +package com.ankurm.sessionmemory; + +import java.time.Instant; + +import org.springframework.ai.session.SessionService; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +/** + * Nothing in Spring AI deletes expired sessions by itself: {@code deleteExpiredSessions} "must be + * called from a scheduler". This is that scheduler. Enable it with {@code @EnableScheduling}. + */ +@Component +public class ExpiredSessionCleaner { + + private final SessionService sessions; + + public ExpiredSessionCleaner(SessionService sessions) { + this.sessions = sessions; + } + + @Scheduled(fixedDelayString = "PT1H") + public int purge() { + return sessions.deleteExpiredSessions(Instant.now()); + } +} diff --git a/session-memory/src/main/java/com/ankurm/sessionmemory/SessionMemoryApplication.java b/session-memory/src/main/java/com/ankurm/sessionmemory/SessionMemoryApplication.java new file mode 100644 index 0000000..4ce11bb --- /dev/null +++ b/session-memory/src/main/java/com/ankurm/sessionmemory/SessionMemoryApplication.java @@ -0,0 +1,12 @@ +package com.ankurm.sessionmemory; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SessionMemoryApplication { + + public static void main(String[] args) { + SpringApplication.run(SessionMemoryApplication.class, args); + } +} diff --git a/session-memory/src/main/java/com/ankurm/sessionmemory/SessionWiring.java b/session-memory/src/main/java/com/ankurm/sessionmemory/SessionWiring.java new file mode 100644 index 0000000..6028755 --- /dev/null +++ b/session-memory/src/main/java/com/ankurm/sessionmemory/SessionWiring.java @@ -0,0 +1,27 @@ +package com.ankurm.sessionmemory; + +import org.springframework.ai.chat.client.ChatClient; +import org.springframework.ai.chat.model.ChatModel; +import org.springframework.ai.session.SessionService; +import org.springframework.ai.session.advisor.SessionAdvisors; +import org.springframework.ai.session.compaction.TurnCountTrigger; +import org.springframework.ai.session.compaction.WindowCompactionStrategy; + +/** + * The whole 2.1 replacement for "a ChatMemory bean plus MessageChatMemoryAdvisor": one + * {@code SessionAdvisors} call that registers the turn advisor (outside the tool loop, runs + * compaction) and the memory advisor (inside the loop, loads and stores messages). + */ +public final class SessionWiring { + + private SessionWiring() { + } + + public static ChatClient chatClient(ChatModel model, SessionService sessions) { + return ChatClient.builder(model) + .defaultAdvisors(SessionAdvisors.builder(sessions) + .compaction(new TurnCountTrigger(3), WindowCompactionStrategy.builder().lastTurns(2).build()) + .build()) + .build(); + } +} diff --git a/session-memory/src/main/resources/application.yml b/session-memory/src/main/resources/application.yml new file mode 100644 index 0000000..326fe97 --- /dev/null +++ b/session-memory/src/main/resources/application.yml @@ -0,0 +1,12 @@ +spring: + application: + name: session-memory + datasource: + url: ${SM_PG_URL:jdbc:postgresql://127.0.0.1:5440/chatdb} + username: chat + password: chat + ai: + session: + repository: + jdbc: + initialize-schema: always diff --git a/session-memory/src/test/java/com/ankurm/sessionmemory/AdvisorTest.java b/session-memory/src/test/java/com/ankurm/sessionmemory/AdvisorTest.java new file mode 100644 index 0000000..f120338 --- /dev/null +++ b/session-memory/src/test/java/com/ankurm/sessionmemory/AdvisorTest.java @@ -0,0 +1,71 @@ +package com.ankurm.sessionmemory; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.ankurm.sessionmemory.support.ScriptedChatModel; +import com.ankurm.sessionmemory.support.Show; +import com.ankurm.sessionmemory.support.Transcript; +import org.junit.jupiter.api.Test; +import org.springframework.ai.chat.client.ChatClient; +import org.springframework.ai.session.DefaultSessionService; +import org.springframework.ai.session.EventFilter; +import org.springframework.ai.session.InMemorySessionRepository; +import org.springframework.ai.session.SessionService; +import org.springframework.ai.session.advisor.SessionAdvisors; + +/** SessionAdvisors on a ChatClient: what reaches the model, session isolation, and the mandatory session id. */ +class AdvisorTest { + + private final ScriptedChatModel model = new ScriptedChatModel(); + private final SessionService service = DefaultSessionService.builder() + .sessionRepository(InMemorySessionRepository.builder().build()).build(); + private final ChatClient chat = SessionWiring.chatClient(model, service); + + private String ask(String session, String text) { + return chat.prompt().user(text).advisors(SessionAdvisors.session(session)).call().content(); + } + + @Test + void sessionsAreIsolatedAndHistoryReachesTheModel() { + try (Transcript t = new Transcript("05-advisors.txt", "SessionAdvisors on a ChatClient, scripted model")) { + t.line("alice> %s", "My name is Asha"); + t.line("model< %s", ask("alice", "My name is Asha")); + t.line("bob> %s", "My name is Bala"); + t.line("model< %s", ask("bob", "My name is Bala")); + t.line("alice> %s", "What is my name?"); + t.line("model< %s", ask("alice", "What is my name?")); + t.line("bob> %s", "What is my name?"); + t.line("model< %s", ask("bob", "What is my name?")); + t.blank().line("Messages sent to the model on its 3rd call (alice's second question):"); + t.line(" %s", Show.inline(model.prompts().get(2).getInstructions())); + t.blank().line("Alice's stored log: %s", Show.inline(service.getMessages("alice"))); + assertThat(Show.inline(model.prompts().get(2).getInstructions())).isEqualTo("U:My name is Asha | A:Nice to meet you, Asha. | U:What is my name?"); + assertThat(Show.inline(service.getMessages("bob"))).contains("Bala").doesNotContain("Asha"); + } + } + + @Test + void compactionRunsAfterTheCallAndTheWindowStaysTurnAligned() { + try (Transcript t = new Transcript("06-advisor-compaction.txt", "TurnCountTrigger(3) + lastTurns(2) through the advisors")) { + for (int n = 1; n <= 6; n++) { + ask("s", "question " + n); + t.line("after turn %d: log=%2d events, model would see %d messages", n, + service.getEvents("s", EventFilter.all()).size(), service.getActiveMessages("s").size()); + } + t.blank().line("Prompt sent on turn 6: %s", Show.inline(model.lastPrompt().getInstructions())); + t.line("Active view after turn 6: %s", Show.inline(service.getActiveMessages("s"))); + } + } + + @Test + void aMissingSessionIdFailsLoudly() { + try (Transcript t = new Transcript("07-missing-session-id.txt", "No session id on the request")) { + Throwable thrown = org.assertj.core.api.Assertions.catchThrowable(() -> chat.prompt().user("hello").call().content()); + t.line("%s: %s", thrown.getClass().getSimpleName(), thrown.getMessage()); + assertThat(thrown).isInstanceOf(IllegalStateException.class); + assertThat(model.prompts()).isEmpty(); + t.line("Model calls made: %d", model.prompts().size()); + } + } +} diff --git a/session-memory/src/test/java/com/ankurm/sessionmemory/CompactionTest.java b/session-memory/src/test/java/com/ankurm/sessionmemory/CompactionTest.java new file mode 100644 index 0000000..521361b --- /dev/null +++ b/session-memory/src/test/java/com/ankurm/sessionmemory/CompactionTest.java @@ -0,0 +1,103 @@ +package com.ankurm.sessionmemory; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import com.ankurm.sessionmemory.support.FixedReplyModel; +import com.ankurm.sessionmemory.support.Show; +import com.ankurm.sessionmemory.support.Transcript; +import com.ankurm.sessionmemory.support.Turns; +import org.junit.jupiter.api.Test; +import org.springframework.ai.chat.messages.AssistantMessage; +import org.springframework.ai.chat.messages.Message; +import org.springframework.ai.chat.messages.ToolResponseMessage; +import org.springframework.ai.chat.messages.UserMessage; +import org.springframework.ai.chat.messages.AssistantMessage.ToolCall; +import org.springframework.ai.session.CreateSessionRequest; +import org.springframework.ai.session.DefaultSessionService; +import org.springframework.ai.session.EventFilter; +import org.springframework.ai.session.InMemorySessionRepository; +import org.springframework.ai.session.SessionService; +import org.springframework.ai.session.compaction.ChatModelSummarizer; +import org.springframework.ai.session.compaction.TurnCountTrigger; +import org.springframework.ai.session.compaction.WindowCompactionStrategy; + +/** Turn-aware windows and compaction, including a tool-calling turn and a summarizer. */ +class CompactionTest { + + private static SessionService service(boolean systemMessages) { + return DefaultSessionService.builder().sessionRepository(InMemorySessionRepository.builder().build()) + .allowSystemMessages(systemMessages).build(); + } + + /** One turn that includes a tool call: user, assistant(tool call), tool result, assistant. */ + private static void toolTurn(SessionService s, String id) { + s.appendMessage(id, new UserMessage("weather in Pune?")); + s.appendMessage(id, AssistantMessage.builder().content("") + .toolCalls(List.of(new ToolCall("c1", "function", "weather", "{\"city\":\"Pune\"}"))).build()); + s.appendMessage(id, ToolResponseMessage.builder() + .responses(List.of(new ToolResponseMessage.ToolResponse("c1", "weather", "31C"))).build()); + s.appendMessage(id, new AssistantMessage("31C in Pune.")); + } + + @Test + void lastNNeverStartsMidTurn() { + try (Transcript t = new Transcript("02-turn-aware-window.txt", "EventFilter.lastN extends back to the start of its turn")) { + SessionService s = service(false); + s.create(CreateSessionRequest.builder().id("w").build()); + Turns.plain(s, "w", 1, 1); + toolTurn(s, "w"); + Turns.plain(s, "w", 2, 2); + t.line("Log: %s", Show.inline(s.getMessages("w"))); + for (int n : new int[] { 1, 2, 3, 4, 5 }) { + List got = s.getEvents("w", EventFilter.lastN(n)).stream().map(e -> e.getMessage()).toList(); + t.line(" lastN(%d) -> %d messages: %s", n, got.size(), Show.inline(got)); + } + assertThat(Show.inline(s.getEvents("w", EventFilter.lastN(3)).stream().map(e -> e.getMessage()).toList())) + .startsWith("U:"); + for (int n = 1; n <= 7; n++) { + assertThat(s.getEvents("w", EventFilter.lastN(n)).getFirst().isTurnStart()).isTrue(); + } + } + } + + @Test + void aToolTurnIsNeverSplitByCompaction() { + try (Transcript t = new Transcript("03-compaction-keeps-tool-turns.txt", "Compaction cuts between turns, so a tool call stays with its result")) { + SessionService s = service(false); + s.create(CreateSessionRequest.builder().id("c").build()); + Turns.plain(s, "c", 1, 2); + toolTurn(s, "c"); + Turns.plain(s, "c", 3, 3); + t.line("Before: %s", Show.inline(s.getActiveMessages("c"))); + var result = s.compact("c", new TurnCountTrigger(2), WindowCompactionStrategy.builder().lastEvents(3).build()); + t.line("compact(keep last 3 EVENTS): covered=%d preserved=%d", result.coveredEventCount(), result.preservedEvents().size()); + t.line("After: %s", Show.inline(s.getActiveMessages("c"))); + t.line("The last 3 events would have started at the assistant reply \"31C in Pune.\", which is mid-turn, so the cut moved forward to the next turn start (u3)."); + assertThat(s.getActiveMessages("c").getFirst()).isInstanceOf(UserMessage.class); + } + } + + @Test + void aSummarizerTurnsCoveredEventsIntoASummaryTurn() { + try (Transcript t = new Transcript("04-summarizer.txt", "WindowCompactionStrategy with a ChatModelSummarizer")) { + FixedReplyModel summarizer = new FixedReplyModel("SUMMARY: user is Asha, asked about turns 1-3."); + SessionService s = service(false); + s.create(CreateSessionRequest.builder().id("s").build()); + Turns.plain(s, "s", 1, 5); + var strategy = WindowCompactionStrategy.builder().lastTurns(2) + .summarizer(ChatModelSummarizer.builder(summarizer).build()).build(); + var result = s.compact("s", new TurnCountTrigger(3), strategy); + t.line("covered=%d preserved=%d summary messages=%d", result.coveredEventCount(), result.preservedEvents().size(), + result.summary().size()); + t.blank().line("Active view after compaction:"); + Show.log(t, s.getEvents("s", EventFilter.active())); + t.blank().line("Messages the summarizer model was sent (%d call):", summarizer.prompts().size()); + summarizer.prompts().getFirst().getInstructions().forEach(m -> { + String text = Show.brief(m).replace("\n", " / "); + t.line(" %s", text.length() > 90 ? text.substring(0, 90) + " ..." : text); + }); + } + } +} diff --git a/session-memory/src/test/java/com/ankurm/sessionmemory/ExpiryTest.java b/session-memory/src/test/java/com/ankurm/sessionmemory/ExpiryTest.java new file mode 100644 index 0000000..72684ba --- /dev/null +++ b/session-memory/src/test/java/com/ankurm/sessionmemory/ExpiryTest.java @@ -0,0 +1,40 @@ +package com.ankurm.sessionmemory; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Duration; +import java.time.Instant; + +import com.ankurm.sessionmemory.support.Transcript; +import com.ankurm.sessionmemory.support.Turns; +import org.junit.jupiter.api.Test; +import org.springframework.ai.session.CreateSessionRequest; +import org.springframework.ai.session.DefaultSessionService; +import org.springframework.ai.session.EventFilter; +import org.springframework.ai.session.InMemorySessionRepository; +import org.springframework.ai.session.SessionService; + +/** Expiry is a timestamp, not a timer: sessions past it stay readable until something deletes them. */ +class ExpiryTest { + + @Test + void expiredSessionsStayUntilTheCleanerRuns() { + try (Transcript t = new Transcript("14-expiry.txt", "timeToLive and deleteExpiredSessions")) { + SessionService s = DefaultSessionService.builder().sessionRepository(InMemorySessionRepository.builder().build()).build(); + s.create(CreateSessionRequest.builder().id("short").timeToLive(Duration.ofHours(1)).build()); + s.create(CreateSessionRequest.builder().id("long").timeToLive(Duration.ofDays(30)).build()); + Turns.plain(s, "short", 1, 1); + + Instant later = Instant.now().plus(Duration.ofHours(2)); + t.line("Two hours from now, 'short' (ttl 1h) is past its expiresAt; 'long' (ttl 30d) is not."); + t.line("Before the cleaner: findById(short) = %s, events = %d", s.findById("short") != null ? "present" : "null", + s.getEvents("short", EventFilter.all()).size()); + int removed = s.deleteExpiredSessions(later); + t.line("deleteExpiredSessions(now + 2h) removed %d session(s)", removed); + t.line("After: findById(short) = %s, findById(long) = %s", s.findById("short") != null ? "present" : "null", + s.findById("long") != null ? "present" : "null"); + assertThat(removed).isEqualTo(1); + assertThat(s.findById("long")).isNotNull(); + } + } +} diff --git a/session-memory/src/test/java/com/ankurm/sessionmemory/JdbcPostgresTest.java b/session-memory/src/test/java/com/ankurm/sessionmemory/JdbcPostgresTest.java new file mode 100644 index 0000000..6ceae54 --- /dev/null +++ b/session-memory/src/test/java/com/ankurm/sessionmemory/JdbcPostgresTest.java @@ -0,0 +1,87 @@ +package com.ankurm.sessionmemory; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Duration; +import java.util.List; +import java.util.Map; + +import com.ankurm.sessionmemory.support.Services; +import com.ankurm.sessionmemory.support.Show; +import com.ankurm.sessionmemory.support.Transcript; +import com.ankurm.sessionmemory.support.Turns; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.ai.session.CreateSessionRequest; +import org.springframework.ai.session.DefaultSessionService; +import org.springframework.ai.session.EventFilter; +import org.springframework.ai.session.Session; +import org.springframework.ai.session.SessionAttributes; +import org.springframework.ai.session.SessionRepository; +import org.springframework.ai.session.SessionService; +import org.springframework.ai.session.compaction.TurnCountTrigger; +import org.springframework.ai.session.compaction.WindowCompactionStrategy; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.jdbc.core.JdbcTemplate; + +/** The autoconfigured JdbcSessionRepository against a real PostgreSQL 16 (scripts/services-up.sh). */ +@SpringBootTest(properties = "spring.ai.model.chat=none") +class JdbcPostgresTest { + + @BeforeAll + static void needPostgres() { + Services.require("PostgreSQL", Services.PG_PORT); + } + + @Autowired + SessionService service; + @Autowired + SessionRepository repository; + @Autowired + JdbcTemplate jdbc; + + @Test + void autoconfigurationCreatesTheSchemaAndTheLogSurvivesANewService() { + try (Transcript t = new Transcript("10-jdbc-round-trip.txt", "JdbcSessionRepository on PostgreSQL 16")) { + jdbc.update("delete from ai_session"); + t.line("service: %s, repository: %s", service.getClass().getSimpleName(), repository.getClass().getSimpleName()); + t.line("tables: %s", jdbc.queryForList("select table_name from information_schema.tables where table_name like 'ai_session%' order by 1", String.class)); + + Session s = service.create(CreateSessionRequest.builder().id("jdbc-1").metadata(SessionAttributes.PRINCIPAL_NAME, "asha").build()); + Turns.plain(service, s.id(), 1, 5); + service.compact(s.id(), new TurnCountTrigger(3), WindowCompactionStrategy.builder().lastTurns(2).build()); + + t.blank().line("select seq order, event_type, message_type, message_content, synthetic from ai_session_event:"); + List> rows = jdbc.queryForList( + "select event_type, message_type, message_content, synthetic from ai_session_event where session_id = ? order by seq", s.id()); + int i = 1; + for (Map r : rows) { + t.line(" %2d %-10s %-10s %-6s %s", i++, r.get("event_type"), r.get("message_type"), r.get("message_content"), r.get("synthetic")); + } + + SessionService restarted = DefaultSessionService.builder().sessionRepository(repository).build(); + t.blank().line("A second SessionService on the same repository (a stand-in for a restart):"); + t.line(" active view: %s", Show.inline(restarted.getActiveMessages(s.id()))); + t.line(" whole log: %d events", restarted.getEvents(s.id(), EventFilter.all()).size()); + t.line(" findByMetadata(%s, asha): %s", SessionAttributes.PRINCIPAL_NAME, restarted.findByMetadata(SessionAttributes.PRINCIPAL_NAME, "asha").stream().map(Session::id).toList()); + assertThat(rows).hasSize(11); + assertThat(restarted.findByMetadata(SessionAttributes.PRINCIPAL_NAME, "asha")).hasSize(1); + assertThat(Show.inline(restarted.getActiveMessages(s.id()))).isEqualTo("U:u4 | A:a4 | U:u5 | A:a5"); + } + } + + @Test + void defaultsOfTheAutoconfiguredService() { + try (Transcript t = new Transcript("11-autoconfigured-defaults.txt", "What the autoconfiguration gives you with no properties")) { + Session s = service.create(CreateSessionRequest.builder().id("defaults-1").build()); + Duration ttl = Duration.between(s.createdAt(), s.expiresAt()); + t.line("default time-to-live: %d days", ttl.toDays()); + Throwable thrown = org.assertj.core.api.Assertions.catchThrowable(() -> + service.appendMessage("defaults-1", new org.springframework.ai.chat.messages.SystemMessage("x"))); + t.line("SystemMessage append: %s", thrown.getClass().getSimpleName()); + service.delete("defaults-1"); + assertThat(ttl.toDays()).isEqualTo(60); + } + } +} diff --git a/session-memory/src/test/java/com/ankurm/sessionmemory/MigrationTest.java b/session-memory/src/test/java/com/ankurm/sessionmemory/MigrationTest.java new file mode 100644 index 0000000..c690bf2 --- /dev/null +++ b/session-memory/src/test/java/com/ankurm/sessionmemory/MigrationTest.java @@ -0,0 +1,42 @@ +package com.ankurm.sessionmemory; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.ankurm.sessionmemory.support.ScriptedChatModel; +import com.ankurm.sessionmemory.support.Show; +import com.ankurm.sessionmemory.support.Transcript; +import org.junit.jupiter.api.Test; +import org.springframework.ai.chat.client.ChatClient; +import org.springframework.ai.chat.client.advisor.api.MemoryAdvisor; +import org.springframework.ai.chat.memory.ChatMemory; +import org.springframework.ai.session.DefaultSessionService; +import org.springframework.ai.session.InMemorySessionRepository; +import org.springframework.ai.session.SessionService; +import org.springframework.ai.session.advisor.SessionAdvisors; +import org.springframework.ai.session.advisor.SessionMemoryAdvisor; + +/** The one-line migration claim: the 2.0 conversation-id parameter is the 2.1 session-id parameter. */ +@SuppressWarnings("removal") +class MigrationTest { + + @Test + void theOldConversationIdParameterStillSelectsTheSession() { + try (Transcript t = new Transcript("13-migration-keys.txt", "ChatMemory.CONVERSATION_ID against SessionMemoryAdvisor.SESSION_ID_CONTEXT_KEY")) { + t.line("ChatMemory.CONVERSATION_ID = %s", ChatMemory.CONVERSATION_ID); + t.line("MemoryAdvisor.CONVERSATION_ID = %s", MemoryAdvisor.CONVERSATION_ID); + t.line("SessionMemoryAdvisor.SESSION_ID_CONTEXT_KEY = %s", SessionMemoryAdvisor.SESSION_ID_CONTEXT_KEY); + + ScriptedChatModel model = new ScriptedChatModel(); + SessionService service = DefaultSessionService.builder().sessionRepository(InMemorySessionRepository.builder().build()).build(); + ChatClient chat = ChatClient.builder(model).defaultAdvisors(SessionAdvisors.builder(service).build()).build(); + + chat.prompt().user("My name is Asha").advisors(a -> a.param(ChatMemory.CONVERSATION_ID, "legacy-key")).call().content(); + String answer = chat.prompt().user("What is my name?").advisors(a -> a.param(ChatMemory.CONVERSATION_ID, "legacy-key")).call().content(); + t.blank().line("Two calls with the 2.0 parameter name, SessionAdvisors on the client:"); + t.line(" model< %s", answer); + t.line(" session 'legacy-key' holds: %s", Show.inline(service.getMessages("legacy-key"))); + assertThat(ChatMemory.CONVERSATION_ID).isEqualTo(SessionMemoryAdvisor.SESSION_ID_CONTEXT_KEY); + assertThat(answer).isEqualTo("Your name is Asha."); + } + } +} diff --git a/session-memory/src/test/java/com/ankurm/sessionmemory/SessionLogTest.java b/session-memory/src/test/java/com/ankurm/sessionmemory/SessionLogTest.java new file mode 100644 index 0000000..35a7b22 --- /dev/null +++ b/session-memory/src/test/java/com/ankurm/sessionmemory/SessionLogTest.java @@ -0,0 +1,60 @@ +package com.ankurm.sessionmemory; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import com.ankurm.sessionmemory.support.Show; +import com.ankurm.sessionmemory.support.Transcript; +import com.ankurm.sessionmemory.support.Turns; +import org.junit.jupiter.api.Test; +import org.springframework.ai.chat.messages.Message; +import org.springframework.ai.session.CreateSessionRequest; +import org.springframework.ai.session.DefaultSessionService; +import org.springframework.ai.session.EventFilter; +import org.springframework.ai.session.InMemorySessionRepository; +import org.springframework.ai.session.Session; +import org.springframework.ai.session.SessionEvent; +import org.springframework.ai.session.SessionService; +import org.springframework.ai.session.compaction.TurnCountTrigger; +import org.springframework.ai.session.compaction.WindowCompactionStrategy; + +/** The session as an append-only event log: what is stored, what the model sees, and that compaction deletes nothing. */ +class SessionLogTest { + + static SessionService service() { + return DefaultSessionService.builder().sessionRepository(InMemorySessionRepository.builder().build()).build(); + } + + @Test + void theLogOnlyGrowsAndTheActiveViewIsAProjection() { + try (Transcript t = new Transcript("01-event-log.txt", "A session is an append-only log; the active view is a projection of it")) { + SessionService service = service(); + Session session = service.create(CreateSessionRequest.builder().id("demo").build()); + Turns.plain(service, session.id(), 1, 5); + + List before = service.getEvents(session.id(), EventFilter.all()); + t.line("After 5 turns, the log holds %d events and the model would see %d messages:", before.size(), + service.getActiveMessages(session.id()).size()); + Show.log(t, before); + + var result = service.compact(session.id(), new TurnCountTrigger(3), + WindowCompactionStrategy.builder().lastTurns(2).build()); + List after = service.getEvents(session.id(), EventFilter.all()); + List view = service.getActiveMessages(session.id()); + + t.blank().line("compact(trigger: more than 3 turns, strategy: keep last 2 turns):"); + t.line(" unchanged=%s covered=%d preserved=%d pinned=%d", result.isUnchanged(), result.coveredEventCount(), + result.preservedEvents().size(), result.pinnedEvents().size()); + t.blank().line("The log now holds %d events (nothing was removed, one COMPACTION boundary was appended):", after.size()); + Show.log(t, after); + t.blank().line("The active view (what the next prompt starts from): %s", Show.inline(view)); + + assertThat(before).hasSize(10); + assertThat(after).hasSize(11); + assertThat(after.subList(0, 10)).extracting(SessionEvent::getId).containsExactlyElementsOf( + before.stream().map(SessionEvent::getId).toList()); + assertThat(Show.inline(view)).isEqualTo("U:u4 | A:a4 | U:u5 | A:a5"); + } + } +} diff --git a/session-memory/src/test/java/com/ankurm/sessionmemory/SystemMessageAndConcurrencyTest.java b/session-memory/src/test/java/com/ankurm/sessionmemory/SystemMessageAndConcurrencyTest.java new file mode 100644 index 0000000..3990d43 --- /dev/null +++ b/session-memory/src/test/java/com/ankurm/sessionmemory/SystemMessageAndConcurrencyTest.java @@ -0,0 +1,76 @@ +package com.ankurm.sessionmemory; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import com.ankurm.sessionmemory.support.Show; +import com.ankurm.sessionmemory.support.Transcript; +import com.ankurm.sessionmemory.support.Turns; +import org.junit.jupiter.api.Test; +import org.springframework.ai.chat.messages.AssistantMessage; +import org.springframework.ai.chat.messages.SystemMessage; +import org.springframework.ai.chat.messages.UserMessage; +import org.springframework.ai.session.CreateSessionRequest; +import org.springframework.ai.session.DefaultSessionService; +import org.springframework.ai.session.EventFilter; +import org.springframework.ai.session.InMemorySessionRepository; +import org.springframework.ai.session.SessionEvent; +import org.springframework.ai.session.SessionService; +import org.springframework.ai.session.compaction.TurnCountTrigger; +import org.springframework.ai.session.compaction.WindowCompactionStrategy; + +/** The two defaults that surprise: system messages are refused, and appends are idempotent with a version check. */ +class SystemMessageAndConcurrencyTest { + + private static SessionService service(boolean allowSystem) { + return DefaultSessionService.builder().sessionRepository(InMemorySessionRepository.builder().build()) + .allowSystemMessages(allowSystem).build(); + } + + @Test + void systemMessagesAreRefusedUnlessEnabledAndThenPinned() { + try (Transcript t = new Transcript("08-system-messages.txt", "SystemMessage in a session")) { + SessionService off = service(false); + off.create(CreateSessionRequest.builder().id("x").build()); + Throwable thrown = org.assertj.core.api.Assertions.catchThrowable(() -> off.appendMessage("x", new SystemMessage("You are terse."))); + t.line("allowSystemMessages(false) [default]: %s: %s", thrown.getClass().getSimpleName(), thrown.getMessage()); + + SessionService on = service(true); + on.create(CreateSessionRequest.builder().id("x").build()); + on.appendMessage("x", new SystemMessage("You are terse.")); + Turns.plain(on, "x", 1, 4); + on.compact("x", new TurnCountTrigger(2), WindowCompactionStrategy.builder().lastTurns(1).build()); + t.blank().line("allowSystemMessages(true), 4 turns, then compact(lastTurns(1)):"); + t.line(" active view: %s", Show.inline(on.getActiveMessages("x"))); + assertThat(thrown).isNotNull(); + assertThat(Show.inline(on.getActiveMessages("x"))).isEqualTo("S:You are terse. | U:u4 | A:a4"); + } + } + + @Test + void appendsAreIdempotentAndBatchesAreVersionChecked() { + try (Transcript t = new Transcript("09-idempotent-and-versioned-appends.txt", "Retries and compare-and-swap appends")) { + SessionService s = service(false); + s.create(CreateSessionRequest.builder().id("v").build()); + SessionEvent e = SessionEvent.builder().sessionId("v").message(new UserMessage("hello")).build(); + long v0 = s.getEventVersion("v"); + s.appendEvent(e); + long v1 = s.getEventVersion("v"); + s.appendEvent(e); + long v2 = s.getEventVersion("v"); + t.line("version before append: %d, after append: %d, after retrying the SAME event: %d", v0, v1, v2); + t.line("events in log: %d", s.getEvents("v", EventFilter.all()).size()); + + SessionEvent next = SessionEvent.builder().sessionId("v").message(new AssistantMessage("hi")).build(); + boolean stale = s.appendEvents("v", List.of(next), v0); + boolean fresh = s.appendEvents("v", List.of(next), v1); + t.blank().line("appendEvents(expectedVersion = %d, which is stale): %s", v0, stale); + t.line("appendEvents(expectedVersion = %d, which is current): %s", v1, fresh); + t.line("events in log: %d", s.getEvents("v", EventFilter.all()).size()); + assertThat(v2).isEqualTo(v1); + assertThat(stale).isFalse(); + assertThat(fresh).isTrue(); + } + } +} diff --git a/session-memory/src/test/java/com/ankurm/sessionmemory/support/FixedReplyModel.java b/session-memory/src/test/java/com/ankurm/sessionmemory/support/FixedReplyModel.java new file mode 100644 index 0000000..8c02a8e --- /dev/null +++ b/session-memory/src/test/java/com/ankurm/sessionmemory/support/FixedReplyModel.java @@ -0,0 +1,31 @@ +package com.ankurm.sessionmemory.support; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.springframework.ai.chat.messages.AssistantMessage; +import org.springframework.ai.chat.model.ChatModel; +import org.springframework.ai.chat.model.ChatResponse; +import org.springframework.ai.chat.model.Generation; +import org.springframework.ai.chat.prompt.Prompt; + +/** A {@link ChatModel} that always answers with one fixed text and records every prompt it was sent. */ +public class FixedReplyModel implements ChatModel { + + private final String reply; + private final List prompts = new CopyOnWriteArrayList<>(); + + public FixedReplyModel(String reply) { + this.reply = reply; + } + + public List prompts() { + return List.copyOf(prompts); + } + + @Override + public ChatResponse call(Prompt prompt) { + prompts.add(prompt); + return new ChatResponse(List.of(new Generation(new AssistantMessage(reply)))); + } +} diff --git a/session-memory/src/test/java/com/ankurm/sessionmemory/support/ScriptedChatModel.java b/session-memory/src/test/java/com/ankurm/sessionmemory/support/ScriptedChatModel.java new file mode 100644 index 0000000..7df2e7e --- /dev/null +++ b/session-memory/src/test/java/com/ankurm/sessionmemory/support/ScriptedChatModel.java @@ -0,0 +1,75 @@ +package com.ankurm.sessionmemory.support; + +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.springframework.ai.chat.messages.AssistantMessage; +import org.springframework.ai.chat.messages.Message; +import org.springframework.ai.chat.messages.MessageType; +import org.springframework.ai.chat.model.ChatModel; +import org.springframework.ai.chat.model.ChatResponse; +import org.springframework.ai.chat.model.Generation; +import org.springframework.ai.chat.prompt.Prompt; +import reactor.core.publisher.Flux; + +/** + * A scripted {@link ChatModel}: no network, no API key, no randomness. It records every + * {@link Prompt} it is sent, which is the whole point -- what a memory test needs to prove is + * which messages reached the model, and that is exactly what a recorded prompt shows. + * + *

Its only "intelligence" is one rule that makes memory observable: if the last user message + * asks for the user's name, it looks for "my name is X" in the earlier messages of the + * same prompt and repeats X, or says it does not know. Nothing here says anything about what a + * real model would reply; it proves what the model would have been given. + */ +public class ScriptedChatModel implements ChatModel { + + private static final Pattern NAME = Pattern.compile("(?i)my name is (\\w+)"); + + private final List prompts = new CopyOnWriteArrayList<>(); + + public List prompts() { + return Collections.unmodifiableList(prompts); + } + + public Prompt lastPrompt() { + return prompts.getLast(); + } + + @Override + public ChatResponse call(Prompt prompt) { + prompts.add(prompt); + return new ChatResponse(List.of(new Generation(new AssistantMessage(reply(prompt))))); + } + + /** {@code ChatModel#stream} does not delegate to {@code call}; it throws unless overridden. */ + @Override + public Flux stream(Prompt prompt) { + return Flux.just(call(prompt)); + } + + private static String reply(Prompt prompt) { + List messages = prompt.getInstructions(); + Message last = messages.getLast(); + String text = last.getText(); + Matcher self = NAME.matcher(text); + if (self.find()) { + return "Nice to meet you, " + self.group(1) + "."; + } + if (text.toLowerCase().contains("what is my name")) { + for (Message m : messages.subList(0, messages.size() - 1)) { + if (m.getMessageType() == MessageType.USER) { + Matcher earlier = NAME.matcher(m.getText()); + if (earlier.find()) { + return "Your name is " + earlier.group(1) + "."; + } + } + } + return "I do not know your name yet."; + } + return "Noted."; + } +} diff --git a/session-memory/src/test/java/com/ankurm/sessionmemory/support/Services.java b/session-memory/src/test/java/com/ankurm/sessionmemory/support/Services.java new file mode 100644 index 0000000..7f10f52 --- /dev/null +++ b/session-memory/src/test/java/com/ankurm/sessionmemory/support/Services.java @@ -0,0 +1,29 @@ +package com.ankurm.sessionmemory.support; + +import java.net.InetSocketAddress; +import java.net.Socket; + +import org.junit.jupiter.api.Assumptions; + +/** Skips a test class (with a pointer to the script that fixes it) when a backing service is not running. */ +public final class Services { + + public static final int PG_PORT = 5440; + public static final int REDIS_STACK_PORT = 6390; + public static final int REDIS_PLAIN_PORT = 6391; + + private Services() { + } + + public static void require(String name, int port) { + boolean up; + try (Socket s = new Socket()) { + s.connect(new InetSocketAddress("127.0.0.1", port), 500); + up = true; + } + catch (Exception e) { + up = false; + } + Assumptions.assumeTrue(up, name + " is not listening on 127.0.0.1:" + port + " -- run scripts/services-up.sh first"); + } +} diff --git a/session-memory/src/test/java/com/ankurm/sessionmemory/support/Show.java b/session-memory/src/test/java/com/ankurm/sessionmemory/support/Show.java new file mode 100644 index 0000000..daedd60 --- /dev/null +++ b/session-memory/src/test/java/com/ankurm/sessionmemory/support/Show.java @@ -0,0 +1,42 @@ +package com.ankurm.sessionmemory.support; + +import java.util.List; + +import org.springframework.ai.chat.messages.AssistantMessage; +import org.springframework.ai.chat.messages.Message; +import org.springframework.ai.chat.messages.ToolResponseMessage; +import org.springframework.ai.session.SessionEvent; + +/** One-line renderings of messages and events so transcripts stay short and diff cleanly (no random ids). */ +public final class Show { + + private Show() { + } + + public static String inline(List messages) { + return messages.stream().map(Show::brief).reduce((a, b) -> a + " | " + b).orElse("(empty)"); + } + + public static String brief(Message m) { + char kind = m.getMessageType().name().charAt(0); + if (m instanceof AssistantMessage a && a.hasToolCalls()) { + return kind + ":[tool call " + a.getToolCalls().getFirst().name() + "]"; + } + if (m instanceof ToolResponseMessage r) { + return kind + ":[tool result " + r.getResponses().getFirst().responseData() + "]"; + } + return kind + ":" + m.getText(); + } + + /** {@code seq TYPE S:text}, where seq is the position in the log, not a database value. */ + public static String event(int position, SessionEvent e) { + String body = e.hasMessage() ? brief(e.getMessage()) : "payload=" + new java.util.TreeSet<>(e.getPayload().keySet()); + return String.format(" %2d %-10s %s%s", position, e.getType().name(), body, e.isSynthetic() ? " (synthetic)" : ""); + } + + public static void log(Transcript t, List events) { + for (int i = 0; i < events.size(); i++) { + t.line("%s", event(i + 1, events.get(i))); + } + } +} diff --git a/session-memory/src/test/java/com/ankurm/sessionmemory/support/Transcript.java b/session-memory/src/test/java/com/ankurm/sessionmemory/support/Transcript.java new file mode 100644 index 0000000..8176914 --- /dev/null +++ b/session-memory/src/test/java/com/ankurm/sessionmemory/support/Transcript.java @@ -0,0 +1,47 @@ +package com.ankurm.sessionmemory.support; + +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.nio.file.Files; +import java.nio.file.Path; + +/** + * Writes a numbered transcript under {@code output/} (repository root, not {@code docs/}) and + * echoes it to the console. Every console block quoted in the article comes out of one of these + * files verbatim. + */ +public final class Transcript implements AutoCloseable { + + private final Path path; + private final StringWriter buffer = new StringWriter(); + private final PrintWriter out = new PrintWriter(buffer); + + public Transcript(String fileName, String title) { + this.path = Path.of("output", fileName); + out.println("# " + title); + out.println(); + } + + public Transcript line(String format, Object... args) { + out.println(args.length == 0 ? format : String.format(format, args)); + return this; + } + + public Transcript blank() { + out.println(); + return this; + } + + @Override + public void close() { + out.flush(); + try { + Files.createDirectories(path.getParent()); + Files.writeString(path, buffer.toString()); + } catch (IOException e) { + throw new IllegalStateException("could not write " + path, e); + } + System.out.print(buffer); + } +} diff --git a/session-memory/src/test/java/com/ankurm/sessionmemory/support/Turns.java b/session-memory/src/test/java/com/ankurm/sessionmemory/support/Turns.java new file mode 100644 index 0000000..c2bad95 --- /dev/null +++ b/session-memory/src/test/java/com/ankurm/sessionmemory/support/Turns.java @@ -0,0 +1,19 @@ +package com.ankurm.sessionmemory.support; + +import org.springframework.ai.chat.messages.AssistantMessage; +import org.springframework.ai.chat.messages.UserMessage; +import org.springframework.ai.session.SessionService; + +/** Appends the plain user+assistant turns the tests are built from. */ +public final class Turns { + + private Turns() { + } + + public static void plain(SessionService service, String sessionId, int from, int to) { + for (int n = from; n <= to; n++) { + service.appendMessage(sessionId, new UserMessage("u" + n)); + service.appendMessage(sessionId, new AssistantMessage("a" + n)); + } + } +}