Skip to content

fix(storage): derive session timestamps from message evidence - #3285

Merged
Sinity merged 1 commit into
masterfrom
fix/storage/session-timestamps-from-messages
Jul 26, 2026
Merged

Sinity merged 1 commit into
masterfrom
fix/storage/session-timestamps-from-messages

Conversation

@Sinity

@Sinity Sinity commented Jul 26, 2026 •

Copy link
Copy Markdown
Owner

Summary

Sessions whose provider payload carries no session-level timestamp (Codex, most Claude Code sessions, Hermes/observer material) now get created_at_ms/updated_at_ms derived from their own messages' occurred_at_ms, at write time and via a bounded backfill for already-archived rows.

Problem

sessions.created_at_ms/updated_at_ms are plain columns the writer only sets from provider-supplied session-level timestamps. On the live archive, 65,946 of 83,198 sessions (79%) have both NULL. since:/until: filters, recency ordering, and --by year/month histograms silently exclude that four-fifths of the archive, even though the excluded sessions' individual messages are timestamped.

Solution

  • write_parsed_session_to_archive falls back to the min/max of the incoming write's own message occurred_at_ms when the provider gives no session-level created_at/updated_at. Computed over the full parsed message set (before prefix-tail slicing) so a prefix-sharing child's derived created_at_ms reflects the whole conversation's start. Provider-supplied timestamps always win; a session with no timestamped message either stays NULL rather than being backdated to the ingest wall clock. The skip-stale-replace freshness guard (incoming_freshness_ms) now reads the same derived value, so a genuinely stale replay of a no-session-timestamp provider is correctly skipped instead of always winning through an unconditional "freshness unknown" bypass.
  • New session_timestamp_backfill maintenance target (repair, non-destructive): one bounded UPDATE ... FROM aggregate over messages, COALESCE-guarded so any existing provider timestamp is preserved — safe to run repeatedly. Registered in MAINTENANCE_TARGET_SPECS, PREVIEW_HANDLERS, REPAIR_HANDLERS, and the docs-surface/artifact-graph coverage registries.

Verification

  • devtools test tests/unit/storage/test_session_timestamp_backfill.py tests/unit/storage/test_archive_tiers_write.py tests/unit/core/test_maintenance_targets.py tests/unit/devtools/test_artifact_graph.py tests/unit/storage/test_session_insight_refresh.py tests/unit/storage/test_repair.py — 175 passed.
  • devtools verify --quick — pass.

Not yet done: running the backfill against the live archive (polylogue ops maintenance --repair --target session_timestamp_backfill) and recording the receipt — planned as a follow-up action once this merges, per polylogue-m3p9's acceptance criteria.

Ref polylogue-m3p9

Summary by CodeRabbit

  • New Features

    • Session timestamps are now derived from message timing data when provider timestamps are unavailable.
    • Added a maintenance repair target to backfill missing session timestamps, with preview and dry-run support.
    • Existing timestamps are preserved, and sessions without usable evidence remain unchanged.
  • Documentation

    • Updated CLI, maintenance, topology, and test-quality documentation to describe the new repair target.
  • Bug Fixes

    • Improved timestamp handling for archived and appended sessions, including stale-update detection.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Jul 26, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 28 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: d58780d0-8c82-4c85-8424-0c963f8badc4

📥 Commits

Reviewing files that changed from the base of the PR and between b71bde6 and 0f98aaf.

📒 Files selected for processing (14)
  • docs/cli-reference.md
  • docs/maintenance.md
  • docs/plans/topology-target.yaml
  • docs/test-quality-workflows.md
  • docs/topology-status.md
  • polylogue/maintenance/targets.py
  • polylogue/storage/repair.py
  • polylogue/storage/session_timestamp_backfill.py
  • polylogue/storage/sqlite/archive_tiers/write.py
  • tests/unit/core/test_maintenance_targets.py
  • tests/unit/devtools/test_artifact_graph.py
  • tests/unit/storage/test_archive_tiers_write.py
  • tests/unit/storage/test_session_insight_refresh.py
  • tests/unit/storage/test_session_timestamp_backfill.py
📝 Walkthrough

Walkthrough

Adds message-derived session timestamp fallbacks during archive writes, a bounded session_timestamp_backfill repair target for legacy rows, shared maintenance dispatch wiring, regression tests, and updated maintenance, topology, and coverage documentation.

Changes

Session timestamp maintenance

Layer / File(s) Summary
Archive timestamp derivation
polylogue/storage/sqlite/archive_tiers/write.py, tests/unit/storage/test_archive_tiers_write.py, tests/unit/storage/test_session_insight_refresh.py
Archive writes derive missing session timestamps from message evidence, preserve provider values, update freshness handling, and test null, precedence, lineage, and merge-append cases.
Timestamp backfill engine
polylogue/storage/session_timestamp_backfill.py, tests/unit/storage/test_session_timestamp_backfill.py
Adds candidate counting, preview, NULL-only updates, dry-run and commit handling, failure reporting, and tests for legacy, partial, idempotent, and undatable sessions.
Maintenance registration and dispatch
polylogue/maintenance/targets.py, polylogue/storage/repair.py, docs/cli-reference.md, docs/maintenance.md, docs/test-quality-workflows.md, tests/unit/core/test_maintenance_targets.py
Registers session_timestamp_backfill as a derived repair target and exposes it through preview, repair, help text, scope, and coverage expectations.
Topology and coverage reporting
docs/plans/topology-target.yaml, docs/topology-status.md, tests/unit/devtools/test_artifact_graph.py
Updates generated location counts, adds the new storage module to topology reporting, and adjusts uncovered-target and operation expectations.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Doctor
  participant RepairDispatch
  participant SessionTimestampBackfill
  participant SQLite
  Doctor->>RepairDispatch: select session_timestamp_backfill
  RepairDispatch->>SessionTimestampBackfill: preview or run backfill
  SessionTimestampBackfill->>SQLite: aggregate message timestamps
  SQLite-->>SessionTimestampBackfill: candidate or repaired row count
  SessionTimestampBackfill-->>RepairDispatch: BackfillResult
  RepairDispatch-->>Doctor: RepairResult
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 61.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise, specific, and matches the main change: deriving session timestamps from message evidence.
Description check ✅ Passed It covers Summary, Problem, Solution, Verification, and follow-up notes, but it omits the requested Changelog section.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/storage/session-timestamps-from-messages

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@polylogue/storage/repair.py`:
- Around line 6688-6709: Add preview_session_timestamp_backfill and
repair_session_timestamp_backfill to the module’s __all__ export list, matching
the established export parity of the other preview/repair handler pairs. Do not
alter the handler implementations.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 4ccad804-0cc7-4a7a-9ed3-57673edc2176

📥 Commits

Reviewing files that changed from the base of the PR and between 59f613e and b71bde6.

📒 Files selected for processing (14)
  • docs/cli-reference.md
  • docs/maintenance.md
  • docs/plans/topology-target.yaml
  • docs/test-quality-workflows.md
  • docs/topology-status.md
  • polylogue/maintenance/targets.py
  • polylogue/storage/repair.py
  • polylogue/storage/session_timestamp_backfill.py
  • polylogue/storage/sqlite/archive_tiers/write.py
  • tests/unit/core/test_maintenance_targets.py
  • tests/unit/devtools/test_artifact_graph.py
  • tests/unit/storage/test_archive_tiers_write.py
  • tests/unit/storage/test_session_insight_refresh.py
  • tests/unit/storage/test_session_timestamp_backfill.py

Comment on lines +6688 to +6709
def preview_session_timestamp_backfill(*, count: int) -> RepairResult:
"""Preview handler for the #m3p9 session-timestamp backfill.

Thin shim over ``session_timestamp_backfill.preview_backfill`` so the
repair orchestrator's preview dispatch keeps working.
"""
from polylogue.storage.session_timestamp_backfill import preview_backfill

return _session_timestamp_backfill_to_repair_result(preview_backfill(count=count))


def repair_session_timestamp_backfill(config: Config, dry_run: bool = False) -> RepairResult:
"""Derive ``sessions.created_at_ms``/``updated_at_ms`` from message
evidence for rows ingested before the write path fell back to it.

Delegates to ``storage.session_timestamp_backfill.run_backfill``; the
implementation lives there to keep this module under its file-size
budget (see ``docs/plans/file-size-budgets.yaml``).
"""
from polylogue.storage.session_timestamp_backfill import run_backfill

return _session_timestamp_backfill_to_repair_result(run_backfill(config, dry_run=dry_run))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Add the new handlers to __all__.

Every other preview/repair pair in this module (preview_message_type_backfill/repair_message_type_backfill, preview_session_insights/repair_session_insights) is exported in __all__, but preview_session_timestamp_backfill/repair_session_timestamp_backfill are missing, breaking that established parity.

🔧 Proposed fix
     "preview_orphaned_messages",
     "preview_message_type_backfill",
+    "preview_session_timestamp_backfill",
     "preview_session_insights",
     "raw_materialization_replay_backlog",
     "raw_materialization_scale_profile",
     "repair_empty_sessions",
     "repair_message_type_backfill",
+    "repair_session_timestamp_backfill",
     "repair_orphaned_attachments",

Also applies to: 6837-6872

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@polylogue/storage/repair.py` around lines 6688 - 6709, Add
preview_session_timestamp_backfill and repair_session_timestamp_backfill to the
module’s __all__ export list, matching the established export parity of the
other preview/repair handler pairs. Do not alter the handler implementations.

…gue-m3p9)

Problem: sessions.created_at_ms/updated_at_ms are plain columns the
writer only sets from provider-supplied session-level timestamps.
Codex, most Claude Code sessions, and Hermes/observer material never
carry those at the session level even though their messages are
individually timestamped, so 65,946 of 83,198 sessions (79%) on the
live archive have both columns NULL. since:/until:/recency ordering
and --by year/month histograms silently exclude that four-fifths of
the archive.

What changed:
- write_parsed_session_to_archive falls back to the min/max of the
  incoming write's own message occurred_at_ms when the provider gives
  no session-level created_at/updated_at. A prefix-sharing child's
  derived created_at_ms reflects the whole conversation's start (the
  full parsed message set, before prefix-tail slicing); the derived
  max is correct either way since the newest message always survives
  slicing into the tail. Provider-supplied timestamps always win; a
  session with no timestamped message either (genuinely undatable)
  stays NULL, never backdated to the ingest wall clock.
  incoming_freshness_ms (the skip-stale-replace guard) now reads the
  same derived value, so a genuinely stale replay of a
  no-session-timestamp provider is correctly skipped instead of always
  winning through an unconditional "freshness unknown" bypass.
- New session_timestamp_backfill maintenance target (repair, non-
  destructive) backfills the derivation for already-archived rows via
  one bounded UPDATE ... FROM aggregate over messages, COALESCE-guarded
  so any existing provider timestamp is preserved. Registered in
  MAINTENANCE_TARGET_SPECS, PREVIEW_HANDLERS, REPAIR_HANDLERS, and the
  docs-surface/artifact-graph coverage registries.

Verification: devtools test tests/unit/storage/test_session_timestamp_backfill.py
tests/unit/storage/test_archive_tiers_write.py tests/unit/core/test_maintenance_targets.py
tests/unit/devtools/test_artifact_graph.py tests/unit/storage/test_session_insight_refresh.py
tests/unit/storage/test_repair.py (175 passed); devtools verify --quick (pass).

Ref polylogue-m3p9

Co-Authored-By: Codex <[email protected]>
Co-Authored-By: Claude <[email protected]>
@Sinity
Sinity force-pushed the fix/storage/session-timestamps-from-messages branch from b71bde6 to 0f98aaf Compare July 26, 2026 20:29
@Sinity
Sinity merged commit f4cd341 into master Jul 26, 2026
3 checks passed
@Sinity
Sinity deleted the fix/storage/session-timestamps-from-messages branch July 26, 2026 20:34
Sinity added a commit that referenced this pull request Jul 29, 2026
Problem: three snapshot files pinned CLI help/output text and archive
diagnostics from before several unrelated, already-merged feature changes:
- #3311 (93f2982, "bounded predicate attribution for zero-hit queries")
  added the `--why` flag to query verbs.
- #3285 (f4cd341, "derive session timestamps from message evidence")
  added the `session_timestamp_backfill` maintenance target.
- SOURCE_SCHEMA_VERSION and INDEX_SCHEMA_VERSION advanced (13->14, 43->45)
  via already-landed additive durable/derived migrations on this branch.
- This session's schema-annotation fix (Ref polylogue-c66i, previous
  commits) changed synthetic-corpus generated content (real user/assistant
  text instead of `synthetic-<n>` placeholders), which legitimately changed
  demo-fixture token counts, evidence-ref ordering, and wall-clock
  distribution figures baked into these snapshots.

None of these are test bugs or production regressions -- the snapshots were
simply stale relative to already-merged, intentional changes.

What changed: regenerated via `pytest ... --snapshot-update`:
- tests/unit/cli/__snapshots__/test_help_snapshots.ambr
- tests/unit/cli/__snapshots__/test_terminal_snapshots.ambr (--why help
  text, session_timestamp_backfill --target choice)
- tests/unit/cli/__snapshots__/test_plain_cli_snapshots.ambr (token counts,
  evidence_refs ordering, wallclock distribution, source/index tier
  user_version, sqlite_stat1_rows)

Verification:
- devtools test tests/unit/cli/test_help_snapshots.py
  tests/unit/cli/test_terminal_snapshots.py
  tests/unit/cli/test_plain_cli_snapshots.py -> 34 passed (21 snapshots
  passed, 0 updated on the verification re-run).

Ref polylogue-c66i

Co-Authored-By: Claude <[email protected]>
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