↩
Synthetic Data Agent · 9 November 2026

🤖 SDA 08: Durable Agent Memory

Teaching the SDA to remember requests, plans, runs, retries, approvals, and evidence.

19 min read
SDA 08: durable agent memory — the next run can find what yesterday did.
0% read·19 min in this view

An agent can inspect a table, build a profile, and still forget what it decided five minutes later. That is not a philosophical problem. It is an operational one.

A chat transcript preserves a conversation, but not the durable record needed to coordinate retries, prove which evidence a plan used, or stop two workers from doing the same work.

Lakebase, Databricks’ fully managed PostgreSQL service, keeps that operational state — requests, runs, plans, approvals, retries, leases, and artifact decisions — while governed Delta tables hold the analytical evidence.

The agent still stops before generation. It has not learned to make synthetic rows yet; it has learned something more basic: yesterday happened, and the next run can find out what it did.


Memory Is Not Chat History

A Conversation Is a Context Window

A chat transcript is useful for conversation context:

  • What the user just asked.
  • Which clarification they answered.
  • Which explanation they found confusing.
  • Which language they prefer.

It is not a reliable operational record.

A transcript does not naturally give the system a stable request ID, a rule for recognizing duplicate submissions, a time-bounded worker lease, a current workflow version, or an immutable record of why a plan was approved. It is also a terrible place to ask a worker whether another worker is already generating the same artifact.

The operational questions are different:

What exactly was requested?
Which run attempted it?
Which evidence version did the plan use?
What failed?
Which artifact was reused?
Who approved the privacy decision?
Can a retry safely resume from the last checkpoint?

Those questions belong to an operational database. A lease is simply a time-bounded ownership claim: it tells the system which worker may act and until when.

Three Memory Planes

The SDA uses three deliberately different kinds of memory:

  1. Conversation context remembers the interaction.
  2. Operational memory remembers requests, workflow state, leases, plans, approvals, and compact run receipts.
  3. Analytical evidence remembers metadata inventories, profiles, distributions, relationships, patterns, validation detail, and eventually synthetic tables.

Lakebase owns the second plane. Delta owns the third.

That boundary matters. Putting a histogram into a transactional run table makes the operational database do analytical work. Putting a lease and an approval transition into a Delta table makes coordination needlessly awkward. The shape of the data should tell the system where it belongs.

Lakebase for Control, Delta for Evidence

If Delta is the evidence plane, Lakebase Postgres is the operational database beside it. Its job is low-latency transactional state and agent memory: the place to record what was requested, which run owns the work, which plan was approved, whether a retry is safe, and which evidence can be reused. Large profiles and analytical artifacts still belong in governed Delta tables, not in the run store.

The Lakebase record for a profile should not contain every distribution bucket.
It should say something like:

  • profile artifact profile_abc
  • source samples.wanderbricks.bookings
  • source version 605 — the Delta table version used for the evidence
  • configuration fingerprint — a stable identifier for the settings used
  • algorithm version profile-v1
  • location of the Delta evidence
  • status complete
  • a compact summary
  • checksum and provenance — where the artifact came from and how it was produced

The evidence plane then contains the column-level rows, histograms, missingness metrics, outlier summaries, and warnings.

The same rule applies to relationships and patterns. Lakebase stores which artifact the run used and why. Delta stores what the artifact measured.

Every reusable artifact therefore needs provenance, not just a friendly name:

  • artifact ID and type
  • source object and source snapshot
  • tool and algorithm version
  • configuration and threshold fingerprint
  • creation timestamp
  • whether it is approved or has been invalidated
  • primary and related locations
  • checksum
  • compact safe summary

Without that, reuse becomes a hopeful cache lookup. With it, reuse becomes a decision about whether the artifact is still safe to use.

Keep Requests, Runs, and Plans Separate

One schema decision matters immediately. A request describes intent, a run records one attempt, and a plan captures the versioned decisions that guide the work. Collapsing those three records creates a surprisingly expensive mess later.

The Request Is Intent

sda_generation_requests is the durable statement of what somebody wanted:

  • requester
  • environment
  • source scope
  • generation options, including privacy constraints
  • target catalog and schema
  • intended use
  • submission time
  • idempotency key — a key used to recognize a repeated submission

If the same user submits the same idempotency key twice with the same content, the system returns the original request. If the key is reused with different content, the request is rejected.

“Idempotent” means that repeating the same request has the same effect; it cannot mean “silently accept anything with the same label”.

The Run Is an Attempt

An sda_runs row is an execution identity:

  • current workflow status
  • current step
  • run and bundle versions
  • tool/configuration versions
  • timestamps and heartbeat
  • retry and lease information
  • sanitized failure
  • references to outputs

One request can have multiple runs. A failed run is history, not something to overwrite because the next attempt looks more flattering.

Within a run, an individual stage can also have multiple execution attempts. The run remains the overall execution identity; the attempt records each try at a particular stage.

The Plan Is a Versioned Decision

A plan is the exact set of decisions handed to downstream tools:

  • evidence IDs and source versions
  • generation order
  • join strategy and fan-out
  • privacy policy
  • business rules
  • validation thresholds
  • assumptions and warnings
  • reviewer and approval state

Plans are immutable versions. If a reviewer rejects a plan, the system creates version 2, which supersedes version 1. Version 1 remains unchanged.

That gives the agent an answer when somebody asks, “Why did this run generate that?”
The answer is not “the prompt was probably something like…”.
It is a plan fingerprint — a stable identifier for the plan’s contents — and an evidence set.

The Operational Schema

The Lakebase schema definition, stored at schema/lakebase/001_state_schema.sql, creates the core state tables:

  • sda_generation_requests
  • sda_runs
  • sda_generation_plans
  • sda_execution_attempts
  • sda_approvals
  • sda_feedback
  • sda_audit_events
  • sda_transition_events
  • sda_run_steps
  • sda_artifact_uses
  • sda_schema_versions

The order is intentional. Requests exist before runs, so sda_runs.request_id is a real foreign key rather than a comment describing a relationship that was never enforced.

Steps also carry attempt_number. A failed profile attempt and a successful retry are two records, not one row whose error column mysteriously became null overnight.

The current workflow state is a projection — a fast summary of the latest valid transition. The transition and audit history are the explanation.

A Small State Machine With Adult Supervision

The conceptual workflow is:

RECEIVED
  ⤷ ANALYZING
      ⤷ READY_FOR_PLANNING
          ⤷ AWAITING_APPROVAL
              ⤷ READY_FOR_GENERATION

The implementation uses the project vocabulary — requested, planned, awaiting_approval, approved, executing, and the later validation/publication states — but the rule is the same: transitions are explicit and legal edges are finite.

The repository rejects:

  • Jumping directly from request to published.
  • Moving a terminal run.
  • Approving a run that was never planned.
  • Completing an attempt after its lease expired.
  • Updating a step after it succeeded.
  • Changing a plan version in place.
  • Racing two workers into the same stage.

Every transition records an actor, a reason, and a timestamp. Optimistic version checks — “only update this row if it is still at the version I read” — stop a stale worker from applying a valid transition to an outdated projection.

This is the part that feels slightly bureaucratic until two workers do exactly what two workers do: both think they are the only one.

Making Lakebase Production-Safe

Durable memory is only useful if the store can be created consistently, reconnected safely, and changed without losing its history. The next three sections cover those operational guarantees.

Versioning the Lakebase Schema

A versioned Lakebase schema is a set of SQL files that defines its internal structure: tables, indexes, constraints, and the history of which schema definitions have been applied. A small deployment script — the schema runner — reads those files and applies them to Lakebase.

For each file, the runner stores a content-based fingerprint in sda_schema_versions. That fingerprint records exactly which SQL definition was applied, so a deployment can verify the installed schema and avoid applying the same definition twice. It is an operational receipt for the state structure, not a record of data being moved or transformed.

That leads to two practical decisions:

  • Keep the schema in schema/lakebase/001_state_schema.sql.
  • Apply it explicitly during deployment rather than when the application starts.

The schema runner:

  1. Discovers SQL files in sorted order.
  2. Hashes filename plus content.
  3. Creates sda_schema_versions.
  4. Applies the SQL in a transaction.
  5. Records a content-addressed schema-change ID — a fingerprint of the filename and SQL content.
  6. Can be run again without duplicating the sda_schema_versions row.

The application does not apply the schema on startup. Deployment owns that responsibility: mixing schema permissions with request handling would make rollback ambiguous and turn a temporary database outage into an uncertain schema state.

Safe OAuth Connections

Lakebase management and Lakebase data access are two different boundaries.

  • The Databricks CLI manages the project, branch, endpoint, role, and database.
  • A PostgreSQL client uses a short-lived Lakebase OAuth token to connect to the endpoint.

Databricks documents that OAuth credentials expire. So the production connection path cannot capture one token once and hope the process never reconnects.

The repository has a small connection boundary:

  • LakebaseConnectionConfig contains non-secret connection settings and a token provider that is called only when a connection is attempted.
  • connect_lakebase asks the provider for a token on every attempt, uses TLS, and retries only connection establishment, waiting a little longer between attempts up to a fixed limit.

The distinction matters: a dropped connection may be retried; a business write may not be repeated blindly.

Retrying a connection is safe. Retrying “insert approval” without a duplicate-protection rule is not automatically safe. The connection helper never retries repository business effects.

The token is passed to psycopg and never appears in the configuration’s debug representation, error text, or test output. Tests deliberately make the first token fail, return a fresh token on the second attempt, and assert that the secret never appears in the raised error.

Declarative Lakebase Infrastructure

The Databricks bundle declares the operational store in bundle/lakebase.yml.

Lakebase branches

  • a Lakebase Autoscaling project
  • a non-expiring dev branch
  • a read/write primary endpoint
  • an OAuth role
  • the sda_state database

Here, a branch is an isolated, writable database environment, an endpoint is the connection point, and a role is the database identity used to connect.

The bundle protects the root production branch and gives SDA a separate, non-expiring dev branch. The state schema, CRUD acceptance tests, idle-reactivation check, and recovery rehearsal all run against dev, so experiments and disposable test rows do not touch the protected root.

Scale to zero

The endpoint is bounded between 0.5 and 1.0 compute units and uses Lakebase scale-to-zero. While work is running, autoscaling stays inside that range. After five minutes without queries or connections, the compute suspends completely, while the durable storage and its data remain available. A new connection wakes the endpoint and it resumes from the 0.5-CU active floor.

The same five-minute timeout applies to dev, staging, and production because this is a batch-oriented synthetic-data system, not an always-on request-serving application. There is no reason to pay for an active database between generation runs. If a real latency requirement appears later, the timeout can be raised deliberately rather than treating production as permanently active by default.

The dev target uses the existing user OAuth role. staging and production point the role configuration at the target service-principal application ID — an application identity rather than a human user’s identity.

The role and the database are related resources, but they are not interchangeable. A PostgreSQL database has an owner, and Lakebase will not let a declarative deployment remove that owner while the database still belongs to it. In this setup, a generic password role owned sda_state; replacing that role with the OAuth role therefore required an ownership transfer first. The safe sequence was:

  1. Transfer database ownership to the existing OAuth identity.
  2. Redeploy the declarative role.
  3. Verify the database owner.
  4. Reconnect and verify the schema.

That is the kind of awkward operational lesson that belongs in the article because it will happen to somebody else at 4:47 p.m.

Building and Proving Durable Memory

The Implementation in the Repository

The repository contains the durable state contract and the pieces around it:

  • storage-neutral domain models and an in-memory reference implementation
  • restartable SQLite persistence for local development
  • the PostgreSQL/Lakebase adapter and OAuth connection boundary
  • the versioned schema files and schema runner
  • declarative Lakebase resources for the project, branches, endpoint, role, database, and snapshot schedule
  • the scope-analysis workflow that persists a plan only after its request and run exist
  • contract, restart, adapter, schema, bundle, and live integration tests

The repository boundary is in place, but not every target has already been promoted. This is where the durable workflow, its recovery path, and the dev acceptance evidence meet.

A durable state layer needs more than “the repository can insert a row”. The complete test plan covers six dimensions.

Contract Tests

The local in-memory repository is the fast reference implementation for expected behavior. It covers:

  • all domain validation
  • every legal workflow branch
  • idempotency and conflict detection
  • plan immutability
  • append-only approvals, feedback, audit events, and transitions
  • artifact decisions
  • optimistic concurrency
  • attempt lease renewal and stale recovery
  • retry step history

SQLite then proves that those semantics survive a process boundary and repository reopen.

Adapter Tests

The PostgreSQL adapter reuses the repository logic through a small database-driver translation layer. Its tests prove:

  • question-mark placeholders are translated to psycopg’s percent-s placeholders
  • logical table names map to sda_* tables
  • PostgreSQL timestamps normalize to the domain string contract
  • PostgreSQL JSONB — its JSON document type — arrays and objects normalize to the same JSON-string values used by SQLite
  • database integrity errors become the repository’s state error where appropriate

That JSONB normalization was not theoretical. The first live CRUD test inserted the rows successfully and then failed to read a JSONB array because the psycopg PostgreSQL driver returned a Python list while the adapter’s SQLite-compatible representation expected JSON text. The live test found it; the adapter now serializes JSONB values consistently.

Schema and Security Tests

The schema tests cover deterministic IDs and the empty-directory failure. The connection tests cover:

  • OAuth token refresh between retries
  • exponential backoff parameters
  • TLS configuration
  • missing-token failure
  • secret-free error text

The schema contract checks all 11 tables, foreign keys, status checks, indexes, sda_schema_versions tracking, and the retry uniqueness boundary. The repository contract also persists sda_audit_events through the in-memory, SQLite, and PostgreSQL implementations.

Bundle Tests

The static bundle contract validates all three targets. The live bundle acceptance validates the dev target against the configured Databricks workspace and confirms that the Lakebase resource graph is present.

The database ownership transfer is part of the runbook because declarative infrastructure is still infrastructure. YAML does not make dependencies disappear; it makes them reviewable.

Databricks Tests

The lab is deliberately a runbook rather than a notebook. The acceptance crosses bundle deployment, short-lived credentials, PostgreSQL, and Lakebase branch APIs; the CLI sequence keeps those boundaries visible and repeatable.

The live sequence was:

  1. Authenticate the Databricks CLI with the deployment identity.
  2. Deploy the bundle.
  3. List the project, branch, endpoint, role, and database.
  4. Generate a short-lived database credential.
  5. Apply the versioned Lakebase schema.
  6. Query the database directly and confirm 11 sda_* tables.
  7. Run request/run/plan/step/attempt/artifact/audit CRUD through the PostgreSQL repository.
  8. Read everything back.
  9. Remove only the generated test rows.
  10. Verify the protected root branch and daily seven-day snapshot schedule.
  11. Run the Spark jobs for metadata, profiling, relationships, patterns, and scope.

The acceptance reapplied the current schema definition. The second pass was idempotent: it left the operational schema at 11 sda_* tables without duplicating the schema-version record or leaving disposable rows behind.

The live repository test deliberately exercised a failed first step followed by a successful second attempt. It recorded a durable audit event and a reused profile artifact, renewed a lease, completed the attempt, and left no live-* request rows behind.

The Spark jobs produced real governed outputs in the Databricks workspace. spark_contract_smoke, uc_metadata_reader, table_profiler, relationship_detector, pattern_detector, and a one-table analyze_scope run all terminated successfully.

The cross-series path was then repeated against a controlled Unity Catalog fixture in the managed workspace, rather than relying only on the sample tables. The metadata reader selected two fixture tables, and the profiler was forced through a fresh calculation with reuse_existing=false. That proves the run exercised computation, not only artifact reuse.

The relationship detector found the expected one-to-many relationship with an orphan_rate of zero. analyze_scope produced the relationship and dependency-graph artifacts. Then pattern_detector consumed the metadata, profile, relationship, and graph IDs explicitly, producing 13 patterns across four families. Cleanup removed only the two tables owned by that run and left the shared integration schema intact.

The run still surfaced an environment caveat worth keeping in mind. Unity Catalog did not expose RELY constraint metadata consistently, so the relationship result was validated from the data rather than inferred from a constraint that was not available. That is a platform-availability warning, not evidence that the relationship detector is broken.

That fixture also exercised a boundary case worth keeping in the test suite: a small input can legitimately produce zero patterns at the default support threshold. The persistence layer now records an empty evidence batch as a completed, idempotent result instead of attempting an invalid empty Delta merge. The bundle smoke path lowers the threshold for its tiny fixture and checks that a positive pattern result is actually emitted.

Recovery Is a Branch, Not a Magic Undo Button

The state store has a recovery path that can be tested without replacing the live branch. The dev acceptance run inserted a unique request marker, committed it, recorded the server timestamp, removed the marker from dev, and created a disposable branch from that point in time. The restored branch returned the marker and the sda_schema_versions rows; the original branch returned zero rows for the marker after cleanup.

That shape is deliberate. It follows Lakebase’s point-in-time restore model: recovery creates a new branch from a previous point in time, while the existing branch and its connections remain untouched. A branch is therefore useful both as an isolated working environment and as a safe recovery destination. The bundle also protects the root production branch and declares a daily snapshot schedule with seven-day retention. The SDA state database lives on the child dev branch, so this acceptance test uses point-in-time recovery for that branch; it does not pretend that a snapshot of production is a backup of dev. The repeatable marker setup lives in scripts/prepare_sda08_restore_point.py.

The live scale check also crossed the boundary that configuration alone cannot prove. After the five-minute idle window, the endpoint reported IDLE; a fresh OAuth connection brought it back to ACTIVE and read sda_schema_versions. The Lakebase API did not return the literal SUSPENDED value during this run, so the evidence is recorded as the observable IDLE -> ACTIVE transition.

The local and Databricks dev gates are complete. That is not a claim that staging or production promotion is complete: those targets still need their service-principal permissions, governed Unity Catalog grants, and platform-owner sign-off.

Boundaries and Payoff

What Durable Memory Does Not Do

It does not generate synthetic rows.

That is a feature, not an apology. Generation needs a durable plan, approved privacy posture, compatible profile and relationship evidence, and explicit validation expectations. Durable memory creates the checkpoint where those decisions become safe to execute.

Durable memory makes the agent more useful, but it also makes mistakes durable. That is why every artifact has provenance, every plan is versioned, invalidation is explicit, and the next run can explain whether it produced new evidence or reused old evidence.

The Moment the Agent Remembers

The interesting result is not that Lakebase can store a row. PostgreSQL has been doing that since before most dashboards were born.

The result is that the SDA can now answer questions across runs:

We already inspected this source version. The profile is complete and compatible. Relationship evidence came from this exact snapshot. The first attempt timed out. The second attempt succeeded. The plan was approved by this reviewer. The pattern registry was reused. The next safe step is generation, but it has not happened yet.

That is a much better agent than one that confidently starts over.


🔗 Source Code

Branch and Acceptance Plan

The implementation, versioned schema, bundle resources, tests, and detailed acceptance plan are on the SDA-08 branch.

Important Files

The article’s build checklist lives with the branch. The most important files are:

  • src/sda/state.py — storage-neutral state contracts and in-memory reference repository.
  • src/sda/state_sqlite.py — restartable local persistence.
  • src/sda/state_postgres.py — PostgreSQL/Lakebase adapter and OAuth connection boundary.
  • schema/lakebase/001_state_schema.sql — Lakebase state schema definition.
  • bundle/lakebase.yml — declarative Lakebase project, protected root branch, endpoint, role, database, and snapshot schedule.
  • scripts/prepare_sda08_restore_point.py — reproducible disposable marker for point-in-time recovery checks.
  • scripts/check_sda08_live_state.py — post-cleanup check for the 11-table schema, sda_schema_versions rows, and disposable-row count.
  • tests/test_state*.py — state, restart, adapter, schema, and integration contracts.

The agent has memory now. The next article can finally ask it to do something with what it remembers.


SDA 08 — Durable Agent Memory

Make yesterday findable. Build the next run with receipts.

79Published
22,889Visits
9,555Read
VisitsReadLAST 5 WEEKS