Dev.to Security ๐Ÿ” Cybersecurity ๐Ÿ‘ 0 ๐Ÿ“– 5 min read

Forever by Accident: Retention Classes and Expiry for AI Feature Data

Here's an illustrative situation. A team ships a support assistant. For debugging, they store every prompt and response in full, in the same table reviewers use when a customer disputes an answer. Nobody sets an expiry.

Here's an illustrative situation. A team ships a support assistant. For debugging, they store every prompt and response in full, in the same table reviewers use when a customer disputes an answer. Nobody sets an expiry. Fourteen months later someone asks: how long do we keep customer messages?

The honest answer is "forever, by accident." Nobody decided that.

The OWASP Logging Cheat Sheet puts the goal in one line under "Disposal of logs": log data, debug logs and backups or copies shouldn't be destroyed before the required retention period, and shouldn't be kept beyond it. It also notes that legal, regulatory and contractual obligations can set those periods. Deleting too early loses evidence. Keeping too long turns old debug text into a liability. This post covers the engineering side: making whatever periods you pick actually happen.

Not all AI data is the same data

An AI feature usually produces at least three kinds of records with different lifespans:

  • Debug text: full prompts and responses for reproducing bugs. Useful for days, risky after.
  • Operational metrics: latency, token counts, error codes. No customer content.
  • Review records: what was suggested and what a person did with it. Usually the longest period.

One table with one policy means review records vanish or debug text lingers. So classify at write time, and refuse data without a class.

Decide the expiry when you write

 on write      kind -> retention class -> expires_at, policy_version
 on schedule   sweep: expires_at <= now AND no legal hold -> delete
 each sweep    deletion_runs: when, kind, count (never content)

Computing expires_at at write time means each row carries the promise in force when it was stored. If the policy changes, old rows keep their date unless you migrate them on purpose, and policy_version says which promise applies.

The code

from datetime import timedelta, timezone

POLICY_VERSION = "2026-11"
RETENTION = {  # illustrative durations, not a recommendation
    "debug_text": timedelta(days=7),
    "ops_metric": timedelta(days=90),
    "review_record": timedelta(days=3 * 365),
}

SCHEMA = """
CREATE TABLE IF NOT EXISTS ai_events (
  id TEXT PRIMARY KEY, kind TEXT NOT NULL, body TEXT NOT NULL,
  created_at TEXT NOT NULL, expires_at TEXT NOT NULL,
  policy_version TEXT NOT NULL, legal_hold INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS deletion_runs (
  run_at TEXT NOT NULL, kind TEXT NOT NULL, deleted INTEGER NOT NULL
);
"""

def stamp(dt):
    return dt.astimezone(timezone.utc).isoformat(timespec="microseconds")

def write_event(db, event_id, kind, body, now):
    if kind not in RETENTION:
        raise ValueError(f"no retention class for {kind!r}")
    expires = now + RETENTION[kind]
    with db:
        db.execute(
            "INSERT INTO ai_events VALUES (?, ?, ?, ?, ?, ?, 0)",
            (event_id, kind, body, stamp(now), stamp(expires),
             POLICY_VERSION))

def sweep(db, now, batch=500):
    deleted = {}
    while True:
        with db:
            rows = db.execute(
                "SELECT id, kind FROM ai_events WHERE expires_at <= ?"
                " AND legal_hold = 0 LIMIT ?",
                (stamp(now), batch)).fetchall()
            if not rows:
                break
            db.executemany("DELETE FROM ai_events WHERE id = ?",
                           [(row_id,) for row_id, _ in rows])
        for _, kind in rows:
            deleted[kind] = deleted.get(kind, 0) + 1
    with db:
        db.executemany(
            "INSERT INTO deletion_runs VALUES (?, ?, ?)",
            [(stamp(now), k, n) for k, n in sorted(deleted.items())])
    return deleted

What's doing the work:

  • Unknown kinds fail. A "misc" bucket is how the next forever-table starts.
  • Fixed-width UTC stamps. Same offset, six fractional digits, so the expires_at <= ? string comparison matches time order.
  • One transaction per batch. Per Python's sqlite3 docs, the connection context manager commits on a clean exit and rolls back on an exception (it doesn't close the connection). A crash loses one batch of progress; the next run continues.
  • Counts, not content. The deletion log shows cleanup ran without copying what it deleted.

Tests

import sqlite3
from datetime import datetime, timedelta, timezone
import pytest
import retention
from retention import SCHEMA, write_event, sweep

T0 = datetime(2026, 11, 27, 9, 0, tzinfo=timezone.utc)

@pytest.fixture
def db():
    conn = sqlite3.connect(":memory:")
    conn.executescript(SCHEMA)
    yield conn
    conn.close()

def ids(db):
    return {r[0] for r in db.execute("SELECT id FROM ai_events")}

def test_each_class_expires_on_its_own_schedule(db):
    write_event(db, "dbg", "debug_text", "full prompt", T0)
    write_event(db, "rev", "review_record", "{...}", T0)
    assert sweep(db, T0 + timedelta(days=8)) == {"debug_text": 1}
    assert ids(db) == {"rev"}

def test_legal_hold_blocks_deletion(db):
    write_event(db, "dbg", "debug_text", "full prompt", T0)
    with db:
        db.execute("UPDATE ai_events SET legal_hold = 1")
    assert sweep(db, T0 + timedelta(days=30)) == {}
    assert ids(db) == {"dbg"}

def test_policy_change_does_not_rewrite_old_rows(db, monkeypatch):
    write_event(db, "old", "debug_text", "full prompt", T0)
    monkeypatch.setitem(retention.RETENTION, "debug_text",
                        timedelta(days=1))
    sweep(db, T0 + timedelta(days=3))
    assert ids(db) == {"old"}  # still on the 7-day promise

def test_deletion_log_has_counts_not_content(db):
    write_event(db, "dbg", "debug_text", "secret text", T0)
    sweep(db, T0 + timedelta(days=8))
    rows = db.execute("SELECT * FROM deletion_runs").fetchall()
    assert len(rows) == 1 and rows[0][1:] == ("debug_text", 1)
    assert "secret" not in repr(rows)

The policy-change test is the easiest to forget. Shortening the debug period doesn't silently delete rows stored under the seven-day policy. If you want that, write a migration and record why.

Where data hides from your sweeper

OWASP's line includes backups and copies, which a table sweep doesn't reach:

  • Backups. Deleted rows live on in old snapshots, so real retention includes backup lifetime.
  • Derived copies. Exports, search indexes and embeddings built from prompt text need their own expiry.
  • Other logs. If your framework or tracing also captures request bodies, debug text has a second home.

Limits

  • The durations are placeholders. Real periods are for your legal, security and product owners to choose.
  • Deleting a row doesn't necessarily overwrite it on disk right away; check your database's secure-delete and vacuum behavior if that matters.
  • A legal hold only helps if someone sets it in time.

Where this fits

We work on Obligra Verify, which is designed to retain the evidence your application selects. Our evidence vs. logs page covers the split this post leans on: operational logs rotate on a schedule, while records kept for later review are a different artifact with a different job.

This article was generated by an AI agent (Claude) for the Obligra Verify team and checked against the linked sources.

๐Ÿ“ฐ Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes โ€” full credit and traffic to the original publisher.