# What an audit trail keeps

What an audited entity's history keeps of personal data, files, passwords
and fields with a retention of their own, and what deleting or erasing
records does to it.

## Personal data in a history

A field marked `personal:`, or of a standard type that is personal data
whatever holds it, such as a `PhoneNumber` or an `Email`, is kept in its
history as a keyed hash, as logs keep it
([Marked fields in logs](/docs/marking-personal-fields.md#marked-fields-in-logs)), so the
history shows that an email changed, not what it was.

A [sealed field](/docs/encrypted-fields.md) is in a history as
having changed, with no value before or after, so a history in clear holds
nothing the field sealed.

A `Password` is never in a history, since no record holds one
([How a secret is kept](/docs/secret-values.md#how-a-secret-is-kept)). A field
holding its `PasswordHash`, however deep, is in a history as a sealed field
is, as having changed with no value before or after. So no history, no
`AuditEntryRecorded` and no route built from one ever carries a password or
its hash.

## Files in a history

A `File` field's entry holds the file's id, name, size and digest, never its
bytes, nor the store and key they are kept under. Its `before` and `after` are
that JSON:

```text
{"id":"0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d","name":"prices.csv","size":18,"digest":"5f0c…"}
```

The `id` is the file's own, the one its key is made from, `name` is `null`
for a file your app put, `size` is in bytes, and `digest` is the BLAKE3 hash
of its bytes, which its ETag is made from. A `File` inside a structured
field, such as a `List<File>`, is kept the same way however deep. Erasure
deletes a file's bytes as it deletes or clears the field holding it
([Deleting and erasing](/docs/files.md#deleting-and-erasing)), and a marked `File` field is a
keyed hash in the history like any marked field, which erasure replaces as
it replaces the person's other values (below).

## A field with its own retention

A history keeps a field's value no longer than the field's own `retention:`
does ([On a field](/docs/retention.md#on-a-field)). The purge schedule run
that clears the value on a record clears it from that record's entries too,
and each entry loses its copy at the first run once the field's `since:`, as
it was when the entry was written, is longer ago than `after:`, whether its
record is still there or not. The entry stays, with the field listed as
changed and no value before or after.

Here the address a visitor signed up from is kept for 30 days, on the record
and in its history alike:

```jadpo
config {
    signup_ip_retention: Duration {
        default: 30d
    }
    visitor_audit_retention: Duration {
        default: 2557d
    }
}

entity Visitor {
    id: Uuid
    decline data.personal_unread: "Read by code this example leaves out"
    signup_ip: IpAddress? {
        personal: PersonalData.online
        retention: {
            after: config.signup_ip_retention
            since: created_at
        }
    }
    created_at: Instant {
        generated: Generated.on_create
    }

    person: true

    audit: {
        retention: {
            after: config.visitor_audit_retention
        }
    }
}
```

Once a visitor signed up more than 30 days ago, `signup_ip` is `none` on the
record and in every entry of its history, which still says it changed.

## Deleting a person's records

A record that belongs to a person ([The person](/docs/person-entities.md))
is deleted in code as any other is, and its history is kept as any deleted
record's is: the delete's entry says which record went, who removed it and
when, and the entries before it keep their values until the history's own
`retention:` ends. Erasing the person later reaches neither, since the record
is gone; erasure deletes the history only of the records it deletes itself
([Retention and erasure](/docs/audit-trail.md#retention-and-erasure)). A record the purge schedule
removes, by its `retention:`, its lifecycle's `purge:` or a cascade from
another's, goes with no entry, as every record the purge removes does. A
lifecycle's `delete` transition keeps the record, so it is an `.updated`
entry.

A shop's customers are people. Each order is theirs, deleted with them, and their
feedback is kept without them once they are erased.

`app.jadpo`:

```jadpo
application {
    connections: {
        erasures: {
            driver: Driver.disk
            path: "/var/lib/shop/erasures"
        }
    }
    privacy: {
        erasure_log: {
            store: erasures
        }
    }
}
```

`domains/shop/entities/customer.jadpo`:

```jadpo
use shop/types { Handle }

/// Someone who buys, and may be erased.
entity Customer {
    id: Uuid
    handle: Handle {
        unique: true
    }

    policy: {
        create: [Access.public]
        read: [Access.public]
        delete: [Access.public]
    }

    person: true
}
```

`domains/shop/entities/order.jadpo`:

```jadpo
use shop/entities { Customer }
use shop/types { OrderedItem }

/// Something a customer ordered, whose every change is kept.
entity Order {
    id: Uuid
    customer_id: Customer.id {
        on_delete: OnDelete.cascade
    }
    item: OrderedItem

    policy: {
        create: [Access.public]
        read: [Access.public]
        delete: [Access.public]
    }

    audit: {
        retention: {
            after: config.audit_retention
        }
    }
}
```

`domains/shop/entities/feedback.jadpo`, whose `author_name` is marked:

```jadpo
use shop/entities { Customer }
use shop/types { AuthorName }

/// What a customer thought, kept without them once they are erased.
entity Feedback {
    id: Uuid
    customer_id: Customer.id? {
        on_delete: OnDelete.cleared
    }
    author_name: AuthorName? {
        personal: PersonalData.identifying
    }
    stars: Int

    policy: {
        create: [Access.public]
        read: [Access.public]
    }

    audit: {
        retention: {
            after: config.audit_retention
        }
    }
}
```

`domains/shop/actions/cancel_order.jadpo`, an ordinary delete:

```jadpo
use shop/entities { Order, OrderNotFound }

/// Cancels an order.
action cancel_order(order_id: Order.id) fails OrderNotFound -> Unit {
    attempt Order.delete(order_id)
}
```

`domains/shop/actions/cancel_order.test.jadpo`:

```jadpo
use shop/entities { Customer, Order }
use shop/actions { order_item, register_customer }

test "a cancelled order's history is kept" {
    var ada: Customer = attempt register_customer("ada")
    var order: Order = attempt order_item(ada.id, "teapot")
    attempt cancel_order(order.id)
    var page: Page<AuditEntry> = Order.history(order.id)
    assert list.map(page.items, entry -> entry.change) == [AuditChange.deleted, AuditChange.created]
    assert list.map(page.items, entry -> entry.action) == ["cancel_order", "order_item"]
}
```

## Changes a delete's cascade makes

A `delete` in your code whose cascade deletes an audited record, or whose
`OnDelete.cleared` reference changes one, writes an entry for each record it
changes, in the same transaction, however deep the cascade goes. A record it
deletes has a `.deleted` entry, holding its values before as any delete's
does; a record it keeps has an `.updated` entry holding what the database
changed, the reference `none` after. Each names the delete that caused it:
`cause_entity` is the deleted record's entity, by name, and `cause_id` its
`id`. The purge schedule's deletions, and what they cascade to, write none.

`domains/shop/actions/remove_customer.jadpo` deletes a customer, which deletes
their orders and clears `customer_id` on their feedback:

```jadpo
use shop/entities { Customer, CustomerNotFound }

/// Removes a customer, with their orders.
action remove_customer(customer_id: Customer.id) fails CustomerNotFound -> Unit {
    attempt Customer.delete(customer_id)
}
```

`domains/shop/actions/remove_customer.test.jadpo`:

```jadpo
use shop/entities { Customer, Feedback, Order }
use shop/actions { leave_feedback, order_item, register_customer }

test "each change a delete's cascade makes is kept, with the delete that made it" {
    var ada: Customer = attempt register_customer("ada")
    var order: Order = attempt order_item(ada.id, "teapot")
    var feedback: Feedback = attempt leave_feedback(ada.id, "Ada", 5)
    attempt remove_customer(ada.id)
    var order_history: Page<AuditEntry> = Order.history(order.id)
    assert list.map(order_history.items, entry -> entry.change) == [
        AuditChange.deleted,
        AuditChange.created
    ]
    assert list.map(order_history.items, entry -> entry.action) == ["remove_customer", "order_item"]
    assert list.map(order_history.items, entry -> entry.cause_entity) == ["Customer", none]
    assert list.map(order_history.items, entry -> entry.cause_id) == [ada.id, none]
    var feedback_history: Page<AuditEntry> = Feedback.history(feedback.id)
    assert list.map(feedback_history.items, entry -> entry.change) == [
        AuditChange.updated,
        AuditChange.created
    ]
    assert list.map(
        feedback_history.items,
        entry -> list.map(entry.fields, change -> change.field)
    ) == [["customer_id"], ["customer_id", "author_name", "stars"]]
    assert list.map(feedback_history.items, entry -> entry.cause_id) == [ada.id, none]
}
```

## Erasure and the records it keeps

An erasure that keeps an audited record, anonymised or retained, keeps its
history: each entry still says what kind of change it was, who made it,
when and through which action. In every entry, each value that was the
erased person's becomes the text `<erased>`: the reference to them, and each
marked field erasure clears on the record, which on a retained record is
none. Every other value stays. No reference's or marked field's value can
read `<erased>`, since each is a UUID or a hash. The erasure writes no entry
of its own, since who erased a person is an
[access record](/docs/access-records.md), and a record it deletes
takes its history with it.

`domains/shop/actions/forget_customer.jadpo`:

```jadpo
use shop/entities { Customer, CustomerNotFound }

/// Erases a customer.
action forget_customer(customer_id: Customer.id) fails CustomerNotFound -> Unit {
    attempt Customer.erase(customer_id)
}
```

`domains/shop/actions/forget_customer.test.jadpo`:

```jadpo
use shop/entities { Customer, Feedback, Order }
use shop/actions { leave_feedback, order_item, register_customer }

test "erasing a customer keeps their feedback's history without them" {
    var ada: Customer = attempt register_customer("ada")
    var order: Order = attempt order_item(ada.id, "teapot")
    var feedback: Feedback = attempt leave_feedback(ada.id, "Ada", 5)
    attempt forget_customer(ada.id)
    var feedback_history: Page<AuditEntry> = Feedback.history(feedback.id)
    assert list.map(feedback_history.items, entry -> entry.change) == [AuditChange.created]
    var kept_changes: List<AuditFieldChange> = list.flatten(
        list.map(feedback_history.items, entry -> entry.fields)
    )
    assert list.map(kept_changes, change -> change.field) == ["customer_id", "author_name", "stars"]
    assert list.map(list.keep_first(kept_changes, 1), change -> change.after) == ["<erased>"]
    assert list.map(list.keep_last(kept_changes, 1), change -> change.after) == ["5"]
    var order_history: Page<AuditEntry> = Order.history(order.id)
    assert order_history.items == []
}
```

The feedback's history still says it was created, with three fields, and the
reference to Ada reads `<erased>`, as her name's hash does in a deployed app;
its stars stay as they were.

A copy of an entry already sent as `AuditEntryRecorded` keeps what it held,
as every event does
([When it runs](/docs/retention.md#when-it-runs)).
