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:
- Ordering. Entries written in the same instant come back in the order they were written.
- Filtering. A
task_typeor a specificreference_idskey narrows the match in SQL, so the caller never pulls back every value-matching row and narrows it in Python. - Paging.
query_pagewalks 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
| Key | Role |
|---|---|
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
seqis added with a plainADD COLUMNand a laterALTER COLUMN ... SET DEFAULT, usingensure_schema()'s_SEQ_COLUMN_SCHEMA. It runs on every start withADD COLUMN IF NOT EXISTS, the same way thechain_hashandchain_prev_hashcolumns inactivity-log-tamper-evidence.mdare 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 anACCESS EXCLUSIVElock, which blocks every concurrent reader and writer of this append-only log for the duration. A plainADD COLUMNwith no default, and a laterSET DEFAULT, are both metadata-only whatever the table size. Existing rows are leftNULL. write()never supplies aseqvalue. Nothing inActivityLogEntrycarries one, so the column's ownDEFAULT nextval(...)fires on every insert.seqis 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_typeis an exact match against the column of the same name, independent of every other filter.reference_ids_keynarrowsreference_id. Without it,reference_idmeans "appears anywhere inreference_ids" (anEXISTS (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 SQLWHEREclause. It requiresreference_id: passingreference_ids_keyalone raisesValueError, 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 everyEntityType; - any key with the
"order_id_N"prefix, which areinventory_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_cursorisNoneon the last page. A legacy row withseq IS NULLsorts after the sequenced rows sharing its instant, and the cursor handles that. - Repeat the filters with each cursor.
query_pagetakes the same filters asquery(node_type,node_instance_id,reference_id,reference_ids_key,task_type,start,end). The cursor records a position, not a query. limitmust be at least 1, orValueErroris raised. This applies toquery_page, wherelimitis required, and toquery(limit=...).query(limit=, after=)returns a plain list. With neither argument,queryreturns every match.InvalidCursorError(aValueErrorsubclass inengine/activity_log.py) is raised for anafterthat 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
seqonly guarantees insertion order for rows written after the column existed.- A row from before
_SEQ_COLUMN_SCHEMAfirst ran hasseq IS NULL. It is never backfilled, deliberately. This is the same "legacy rows don't retroactively gain a guarantee" stance that theNULLchain_hashandchain_prev_hashcolumns take inactivity-log-tamper-evidence.md. NULLsorts last within anoccurred_attie, 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
idfallback restores only determinism for this case, which is whatidalone gives withoutseq. 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_logtables created before theseqcolumn existed.
- A row from before
reference_ids_keynarrows areference_idmatch; it does not replacetask_typeas a disambiguator. Nothing stops a future Task from writingreference_ids={"order_id": ...}under some othertask_type. Passtask_typetoo whenever the caller needs "this key, from this kind of entry", asassemble_genealogydoes above.
Release: v0.11.0