# Lakebase Memory Store Service (SQLAlchemy + httpx)

## PURPOSE
This service persists the two stores from the Databricks Agent Memory design in a real database: a **sessions** table that records each conversation turn by turn, and a **memories** table that keeps what is worth knowing about each user (preferences, facts, workflows). An httpx client triggers the memory pipeline that distills sessions into memories and merges duplicates.

## WHY THIS MATTERS
The video describes agent memory on Agent Bricks as three pieces "all built on Lakebase," hooked up by binding a session store and a memory store and creating a memory pipeline between them. This project is that binding, made explicit: tables with foreign keys model how a distilled memory traces back to the session turns it came from. Students see why durable storage (not a dict) is what lets "your agent's next conversation start with what it learned from the last one."

## HOW TO BUILD
1. Define SQLAlchemy models `Session`, `Turn`, `Memory` with FK from `Memory.session_id` to `Session.id`.
2. Provide a `MemoryRepository` with `append_turn`, `distill`, and `get_user_memory`.
3. Use a deterministic extractor as the LLM stand-in; merge duplicates by `(user_id, kind, key)`.
4. Add an `httpx` client that posts to a configurable pipeline endpoint and reuses one connection.

```python
def distill(self, session_id: int) -> list[Memory]:
    session = self.session.get(Session, session_id)
    facts = extract_stub([t.text for t in session.turns])   # no LLM here
    existing = {(m.kind, m.key): m for m in session.user.memories}
    for f in facts:                                          # merge duplicates
        existing[(f.kind, f.key)] = Memory(user_id=session.user_id, **f._asdict())
    self.session.commit()
    return list(existing.values())
```

## WHEN TO USE IN PRODUCTION
Use it when you need memory on a governed database (Databricks Lakebase or any SQL store) with auditability, multi-instance safety, and the ability to join memory back to raw sessions. Ideal for regulated domains needing a provenance trail. Do **not** use it for ephemeral scratch or extremely high write throughput without batching — hot per-turn inserts and the vendor's managed pipeline will outperform a naive ORM loop.

## HOW IT HELPS STUDENTS
Students learn relational modeling of agent state, ORM sessions and transactions, de-duplication constraints, and HTTP client hygiene with httpx. They also practice the crucially real skill of swapping a deterministic stub for a provider call behind a stable interface.

## STARTER CODE
See `starter/main.py` — SQLAlchemy models, a repository with distill/merge, an httpx pipeline client, and `# TODO` markers for the real pipeline call and Lakebase connection string.
