Search and contents

Activity Log Query Ordering & Filtering: a monotonic tiebreak and SQL-level filters

This guide covers how ActivityLog.query in engine/activity_log.py returns entries and narrows them:

  1. Ordering. Entries written in the same instant come back in the order they were written.
  2. Filtering. A task_type or a specific reference_ids key narrows the match in SQL, so the caller never pulls back every value-matching row and narrows it in Python.
  3. Paging. query_page walks a large result with a cursor.

1. Ordering: occurred_at, then seq, then id

ActivityLog.query and ActivityLog.verify_chain both order results ORDER BY occurred_at, seq, id.

from engine.activity_log import ActivityLog

activity_log = ActivityLog()
results = activity_log.query(node_instance_id="mes-line-3")
# results is ordered oldest-to-newest, and same-instant entries come back
# in the order they were actually written, not in id's own random order.

What each sort key does

KeyRole
occurred_at The entry's timestamp. It is set client-side with datetime.now(UTC), so two writes can tie at the database's timestamp resolution.
seq A BIGINT column with a sequence-backed DEFAULT. Postgres assigns the value at insert time, and a sequence only hands out values in allocation order, so seq reflects insertion order. It breaks occurred_at ties correctly.
id A random uuid.uuid4(). A third-level fallback, not a replacement for seq.

id alone gives a deterministic order to same-instant writes but not an insertion-order-correct one, because a random UUID's sort order says nothing about which write happened first.

id is still needed because seq is nullable (see Pitfalls). Two legacy rows sharing an occurred_at instant would tie on seq as well (NULL = NULL), and would sort differently from call to call. That is the failure this feature exists to close. id closes that last gap, and it never overrides seq for any row seq covers.

How seq is stored and written

  • seq is added with a plain ADD COLUMN and a later ALTER COLUMN ... SET DEFAULT, using ensure_schema()'s _SEQ_COLUMN_SCHEMA. It runs on every start with ADD COLUMN IF NOT EXISTS, the same way the chain_hash and chain_prev_hash columns in activity-log-tamper-evidence.md are added.
  • It is deliberately not GENERATED ALWAYS AS IDENTITY, although that looks like the more obvious way to say "a column whose value is a sequence". An identity column's contract is that no row is ever without a value. Adding one to an existing, non-empty table therefore forces Postgres to compute and write a value for every existing row. That is a full table rewrite under an ACCESS EXCLUSIVE lock, which blocks every concurrent reader and writer of this append-only log for the duration. A plain ADD COLUMN with no default, and a later SET DEFAULT, are both metadata-only whatever the table size. Existing rows are left NULL.
  • write() never supplies a seq value. Nothing in ActivityLogEntry carries one, so the column's own DEFAULT nextval(...) fires on every insert. seq is a query-ordering detail of the store, not part of an entry's content.

2. Filtering: task_type and reference_ids_key

ActivityLog.query takes two optional keyword arguments for narrowing:

activity_log.query(
    reference_id="MO-1001",
    reference_ids_key="order_id",  # narrows the match to this one key
    task_type="Material Genealogy Link",
)
  • task_type is an exact match against the column of the same name, independent of every other filter.
  • reference_ids_key narrows reference_id. Without it, reference_id means "appears anywhere in reference_ids" (an EXISTS (SELECT 1 FROM jsonb_each_text(reference_ids) ...) scan). With it, the meaning becomes "appears under this one key" (reference_ids ->> key = value). Either way the test runs in the SQL WHERE clause. It requires reference_id: passing reference_ids_key alone raises ValueError, because a key with nothing to match against is not a filter.

Why these filters exist

Without them, a caller would pull back every entry whose reference_ids contains a given value under any key, then filter in Python for task_type == "Material Genealogy Link" and reference_ids.get(key) == value.

assemble_genealogy in engine/traceability.py passes both arguments straight through to ActivityLog.query, so Postgres computes the result:

link_entries = activity_log.query(
    reference_id=order_id, reference_ids_key="order_id", task_type="Material Genealogy Link"
)

Not every caller needs this

assemble_order_trail in engine/order_trail.py also narrows ActivityLog.query(reference_id=...) on the client side (_entry_names_order), and deliberately keeps doing so. Its narrowing is not one specific key. It accepts any of three key patterns:

  • the exact key "order_id";
  • the exact key "reference_id", the generic identity-resolution key accepted across every EntityType;
  • any key with the "order_id_N" prefix, which are inventory_shortage.py's multi-order correlation keys.

reference_ids_key matches exactly one key and cannot express a key prefix. Folding prefix matching into ActivityLog.query's generic surface would leak order_trail.py's domain vocabulary into infrastructure that every Activity-Log-reading module shares. See the Pitfalls in order-trail-assembly.md for the full reasoning.

assemble_order_trail still benefits from the ordering guarantee in section 1, because it makes the same ActivityLog.query call underneath.

3. Paging: limit, after, and query_page

ActivityLog.query takes two optional arguments, limit and after. ActivityLog.query_page is the paging form of it:

page = activity_log.query_page(limit=100, node_instance_id="mes-line-3")
while True:
    handle(page.entries)  # an ActivityLogPage: entries, in query()'s order
    if page.next_cursor is None:
        break  # the last page
    page = activity_log.query_page(limit=100, after=page.next_cursor, node_instance_id="mes-line-3")
  • Keyset paging, not offset. The cursor records the last row's (occurred_at, seq, id) sort keys, so a page boundary is a position in the section 1 order. An entry written between two requests never makes a later page repeat or skip a row, and nothing is scanned and thrown away as an offset would be. next_cursor is None on the last page. A legacy row with seq IS NULL sorts after the sequenced rows sharing its instant, and the cursor handles that.
  • Repeat the filters with each cursor. query_page takes the same filters as query (node_type, node_instance_id, reference_id, reference_ids_key, task_type, start, end). The cursor records a position, not a query.
  • limit must be at least 1, or ValueError is raised. This applies to query_page, where limit is required, and to query(limit=...). query(limit=, after=) returns a plain list. With neither argument, query returns every match.
  • InvalidCursorError (a ValueError subclass in engine/activity_log.py) is raised for an after that is not a cursor this module issues: bad base64 or JSON, the wrong shape or types, or no timezone. The cursor is parsed into typed values and bound as parameters, never put into the SQL text.

Pitfalls

  • seq only guarantees insertion order for rows written after the column existed.
    • A row from before _SEQ_COLUMN_SCHEMA first ran has seq IS NULL. It is never backfilled, deliberately. This is the same "legacy rows don't retroactively gain a guarantee" stance that the NULL chain_hash and chain_prev_hash columns take in activity-log-tamper-evidence.md.
    • NULL sorts last within an occurred_at tie, so a legacy row sharing an instant with a post-migration row won't necessarily land in its true insertion position relative to it.
    • The id fallback restores only determinism for this case, which is what id alone gives without seq. It cannot restore insertion-order correctness for rows that predate the column that makes the guarantee possible.
    • This does not matter for a fresh database. It only affects activity_log tables created before the seq column existed.
  • reference_ids_key narrows a reference_id match; it does not replace task_type as a disambiguator. Nothing stops a future Task from writing reference_ids={"order_id": ...} under some other task_type. Pass task_type too whenever the caller needs "this key, from this kind of entry", as assemble_genealogy does above.

Release: v0.11.0