Skip to content

Record row state on audited models - #178

Merged
WiktorB2004 merged 7 commits into
mainfrom
add-record-state
Dec 3, 2026
Merged

WiktorB2004 merged 7 commits into
mainfrom
add-record-state

Conversation

@WiktorB2004

@WiktorB2004 WiktorB2004 commented Dec 3, 2026 •

Copy link
Copy Markdown
Owner

Part of #51.

  • AuditOptions(record_state="always" | "on_delete") stores the row in data.state next to the diff: audited columns under their policy, tracked collections as sorted member ids. "always" on every entity.* entry (after the change; before it for a delete), "on_delete" on deletes only.
  • Unloaded columns and tracked collections are loaded in before_flush, batched per model and relationship, so the state has no "<unknown>" for them. data.changes stays as without the option.
  • hidden_fields masks state values, compaction keeps the newest state, scrub() erases it.
  • audit.query.state_at() / astate_at(): the state of the newest entity.* entry at or before at, one lookup on the object index (plan test added). None before the first entry, after a delete, or when visibility hides that entry. ValueError when an imported model with that object_type does not use "always", or when the entry has no state.
  • With AuditTrail(integrity=...), a flush of a model with record_state raises AuditOptionError until integrity covers data.state.
  • New module audit_trail/_state.py; docs in the models, querying and privacy guides, limitations and the continuum page.

Review follow-up

  1. lazy="raise" tracked collections are loaded by the batch query below instead of attribute access. Test: an "always" model with a raise collection, reloaded, updated, committed.

  2. write_only and dynamic tracked collections with record_state raise ValueError naming the model and relationship: at mapper configure (once a trail is installed), and on every flush of the model, since SQLAlchemy raises a configure error only once. check_models() reports them as state-collection (error). Docs bullet fixed.

  3. Loading is batched: one SELECT pk, cols ... WHERE pk IN (...) per mapper for unloaded columns, one SELECT parent_pk, member ... JOIN per mapper and tracked relationship for unloaded collections, chunks of 500, values set with set_committed_value (pending backref appends are applied on top, as a lazy load does). New objects load nothing. Deleting a parent that cascades to 20 children with a deferred column: 20 extra SELECTs before, 1 after (the reviewer's probe); the new test with a tracked collection on the children asserts 3 (parent columns, children columns, children's tags). Test that pending column values and a pending backref append survive the batch. Cost statement updated.

  4. The orphan-delete sentence is gone from the docs (AT-73 handles the bug).

  5. The install-time integrity scan is dropped (a trail is given no models); the flush check stays, now on every entry of a model with record_state, so an "on_delete" model fails on its first write. Test: an integrity trail and a non-integrity trail on separate session classes. modes_of reuses listener._subclasses; it still sees every imported model, as no narrower set exists.

  6. Updates are checked for a possible entry (an audited column change or a tracked collection change) before loading; an update of an excluded column alone runs no SELECT (tested).

  7. modes_of is cached per object type and read again when the process's mapper count changes, as by_actor_type does (unit test).

  8. Orphan deletes (with Audit objects deleted as orphans #180): SQLAlchemy decides them during the flush, after before_flush, so the first before_delete of an Audited instance in a flush batch-loads every instance the unit of work deletes that before_flush did not see (flush_context.states with isdelete), before any row is deleted. Test: clear() on a delete-orphan collection of "on_delete" children with a deferred column and a lazy="raise" tracked collection gives real values in data.state, with one extra SELECT for the orphans' columns (the flush itself still loads each orphan's association rows).

  9. Collections are no longer loaded into the objects (second review, blocker): loading a passive_deletes=True collection made the flush act on its members (UPDATE ... SET fk=NULL, failing with a non-null FK, leaving children with a NULL FK with a nullable one). load_for_state now reads only the member ids of unloaded tracked collections, in one outer-joined SELECT per mapper and relationship, into InstanceState.info; the listener takes them for the entry and entity_state applies the collection's pending backref changes on top. The collection stays unloaded, so the flush does what it does without the option. Tests: an "on_delete" parent with a tracked passive_deletes collection and an ON DELETE CASCADE FK (nullable, non-null, and with delete-orphan), and an "always" update of the same: the app's DML is identical with and without record_state, the database deletes the children, and the state holds the member ids. The cascade query-count test now compares against the same delete without the option (+3 SELECTs).

  10. A row that is gone when its state is loaded (deleted by SQL earlier in the transaction) fails the flush with SQLAlchemy's ObjectDeletedError naming the model and id, and nothing is written: leaving the state out with a warning would still store less than promised. Detected for both the column load and the member query (the outer join gives every live parent a row). Documented under "Row state". Tests for both paths, plus the composite-key tuple_().in_() branch and the 500-row batches (501 objects: two SELECTs each for columns and member ids).

  11. modes_of is keyed on the set of registries (weak references) plus the mapper count; unit test with one registry disposed and another added with as many mappers.

Cleanup notes

  • entity_state and entity_changes repeat the "column never set on a new instance" rule and the hash key-ring check.
  • _state._may_write_update mirrors the history comparison in entity_changes for updates; one helper could serve both.
  • _mask_activity handles payload and state with the same comprehension.
  • _state._load_orphans reads SQLAlchemy's UOWTransaction.states, as Audit objects deleted as orphans #180's _flushed_deletes does; they could share one helper.
  • _state._mappers_key uses SQLAlchemy's private mapperlib._all_registries() (present in 2.0 and 2.1).

AuditOptions(record_state="always" | "on_delete") stores the row in
data.state next to the diff, under the column policies, with tracked
collections as sorted member ids. Unloaded columns and collections are
loaded before the flush. Masking, compaction and scrub cover the state.
query.state_at() and astate_at() read a record's state at a point in
time. With integrity, record_state is refused for now.
Unloaded columns load in one SELECT per mapper and unloaded tracked
collections in one per relationship, set as committed values, and only
for objects that will get an entry; lazy="raise" collections work.
write_only and dynamic tracked collections are refused with
record_state, and check_models reports them as state-collection. The
integrity guard runs at flush only, so a separate trail without
integrity can use record_state. modes_of is cached per mapper count.
# Conflicts:
#	CHANGELOG.md
#	audit_trail/query.py
#	docs/guides/querying.md
#	tests/db/test_plans_history.py
The flush finds delete-orphan orphans after before_flush, so the first
before_delete of an Audited instance in the flush batch-loads every
deleted instance before_flush did not see, before any row is deleted.
Loading a tracked collection into a deleted or updated object made the
flush act on its members: a passive_deletes collection had its foreign
keys set to NULL instead of being left to ON DELETE CASCADE. The member
ids are now read into InstanceState.info and the collection stays
unloaded, so the flush emits the same statements with and without
record_state.

A row that is gone when its state is loaded now fails the flush with
ObjectDeletedError instead of storing an incomplete state. The modes_of
cache is keyed on the set of registries and the mapper count. Tests
cover passive_deletes, composite keys, the 500-row batches and the gone
row.
@WiktorB2004
WiktorB2004 merged commit 8bf2e83 into main Dec 3, 2026
15 checks passed
@WiktorB2004
WiktorB2004 deleted the add-record-state branch December 3, 2026 17:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant