Skip to content

fix(audit): keep inclusive time bounds precise across ISO timestamp forms (#3555) - #3573

Closed
developerjillur wants to merge 8 commits into
Abilityai:devfrom
developerjillur:fix/3555-audit-export-time-bounds
Closed

developerjillur wants to merge 8 commits into
Abilityai:devfrom
developerjillur:fix/3555-audit-export-time-bounds

Conversation

@developerjillur

Copy link
Copy Markdown
Contributor

Description

Audit time filters compare stored timestamps as text. A fractional event such as 2026-10-11T10:30:52.741692Z sorts before the whole-second bound 2026-10-11T10:30:52Z, so an inclusive start_time drops events in its first second, and a whole-second end_time includes events after it.

Valid bounds are now normalized to UTC with the existing to_utc_iso helper and compared against a read-only expression that pads the stored UTC-Z fraction to six digits. A coarse range on the raw timestamp column stays in the query so the index is still used. Stored timestamps and hash-chain fields are never rewritten. Malformed bounds keep their old raw-string comparison; this does not add API validation.

The fix is in the shared filter used by list, count, stats, calendar and heatmap, so JSON and CSV export pick it up too. Other filters, ordering, pagination and admin checks are unchanged. The existing audit-trail flow doc now states the bound semantics.

Related Issue

Fixes #3555

Journey Impact

Journey Impact: none: this corrects the existing admin audit time-window query and does not add or extend a journey in tests/journeys/catalog.yaml.

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update

Testing

  • I have tested this locally
  • New tests added (if applicable)
  • All existing tests pass (one local environment failure, same on dev; details below)
  • Every new test executes the changed path

tests/unit/test_3555_audit_time_bounds.py (73 cases) uses the real audit_log table and PlatformAuditOperations on a temporary SQLite database. It also mounts the actual audit router in-process with the real require_admin for JSON/CSV export, list paging and non-admin rejection. Windows cover whole-second, short-fraction and microsecond stored rows, offset bounds and exact microsecond matches.

  • New regression file: 73 passed with the fix; 49 failed and 24 passed against the original src/backend/db/audit.py.
  • With the existing audit tests (tests/unit/test_847_audit_dashboard.py, tests/unit/test_audit_chain_edges.py) and tests/unit/test_2338_journey_catalog.py, merged locally onto the current dev (474e00c): 167 passed.
  • Full backend unit island, serial on Python 3.13.14: 25,518 passed, 114 skipped, 14 xfailed, 3 failed, 21 errors. All 24 came from my local setup: a long temp path and a DB path override. Rerun with a short temp directory and the default unit DB path, 23 pass. The last one, the pyjwt pin-parity check, fails the same way on dev because this environment has pyjwt 2.15.1 and the image pins 2.14.0.
  • tests/lint_sys_modules.py and tests/lint_root_test_placement.py pass.
  • The new expression compiles to || concatenation on SQLite and PostgreSQL, and SQLite EXPLAIN still searches idx_audit_log_timestamp. I did not run it against a live PostgreSQL.

Mutation: with src/backend/db/audit.py replaced by the dev version, test_3555_all_readers_use_inclusive_instants (45 of 60 cases), both test_3555_export_uses_real_time_filtered_rows cases, test_3555_other_filters_and_pagination_are_preserved and test_3555_list_route_keeps_count_and_page_consistent fail: 49 failed, 24 passed. The fixed file was then restored byte-identical.

Checklist

  • My code follows the project's style guidelines
  • I have updated the documentation (if applicable)
  • I have not committed any sensitive data (API keys, credentials, etc.)
  • I have added appropriate logging for new functionality (not applicable: no new functionality)

No running Trinity instance, live PostgreSQL, enterprise module, agent or model call was used.

Exercise all five shared readers and JSON/CSV export on real temporary SQLite. RED: 48 failed, 21 passed before production changes.
Serialize details when cloning read rows into writer fixtures, and pin list pagination and legacy invalid-bound behavior. Final tests on original production source: 49 failed, 24 passed; fixed source: 73 passed.
Pad optional UTC-Z fractions in read-only SQL and normalize bounds with the existing UTC helper. Retain indexable raw-second ranges and legacy malformed-bound behavior without rewriting hash-chain data. Regression suite: 73 passed; audit neighbors: 116 passed. Original-source mutation: 49 failed, 24 passed.
@vybe

vybe commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

merge-train: ejected from this batch. It rides the next train once fixed.

The backend fix itself is solid. Reverting audit.py turns 49 of the 73 new tests red, and the tests run real queries through the real writer and routes. One regression at the upper edge needs a decision from you before merge:

The calendar day drill-down now drops events in the last second of the day. src/frontend/src/stores/auditLog.js:318 sends end_time = <day>T23:59:59Z. Before this PR the string comparison included that whole second (. sorts before Z). The new comparison in src/backend/db/audit.py (_filter_conditions) normalizes the bound to …T23:59:59.000000, so a row at 23:59:59.4Z is now excluded. Against the same rows on SQLite, the drill-down list returns 4 events on dev and 2 on this branch. The calendar cell for that day still reads 4.

Two ways to close it:

  • (a) Treat an upper bound with no fraction as covering the whole second (…:59 → …:59.999999). That matches the existing compliance-export normalization, so two audit exports don't disagree about the same end_time, and it fixes the drill-down without a frontend change.
  • (b) Keep the exact-instant meaning, send T23:59:59.999999Z from auditLog.js (and update the comment above it), and add a test for the day window.

Smaller, and mechanical: audit.py catches only ValueError around datetime.fromisoformat(bound) / to_utc_iso. An offset bound at the edge of the date range (e.g. 0001-01-01T00:00:00+01:00) raises OverflowError and the request returns a 500. Catching (ValueError, OverflowError) fixes it.

Your next push removes the status-needs-fix label automatically. That won't happen on a fork PR, so mention it in a comment and a maintainer will remove it.

@vybe vybe added the status-needs-fix PR has an unaddressed review/validation finding; cleared by the author's next push (#2815) label Oct 13, 2026
… bounds

An audit end_time with a time part and no fraction now covers the end of the
smallest unit it states: T23:59:59Z through :59.999999, T23:59Z through
23:59:59.999999, T23Z likewise. The calendar day drill-down sends
<day>T23:59:59Z, so it keeps the last second of the day again. For Z-suffixed
bounds this matches the earlier raw string comparison; for spellings such as
+00:00 or no suffix that comparison was imprecise, which is what Abilityai#3555 fixes,
so they follow the same rule rather than the old result. Date-only bounds,
bounds with a fraction and all lower bounds stay exact instants.

An offset bound at the edge of the date range (for example
0001-01-01T00:00:00+01:00) raises OverflowError when converted to UTC. Catch
it with ValueError so the request keeps the legacy string comparison instead
of returning a 500.

The normalized bound is now built with isoformat(timespec="microseconds"):
strftime("%Y") does not zero-pad years below 1000 on Linux, which broke the
fixed-width slices for bounds such as 0999-01-01T00:00:00Z.

Tests cover the day window through the readers and the real list and export
routes, hour, minute and second upper bounds, date-only and fractional bounds,
lower bounds, offset spellings, years before 1000 and the edge offset bounds
on every audit read route. The audit-trail flow doc states the rule and that
exports sharing a whole-second boundary can overlap.
@developerjillur

Copy link
Copy Markdown
Contributor Author

Thanks, both points were right.

An upper bound with a time part and no fraction now covers the end of the unit it states. T23:59:59Z, T23:59Z and T23Z each run through 23:59:59.999999, so the day drill-down keeps the last second again. For bounds written like these with a Z suffix this matches the old string comparison; +00:00 and suffix-less bounds now follow the same rule instead of the old string result. Date-only bounds, bounds with a fraction and lower bounds stay exact. The doc now says that adjacent exports sharing a boundary second, minute or hour can overlap, so consumers should de-duplicate by event_id.

Offset bounds outside the date range no longer raise OverflowError. They fall back to the old string comparison, so the route returns 200.

The bound text is now built with isoformat(timespec="microseconds") instead of to_utc_iso(), whose strftime("%Y") does not zero-pad years below 1000 on Linux with Python 3.13.

Tests cover the day window through the list and export routes, hour, minute and second bounds, years before 1000 and the edge offsets, and I ran them in Python 3.13 on Linux as well.

Could a maintainer remove the status-needs-fix label? A fork push does not clear it.

…time-bounds

# Conflicts:
#	tests/registry.json
@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

✅ Nightly unit-suite clean when this PR is merged into dev, all 3 seeds (head_sha: f0a98dcaad5bb84d7300febd28ca1d834289a254).

…time-bounds

# Conflicts:
#	tests/registry.json
@developerjillur

Copy link
Copy Markdown
Contributor Author

Closing this for now as part of a cleanup of my older pending contributions. Thank you for your time and feedback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status-needs-fix PR has an unaddressed review/validation finding; cleared by the author's next push (#2815)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants