The myth of agentic self-healing
In modern agent architectures, developers frequently implement retry loops. When a model produces a syntax error or receives a database exception, the framework feeds the error back into the prompt context:
“The previous query failed with violates foreign key constraint. Please correct your SQL and try again.”
Frameworks market this pattern as autonomous self-healing. When applied to code generation or document summarization, prompting a model to reflect on an error message often yields a corrected output.4
At the storage layer, however, this pattern is dangerous.
Language models do not possess physical access to database tables. When an agent experiences an error during a multi-statement transaction or attempts a partial write, it cannot inspect the committed state on disk. The agent guesses what changed based purely on its conversational memory. When prompted to fix its mistake, the model generates compensatory queries that frequently amplify the corruption.
Deedglass
Putting back what an agent changed
-
1Too much changed
301 rows changed
The agent said 1 row
Doesn’t match -
2A person decides
Signs the undo
Not nowUndo 301 rowsSigned by a person -
3Checked, then put back
All 301 rows back
The undo is checked before it runs
Matches
How a retry creates an amplification cascade
Consider what happens during an automated customer migration task:
An agent attempts to migrate billing profiles between two relational tables: customer_accounts and subscription_ledger. The agent begins by updating the account state:
Code A database command in SQL. The text around it says what it does.
UPDATE customer_accounts
SET tier = 'enterprise', status = 'migrated'
WHERE organization_id = 'org_7721';
PostgreSQL executes the update and updates one row.
Next, the agent attempts to insert an audit entry into subscription_ledger:
Code A database command in SQL. The text around it says what it does.
INSERT INTO subscription_ledger (org_id, event, recorded_at)
VALUES ('org_7721', 'tier_upgrade', 'invalid_timestamp');
The database rejects the timestamp syntax and returns an error: ERROR: invalid input syntax for type timestamp with time zone.
In a standard agent loop, the retry mechanism activates. The agent receives the error string. Instead of rolling back the initial transaction, the agent attempts to correct its query. However, because the agent runs across distinct database connections or autocommit sessions, the initial UPDATE on customer_accounts has already committed.
The agent reasons in natural language: “My previous attempt to upgrade org_7721 failed. I should clean up and restart.”
The agent now attempts an unconstrained repair:
Code A database command in SQL. The text around it says what it does.
UPDATE customer_accounts
SET status = 'active'
WHERE status = 'migrated';
Notice what just occurred: because the agent omitted organization_id = 'org_7721', this compensatory update reset every migrated customer in the database back to active status. What began as a single-statement timestamp syntax error escalated into widespread relational data corruption.
Why conversational feedback fails the storage layer
Why does this failure recur across AI agent frameworks? The problem stems from three architectural blind spots:
1. Disconnect between intention and execution
When an agent calls a database tool, it operates through a remote protocol such as the Model Context Protocol (MCP) or an HTTP API wrapper.2 The model receives text output from the tool. If a tool call partially mutates the database before failing, the model has no visibility into foreign key cascades, trigger side effects, or locks.
2. Autocommit and broken transaction boundaries
Most developer agents (including Cursor, Claude Code, and terminal coding assistants) execute queries in autocommit mode. Each executed statement commits immediately. When an agent encounters an error on step three of a three-step workflow, steps one and two remain permanently committed in PostgreSQL. A conversational retry cannot revert physical database pages.
3. Hallucinated compensating transactions
When asked to undo its own changes, an LLM generates SQL based on training patterns rather than the actual state before the mutation. If an agent modified a column from gold to platinum, it may assume the previous value was standard, overwriting historical ground truth.
The three rules for safe database retries
To prevent automated retries from corrupting production databases, engineering teams must replace conversational reflection with deterministic storage verification:
Code What the screen or file shows, copied as is.
┌────────────────┐ 1. Policy gate ┌────────────────┐
│ AI Agent ├────────────────────────►│ Pre-Execution │
│ (Cursor/Code) │ │ CEL gate │
└────────────────┘ └───────┬────────┘
│ 2. Allowed SQL
▼
┌────────────────┐ 4. Compare State ┌────────────────┐
│ Postgres WAL │◄────────────────────────┤ PostgreSQL │
│ Change Log │ │ Target DB │
└───────┬────────┘ └────────────────┘
│
▼ 5. Cryptographic Record
┌──────────────────────────────────────────┐
│ Deedglass Record + Deterministic Undo │
└──────────────────────────────────────────┘
Rule 1: Evaluate blast radius before execution
Every query must pass through a deterministic pre-execution gate before touching the socket. Statements lacking a WHERE clause, or operations touching tables marked as sensitive, must be denied or held for human review.1 You can test sample queries on the /check/ai change checker to see how deterministic rules intercept risky mutations.
Rule 2: Verify committed state against write-ahead logs
Never trust the agent’s textual summary of what happened. An agent may report: “Updated 1 customer record”, while PostgreSQL write-ahead logs record 50 deleted rows due to cascading foreign keys. Deedglass connects to PostgreSQL logical decoding replication slots to read the exact row diff committed on disk.1
Rule 3: Generate deterministic undo SQL from disk diffs
If a workflow must be reverted, never ask the language model to write an undo script. The rollback must be generated mathematically from the pre-image recorded in the database change log.2
Deterministic undo SQL versus hallucinated rollbacks
When Deedglass observes database writes via logical decoding, it captures the exact before and after images of modified tuples.1 If an agent runs an erroneous update during an interactive session, Deedglass produces an exact, deterministic undo script:
Code A database command in SQL. The text around it says what it does.
-- Generated by Deedglass Observe Engine from PostgreSQL WAL
-- Session: obs_01k829a | Target: customer_accounts
UPDATE customer_accounts
SET tier = 'pro', status = 'active'
WHERE organization_id = 'org_7721'
AND tier = 'enterprise'
AND status = 'migrated';
Because this query asserts both the primary key and the expected intermediate state in its WHERE clause, PostgreSQL ensures atomic rollback. If any external transaction touched the row in the interim, the update affects zero rows and rolls back cleanly, preventing data races.
You can experiment with simulated agent errors and review atomic rollback behavior directly in the browser using the interactive /play playground.
Auditing your agent setup before production
Before giving autonomous coding agents or workflow tools write access to staging or production databases, teams must grade their existing attack surface.
Run the scan tool locally across your agent configurations:
Code Commands typed in a terminal. The text around it says what happens.
npx deedglass scan
The scanner inspects your .cursor/mcp.json, claude_desktop_config.json, and database connection permissions without sending any data off your machine. It checks whether database roles hold superuser privileges, whether MCP servers lack read-only constraints, and whether unconstrained write paths exist.
To understand how each deduction is calculated and how to raise your security posture from a D to an A, review the complete grading rubric on /score.
Autonomous agents will continue to make mistakes when interacting with complex relational systems. The role of systems engineering is not to hope for perfect language model outputs, but to ensure that physical reality at the storage layer remains deterministic, verifiable, and completely recoverable.
Written with AI assistance and checked against our claims register.