Data Contracts, Access and Retention

Three agreements keep agent data trustworthy: what it looks like, who may use it and how long it stays.

BeginnerIntermediateExpert · 13 min read · Last updated:

In short

A data contract states what a producer promises to consumers, including structure, meaning, quality and change rules, and a machine can check it. Access policies decide what each user and agent may read or change, and must be enforced in trusted code. Retention rules decide when data is removed, and erasure has to reach every copy: tables, indexes, memories, caches, logs and backups, with documented exceptions.

What you will learn: what to put in a contract, compatibility and versioning, fine-grained permissions for agents, retention schedules, and erasure workflows you can verify.
Prerequisites: Data Architecture for Agentic AI.

Not legal advice

This page describes engineering practice. Which laws apply, what must be kept and what must be deleted are legal questions for qualified advisers.

Beginner Why agreements matter

The silent break

A source team renames a column or starts sending a new status value. A person reading a report might notice. An agent's tool may return nothing, and the agent concludes that no urgent cases exist. Nothing crashes. A data contract turns this kind of surprise into a failed check before release.

What a data contract contains

PartQuestions it answers
Identity and ownerWhat is this dataset, and who answers for it?
SchemaWhich fields, types and keys?
MeaningWhat is one row? Which units and allowed values?
QualityWhich rules must hold, and what happens when they fail?
Service levelsHow fresh, how available, how long retained?
Access and useWho may read it, and for what purposes?
Change policyWhat counts as breaking, and how much notice is given?
SupportWhere to report problems?

The Open Data Contract Standard, maintained by the Bitol project under the Linux Foundation's data and AI umbrella and published under the Apache 2.0 license, describes contracts in YAML with sections covering fundamentals, schema, quality, roles, service levels and servers, among others. Version 3.2.0 was the current release when this page was updated. Using a standard format lets tools validate and publish contracts, but a short agreed file that is actually enforced beats an elaborate one that is not.

Two kinds of contract an agent depends on

ContractBetweenExample promise
Data contractData producer and consumersPriority is "low" or "high", updated within 15 minutes
Tool contractTool provider and the agentSearch returns source, date and a stable error format
Retrieval contractIndex owner and applicationsEvery passage carries identifier, version and audience

Tool design is covered in Designing Tool Schemas and Contracts. The idea is the same: state what the consumer may rely on, and test it.

Intermediate Enforcement and permissions

Check rows and check changes

A contract has two enforcement points: data arriving now, and proposed changes to the contract itself.

"""Enforce a data contract: check the rows, and check proposed changes."""
V1 = {"version": "1.2.0", "fields": {
    "ticket_id": {"type": str, "required": True},
    "priority": {"type": str, "required": True, "allowed": {"low", "high"}},
    "opened_hours_ago": {"type": int, "required": True, "minimum": 0},
}}
V2 = {"version": "1.3.0", "fields": {
    "ticket_id": {"type": str, "required": True},
    "priority": {"type": str, "required": True,
                 "allowed": {"low", "high", "urgent"}},
    "team": {"type": str, "required": False},
}}

def violations(row, contract):
    found = []
    for name, rule in contract["fields"].items():
        if name not in row:
            if rule["required"]:
                found.append(f"{name} missing")
            continue
        value = row[name]
        if type(value) is not rule["type"]:
            found.append(f"{name} is not {rule['type'].__name__}")
        elif "allowed" in rule and value not in rule["allowed"]:
            found.append(f"{name}={value!r} not allowed")
        elif "minimum" in rule and value < rule["minimum"]:
            found.append(f"{name} below {rule['minimum']}")
    return found

def breaking_changes(old, new):
    """From a consumer's point of view."""
    found = []
    for name, rule in old["fields"].items():
        other = new["fields"].get(name)
        if other is None:
            found.append(f"removed field {name}")
        elif other["type"] is not rule["type"]:
            found.append(f"changed type of {name}")
        elif "allowed" in rule:
            extra = other.get("allowed", set()) - rule["allowed"]
            if extra:
                found.append(f"new values in {name}: {sorted(extra)}")
    return found

rows = [
    {"ticket_id": "T1", "priority": "high", "opened_hours_ago": 3},
    {"ticket_id": "T2", "priority": "HIGH", "opened_hours_ago": 5},
    {"ticket_id": "T3", "priority": "low", "opened_hours_ago": "7"},
]
for row in rows:
    print(row["ticket_id"], violations(row, V1) or "ok")
changes = breaking_changes(V1, V2)
print(f"{V1['version']} -> {V2['version']}: {len(changes)} breaking")
for change in changes:
    print("  ", change)
if changes and V2["version"].split(".")[0] == V1["version"].split(".")[0]:
    print("release blocked: breaking changes need a new major version")

Output:

T1 ok
T2 ["priority='HIGH' not allowed"]
T3 ['opened_hours_ago is not int']
1.2.0 -> 1.3.0: 2 breaking
   new values in priority: ['urgent']
   removed field opened_hours_ago
release blocked: breaking changes need a new major version

Adding an allowed value looks harmless to the producer, yet it is reported as breaking here, because a consumer that handles only "low" and "high" may mishandle "urgent". Removing a field is obviously breaking. Adding the optional team field is not listed. The rule at the end ties the finding to the version number so that consumers can trust it.

This checker is deliberately small. A fuller one would also detect a required field becoming optional, tightened or loosened limits, changed units and changed meaning. Meaning changes are the hardest to catch automatically, so require human review when a description changes.

Where to enforceCatches
Producer's build pipelineBreaking changes before release
IngestionBad rows, which go to quarantine
Scheduled monitoringFreshness and volume promises
Tool boundaryMalformed results before the model sees them

Fine-grained access

ModelDecision based onGood for
Role-basedThe roles a user holdsStable job functions
Attribute-basedAttributes of user, data and contextRegion, sensitivity, time, purpose
Relationship-basedLinks such as owner, member, parent folderShared documents and hierarchies
Row and column policiesRules inside the databaseEnforcement close to the data
Purpose limitsWhy the data is being usedPreventing reuse beyond the stated aim

For an agent acting on behalf of a person, a sound default is the intersection: the agent may do only what both the user and the agent are allowed to do.

"""An agent acting for a person gets the overlap of both sets of rights."""
records = [
    {"id": 1, "region": "east", "name": "Ng", "salary": 91000},
    {"id": 2, "region": "west", "name": "Ruiz", "salary": 87000},
    {"id": 3, "region": "east", "name": "Park", "salary": 78000},
]
users = {
    "hr_east": {"regions": {"east"}, "fields": {"id", "name", "salary"}},
    "analyst": {"regions": {"east", "west"}, "fields": {"id", "region"}},
}
agent = {"regions": {"east", "west"}, "fields": {"id", "name", "region"}}

def read(user_name, wanted):
    user = users.get(user_name)
    if user is None:
        return "denied: unknown user"
    regions = user["regions"] & agent["regions"]
    fields = user["fields"] & agent["fields"]
    refused = sorted(set(wanted) - fields)
    if refused:
        return f"denied fields: {refused}"
    return [{f: r[f] for f in wanted}
            for r in records if r["region"] in regions]

print("hr_east names:  ", read("hr_east", ["id", "name"]))
print("hr_east salary: ", read("hr_east", ["name", "salary"]))
print("analyst regions:", read("analyst", ["id", "region"]))
print("analyst names:  ", read("analyst", ["name"]))
print("visitor:        ", read("visitor", ["id"]))

Output:

hr_east names:   [{'id': 1, 'name': 'Ng'}, {'id': 3, 'name': 'Park'}]
hr_east salary:  denied fields: ['salary']
analyst regions: [{'id': 1, 'region': 'east'}, {'id': 2, 'region': 'west'}, {'id': 3, 'region': 'east'}]
analyst names:   denied fields: ['name']
visitor:         denied: unknown user

The HR user may see salaries in the source system but not through this agent, because the agent is not allowed salary data at all. The analyst may see regions across both areas but no names. An unknown caller gets nothing. In production the user identity must come from authentication, never from text in the conversation, and the policy should live in a database or policy engine rather than in each tool.

Leaks through side doors

A strict table policy is undone if a cache, summary, embedding index or log holds the same data without it. Counts and error messages can leak too. Apply the policy to every derived copy, or restrict the copy to the most limited audience of its inputs.

Expert Retention and erasure

Retention schedules

Keeping data forever increases cost and risk. Deleting too early can break legal duties and make incidents impossible to investigate. Write a schedule that links each data type to a purpose, a basis, a period and a deletion method.

Agent dataQuestions to settle
Source documents and recordsFollow the source system's rules
Chunks, vectors, graph factsRemove when the source goes
Conversation historyHow long does the user benefit?
Long-term memoryWho can view, correct and delete it? See Memory Integrity, Isolation and Sharing
Traces and logsWhat content is needed for debugging? See Safe Logging, Sampling and Retention
Evaluation datasetsWere real cases copied in, and can they be removed?
Provider-side copiesWhat do model and tool providers keep, and for how long?
BackupsWhen do they expire, and what happens on restore?

Automate expiry. A schedule that depends on someone remembering will drift.

Right-to-erasure workflows

Under the GDPR, Article 17 gives people a right to have personal data erased in certain circumstances, with exceptions such as legal obligations and legal claims. Other laws have related rights. Engineering must be able to find all of a person's data, act on it and show what happened.

Verifyidentity and scope
Decideexceptions and holds
Findevery store, via lineage
Eraseand suppress re-import
Checkindependent scan
Respondrecord outcome
Decisions about exceptions belong to people with the authority to make them.
"""Erase one person from every copy, honor holds, then prove it."""
stores = {
    "crm": [{"subject": "u7", "data": "profile"},
            {"subject": "u8", "data": "profile"}],
    "invoices": [{"subject": "u7", "data": "invoice 2025-113"}],
    "search_index": [{"subject": "u7", "data": "chunk of an email"}],
    "agent_memory": [{"subject": "u7", "data": "prefers phone"}],
    "answer_cache": [{"subject": "u7", "data": "cached reply"}],
}
holds = {"invoices": "kept for a legal retention duty (example)"}
registered = ["crm", "invoices", "search_index", "agent_memory"]

def erase(subject):
    report = {}
    for name in registered:
        rows = stores[name]
        mine = [r for r in rows if r["subject"] == subject]
        if name in holds:
            report[name] = f"retained {len(mine)}: {holds[name]}"
            continue
        stores[name] = [r for r in rows if r["subject"] != subject]
        report[name] = f"deleted {len(mine)}"
    return report

def verify(subject):
    """Scan every store that exists, not only the registered ones."""
    return [name for name, rows in stores.items()
            if name not in holds
            and any(r["subject"] == subject for r in rows)]

for name, outcome in erase("u7").items():
    print(f"{name:<13} {outcome}")
left = verify("u7")
print("still holds data:", left)
for name in left:
    registered.append(name)
erase("u7")
print("after registering it:", verify("u7") or "clean")

Output:

crm           deleted 1
invoices      retained 1: kept for a legal retention duty (example)
search_index  deleted 1
agent_memory  deleted 1
still holds data: ['answer_cache']
after registering it: clean

The invoice is retained, with a recorded reason. The first run reports success for every registered store, yet the verification step finds data in an answer cache that nobody had registered. This is the usual failure: not a delete command that errors, but a copy that the workflow does not know exists. Verification must therefore look wider than the deletion list, and each new store should be registered before it receives personal data.

The European Data Protection Board's 2025 coordinated action on this right, reported in February 2026, found recurring weaknesses that include missing internal procedures, inadequate training, difficulty setting retention periods and handling deletion in backups. Backups were a concern for about half of the responding authorities. Decide your approach in advance: for example, let backups expire on a fixed cycle, restrict their use, and reapply erasures after any restore. Confirm that the approach is acceptable with your advisers.

Hard cases

CaseApproach to consider
Name appears inside a shared documentRedact the source, then rebuild derived items
Summaries mixing many peopleRegenerate from remaining sources
Table history and file versionsRun the platform's cleanup within its retention window
Fine-tuned model trained on the dataAvoid training on it; otherwise assess retraining with advisers
Rebuilds from raw eventsApply a suppression list during replay
Third parties that received dataNotify them where required and record it

A suppression list itself contains identifiers. Keep it minimal, for instance a keyed hash, protect it and document why it exists.

Making the three work together

Put classification, owner, audience and retention period in the contract, and let pipelines and policy engines read them. Then one change updates enforcement everywhere. Lineage from Metadata, Indexing, Quality and Lineage supplies the list of derived copies that erasure needs.

Illustrative example: a new status value

A ticket system plans an "urgent" priority. The contract check in its pipeline flags the change as breaking for consumers. The agent team updates its tool and tests, the producer publishes a new major version, and both versions run in parallel for two weeks. Without the contract, urgent tickets would have fallen outside the agent's "high priority" filter.

Introducing contracts without stalling teams

Contracts imposed on every dataset at once usually become paperwork. Begin where an agent or an important report depends on data owned by another team.

  1. Write down current behavior. Generate a draft from the real schema, then ask the owner to add meaning, allowed values and freshness.
  2. Check in warning mode. Report violations for a few weeks and learn which rules are wrong and which data is.
  3. Block selectively. Turn on blocking for rules whose failure would cause harm, with a named person who can grant a time-limited exception.
  4. Add change checks to the producer's pipeline, so breaking changes are discovered by the people making them.
  5. Publish consumers. Producers can only give notice if they know who relies on the data.

Measure the effort as well as the benefit: violations caught before release, incidents caused by unannounced changes, and the time producers spend maintaining files. Generate as much as possible and keep human attention for meaning and policy.

Testing permissions and deletion like features

Write automated tests with several synthetic users: one who should see a record, one who should not and one whose access was removed a moment ago. Run them against search, caches, summaries and the agent itself. For erasure, create a synthetic person, let their data flow everywhere, erase them and search every store. Schedule this test, because new copies appear as systems change.

Common mistakes

  • Writing contracts that nothing checks.
  • Treating new values and meaning changes as harmless.
  • Using a powerful shared account and filtering in the prompt.
  • Deleting the record but keeping vectors, memories and logs.
  • Verifying erasure only in the stores that were told to delete.
  • Restoring a backup and reintroducing erased data.
  • Keeping everything because deletion is hard.

Checklist

  • Important datasets and tools have owned, versioned contracts.
  • Breaking changes are detected before release.
  • User identity comes from authentication.
  • Derived copies carry the source's restrictions.
  • Every data type has a retention period and automated expiry.
  • All stores holding personal data are registered.
  • Erasure is verified independently and exceptions are recorded.
  • Restore procedures reapply erasures.

Frequently asked questions

Who writes the data contract?

The producer owns it, written with input from consumers. A contract that consumers impose without agreement rarely gets maintained.

Are embeddings personal data?

Treat them as sensitive if the source is. They are derived from the text, so delete them with it and ask your privacy advisers about their legal status.

Can an agent process erasure requests?

It can help gather information and prepare steps. Identity checks, exception decisions and destructive actions need defined controls and accountable people.

How long should agent logs be kept?

Long enough for debugging, security and any legal duty, and no longer. Reducing the content you log is often more effective than debating the period.

References and further reading

Next steps