惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

GbyAI
GbyAI
The GitHub Blog
The GitHub Blog
小众软件
小众软件
美团技术团队
博客园 - 司徒正美
G
Google Developers Blog
Blog — PlanetScale
Blog — PlanetScale
Hugging Face - Blog
Hugging Face - Blog
博客园_首页
大猫的无限游戏
大猫的无限游戏
罗磊的独立博客
Recent Announcements
Recent Announcements
酷 壳 – CoolShell
酷 壳 – CoolShell
D
Docker
J
Java Code Geeks
Last Week in AI
Last Week in AI
V
Visual Studio Blog
Microsoft Azure Blog
Microsoft Azure Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Proofpoint News Feed
V
V2EX
C
Check Point Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
MyScale Blog
MyScale Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
From 45 Minutes to 3: Automated Testing for AI Agent Memory
BAOFUFAN · 2026-06-23 · via DEV Community

BAOFUFAN

At 2 AM, a colleague dropped a message in the group chat: “Our Agent messed up the VIP client’s budget by an order of magnitude.” It wasn’t an LLM hallucination — it was the long-term memory layer silently swallowing a record, and our manual regression tests never touched that edge case.

How reliable an AI agent’s memory is isn’t something you can gauge by “feeling.” It needs to be verified relentlessly, automatically. If you’re still clicking through conversations and manually inspecting databases to confirm whether your agent remembers correctly, this article will show you the peace that settles over your world once you turn memory verification into an automated pipeline with GitHub Actions.

Breaking down the problem: why manual memory testing is almost like no testing at all

Our agent handles multi-turn user conversations. It uses LangChain’s ConversationBufferMemory for short-term memory and a long-term memory layer to persist critical information in SQLite (we started with Chroma, then cut complexity). Whenever a user mentions a quote, preference, or constraint, the agent calls a tool to write it into long-term memory, and retrieves it in the next conversation.

The trouble begins during iteration: we frequently tweak prompts, swap memory strategies, adjust retrieval thresholds. Every change meant re-running an entire set of conversation scenarios, then manually validating in the database — was it written? Duplicated? Old info expired and cleaned up? It’s deeply unnatural: click through dialogues one by one, check rows one by one. A full round took at least 45 minutes, and there was no way I could think of every edge case every time.

The root cause is obvious: verifying memory storage depends on state, and in a small team manual testing simply cannot guarantee that every state combination is covered. Regular unit tests don’t help either, because memory persists across sessions — you need an integration test environment and a clean initial state.

Designing the solution: let GitHub Actions be that “never-annoyed quality inspector”

The idea is brutally simple:

  1. On every push or PR, the runner spins up an isolated, deterministic test memory store (a SQLite file, zero external dependencies).
  2. A Python test script runs a series of simulated multi-turn conversations. After each turn it directly verifies the underlying stored data — not just comparing what the agent said, but asserting what records exist in the database.
  3. After the tests, the SQLite file is thrown away. No external services are involved, so the environment stays clean.

Why not other approaches?

  • Spinning up services with Docker Compose: Adding Chroma/Postgres would slow CI down, and we’re only testing business logic — no reason to introduce the non-determinism of a real vector database.
  • Only mocking database calls: That bypasses real SQL/vector retrieval logic, rendering the tests meaningless. We genuinely want to verify “it was really written, it was really read back.”
  • UI automation only: That’s yet another maintenance hell. Testing the storage layer directly is small, stable, and costs almost nothing to maintain.

So the final setup: pure Python script + pytest + tmp_path to create a temporary SQLite + GitHub Actions default Ubuntu runner. No Docker, no cloud services. The CI configuration is clean, under 40 lines.

Core implementation

1. A testable memory store abstraction

This snippet makes the memory store swappable with a test-friendly SQLite, completely free of production wiring.

# memory_store.py
import sqlite3
import json
from datetime import datetime, timezone

class MemoryStore:
    """长期记忆存储:负责写入、检索、过期清理"""

    def __init__(self, db_path: str):
        self.conn = sqlite3.connect(db_path, check_same_thread=False)
        self.conn.row_factory = sqlite3.Row
        self._init_table()

    def _init_table(self):
        self.conn.execute("""
            CREATE TABLE IF NOT EXISTS memories (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                session_id TEXT NOT NULL,
                key TEXT NOT NULL,
                value TEXT NOT NULL,
                created_at TIMESTAMP DEFAULT (datetime('now')),
                ttl_seconds INTEGER DEFAULT 86400
            )
        """)
        self.conn.commit()

    def upsert(self, session_id: str, key: str, value: str, ttl_seconds: int = 86400):
        # 原子性 upsert:如果 key 已存在则更新,否则插入
        self.conn.execute("""
            INSERT INTO memories (session_id, key, value, ttl_seconds, created_at)
            VALUES (?, ?, ?, ?, datetime('now'))
            ON CONFLICT(session_id, key) DO UPDATE SET
                value = excluded.value,
                created_at = datetime('now'),
                ttl_seconds = excluded.ttl_seconds
        """, (session_id, key, value, ttl_seconds))
        self.conn.commit()

    def retrieve(self, session_id: str, key: str) -> str | None:
        row = self.conn.execute(
            "SELECT value FROM memories WHERE session_id = ? AND key = ? "
            "AND datetime(created_at, '+' || ttl_seconds || ' seconds') > datetime('now')",
            (session_id, key)
        ).fetchone()
        return row["va

(The snippet above is presented exactly as in the original, truncated where it was originally cut off.)