Skip to content

fix(userstore): keep a played mark made in the same second as an unplayed mark - #2217

Merged
Quick104 merged 9 commits into
Silo-Server:mainfrom
blurbery:fix/userstore-same-second-replay
Oct 15, 2026
Merged

Quick104 merged 9 commits into
Silo-Server:mainfrom
blurbery:fix/userstore-same-second-replay

Conversation

@blurbery

@blurbery blurbery commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Closes #2193
Related issue: N/A
Validation tasks: unblocks #1238 C1, C2; unblocks #1240 C3, #1241 C3, #1242 C3

If an item is marked unplayed and then played again within the same second, for example a quick double toggle in Jellyfin or Emby, the mapped Silo profile ends up unwatched. Webhook sync logs both events as applied, so resending doesn't fix it. With this change the played mark lands and the item is watched.

A history removal stores its watermark (hidden_before) to the microsecond. The Postgres user store checked imported progress and history against it as whole-second RFC 3339 text, and watch state also handed imported history to the store in whole seconds. So a played write at 12:00:00.9 was checked as 12:00:00, which is before a removal at 12:00:00.5, and was dropped. This hits every write that carries its own event time: Jellyfin and Emby webhook sync (including the TogglePlayed marks from #2178), history import, watch-provider sync and client progress sync.

Approach

  • SetProgressAt and SetProgressIfNewer pass the event time itself to the watermark check, so Postgres compares two timestamptz values at the same precision. Those rows were already stored at full precision; only the check was rounded.
  • Watch state passes imported history to the store with its full time. The Postgres AddHistoryIfMissing compares that with the watermark at full precision. It still stores the whole second, as imports always have, unless that second is at or before the watermark; then it keeps the precise time, which is what keeps the row visible. Any row in the same second counts as the same play, so reruns still match rows written before this change, and a webhook mark and a later import of the same play don't both land.
  • A write at or before the removal still stays hidden. Only the precision of the comparison changes.
  • Responses don't change: Postgres still returns updated_at and watched_at as whole-second RFC 3339. Sub-second history rows already exist (a mark after a removal is stored at hidden_before plus one second), and history paging already handles them.
  • SQLite user store: it keeps timestamps as whole-second text, compares them as strings, and its watermark is whole-second too, so it can't tell which of two writes in one second came first. I left its behaviour alone. AddHistoryIfMissing there now cuts the new sub-second input back to whole seconds, because ...:05.5Z sorts before ...:05Z as text. Unplayed then played within one second still ends up unwatched on SQLite. I didn't change its storage format because the SQLite store is retired at 1.0.

Validation

  • New regression tests fail on main and pass on this branch: a Postgres store test of the removal boundary (writes at and before the removal stay hidden, a write later in the same second is visible, duplicates within the second are refused) and a webhook sync test that sends Jellyfin TogglePlayed and Emby item.markunplayed then item.markplayed within one second against the real Postgres store. Both are pinned in scripts/ci/db-contracts.txt.
  • A SQLite unit test covers the whole-second truncation and the duplicate check against an existing row.
  • Locally against a migrated PostgreSQL 18 database, go test passes for internal/userstore/pgstore, internal/webhooksync, internal/userdb, internal/watchstate and internal/historyimport.
  • CI on 0cc7f4b passes: all 16 checks, including Go lint, Go test, Go integration and the DB pins that run the two new tests (https://github.com/Silo-Server/silo-server/actions/runs/38042281972). Four checks were skipped by their path filters.

Evidence

Evidence: https://evidence.siloserver.org/r/silo-server/pr-2217/

The same Jellyfin UserDataSaved / TogglePlayed deliveries sent to a local server built from main and from this branch: played at 11:59:00, unplayed at 12:00:00.5, played at 12:00:00.9. After each one I read the profile's progress. Data is synthetic (one movie, one webhook connection, fresh database).

Before (main, bf63b3d):

played=true   2026-04-07T11:59:00Z    GET /api/v1/progress: [{"media_item_id":"evidence-movie","completed":true,"position_seconds":0,"updated_at":"2026-04-07T11:59:00Z"}]
played=false  2026-04-07T12:00:00.5Z  GET /api/v1/progress: []
played=true   2026-04-07T12:00:00.9Z  GET /api/v1/progress: []
webhook_sync_event_logs: applied, applied, applied

After (this branch, f5ca1ff):

played=true   2026-04-07T11:59:00Z    GET /api/v1/progress: [{"media_item_id":"evidence-movie","completed":true,"position_seconds":0,"updated_at":"2026-04-07T11:59:00Z"}]
played=false  2026-04-07T12:00:00.5Z  GET /api/v1/progress: []
played=true   2026-04-07T12:00:00.9Z  GET /api/v1/progress: [{"media_item_id":"evidence-movie","completed":true,"position_seconds":0,"updated_at":"2026-04-07T12:00:00Z"}]
webhook_sync_event_logs: applied, applied, applied

Surface and build: GET /api/v1/progress (native API, profile-scoped), local integrated server on PostgreSQL 18. The branch's later commit only changes duplicate detection within one second, which this sequence doesn't exercise.

Benchmarks

Not applicable. The change alters which timestamp a write is compared and stored at, not how much work it does: the same single-row lookups by primary key, with one extra parameter.

Risks

  • No migration, and existing rows aren't rewritten.
  • On Postgres, imported history written later in the same second as a removal is now stored with a sub-second watched_at. Reads already truncate history to the second for paging, so clients see the same whole-second value as before.
  • Imported history now treats two plays of the same item within one second as one. Before, two whole-second imports in the same second were already one row, so this only matters for rows stored at sub-second precision.
  • The Postgres AddHistory and AddHistoryIfMissing now parse watched_at as RFC 3339 before querying. Every caller already passes RFC 3339; a string only Postgres could read would now fail with a parse error.
  • SQLite keeps the same-second limitation described above.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • The Evidence section shows every change a user can see, or says there is none.

AI Disclosure

AI-assisted with Claude Opus. I directed the task and designed the work.

  • Harness: Claude Code (Claude desktop app, Code tab)
  • Tool(s): Claude Code
  • Model(s): claude-opus-5-5
  • Involvement: AI-assisted
  • Adversarial review: a separate Claude Code agent (claude-opus-5-5) with no access to the working session read the diff and the surrounding code, and checked the new SQL, the import and webhook callers, read-back consumers, the SQLite path and the tests. It found that a play in the removal's second could be stored twice when two sources reported it milliseconds apart; I fixed that by counting any row in the same second as the same play and added a test. It also suggested AddHistory insert the time it checks, which I did. Its note on an unreachable helper with the same rounding was left out of scope.

Note

Normalize imported watched-at timestamps to UTC whole seconds in userdb.AddHistoryIfMissing

Parses valid RFC 3339 watched-at values in the history import helper in progress.go and stores them as UTC whole-second text. The same normalized value is used for the SQLite visibility check and the insert. Inputs that cannot be parsed keep the prior handling.

  • Risk: sub-second replays now dedupe against a removal made in the same stored second, and imports within a removal's stored second stay hidden.

Macroscope summarized ff8c348.

RealtimeEventsProvider loads with the app and imported
adminDownloadStorageRootKey from the download storage API module, which
pulled that whole module into the launch chunk. The key now lives in
adminDownloadStorageCache, as adminSessionsKey does, so the API stays in
the admin Downloads chunk.

The launch bundle drops from 326,619 B to 326,313 B brotli, back inside
the budget check's tolerance.
A history removal stores its watermark to the microsecond, but imported
progress and history were checked against it as whole-second RFC 3339
text. A played mark in the same second as an earlier removal compared at
or before the watermark and stayed hidden, while webhook sync recorded
the event as applied.

The Postgres store now compares imported writes with the watermark as
timestamptz, and watch state hands imported history to the store with
its full time. Imported history keeps its whole-second stamp unless that
second is at or before the watermark, so replays still match rows stored
before. SQLite keeps whole-second text and truncates sub-second input.
An import that lands in a removal's second keeps its precise time, so an
exact-time duplicate check let the same play through twice when two
sources reported it a few milliseconds apart. Imported history now
treats any row in the same second as the same play, which also still
matches whole-second rows stored before. AddHistory inserts the time it
checked.
@silo-kody

silo-kody Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@coderabbitai

coderabbitai Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d5745dcd-7a03-427a-be8b-3279becc438d
📥 Commits

Reviewing files that changed from the base of the PR and between 234d06b and ff8c348.

📒 Files selected for processing: 4
  • internal/userdb/progress.go
  • internal/userstore/pgstore/progress.go
  • internal/watchstate/service.go
  • scripts/ci/db-contracts.txt

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 1 remain after this review.

📝 Walkthrough

Progress and imported-history timestamps now retain sub-second precision for removal-watermark comparisons. Imported history applies whole-second storage and same-second duplicate detection. Unit and database tests cover progress writes, imports, and Jellyfin and Emby webhook events.

Changes: History visibility

Layer / File(s) Summary
Timestamp inputs and visibility checks
internal/watchstate/service.go, internal/userstore/pgstore/progress.go
Imported timestamps retain nanosecond precision when passed to the store. PostgreSQL progress and history visibility checks use parsed time.Time values.
Imported-history watermark and duplicate handling
internal/userstore/pgstore/progress.go, internal/userdb/progress.go, internal/userdb/progress_test.go, internal/userstore/pgstore/same_second_removal_test.go, internal/webhooksync/service_db_test.go, scripts/ci/db-contracts.txt
Imported-history writes compare the precise timestamp to the removal watermark, store qualifying writes at whole-second precision, and detect duplicates within the same-second interval. Tests cover removals, replays, and webhook events.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix · Severity of issue fixed: Low

Suggested reviewers: quick104

Merge Risk: ⚪ Minimal · up to ff8c3

No actionable issue remains for the PostgreSQL fix. SQLite retains its disclosed same-second limitation; normal checks can proceed before merge.

Pre-merge checks: Passed 3 · Failed 2

Failed Failed checks: 2 warnings

Check name Status Explanation Resolution
Linked Issues check Warning Issue #2193 covers the Postgres and SQLite user-store progress and history paths. This pull request fixes the same-second watermark comparison for Postgres and passes imported history at sub-second pr… Implement the required same-second ordering behavior in the SQLite progress and history paths, including regression tests, or update the linked issue scope before merging.
Docstring Coverage Warning Docstring coverage is 55.56% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 10 files. (1 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 3 passed
Check name Status Explanation
Out of Scope Changes check Passed The changed user-store timestamp handling, watch-state import path, webhook-sync regression coverage, and database contract entries directly support issue #2193. The tests validate the required Postgr…
Title check Passed The title clearly identifies the primary fix: preserving a played mark made within the same second as an unplayed mark.
Description check Passed The description directly explains the same-second timestamp problem, the PostgreSQL and SQLite behavior, the implementation, tests, validation, evidence, and risks.
Full details: Linked Issues check

Explanation

Issue #2193 covers the Postgres and SQLite user-store progress and history paths. This pull request fixes the same-second watermark comparison for Postgres and passes imported history at sub-second precision. The SQLite store still formats SetProgressAt and SetProgressIfNewer timestamps to whole-second RFC 3339 text, and the PR states that the same-second played-after-unplayed case remains unwatched there. The linked issue's expected watched result is therefore not met for SQLite.

Full details: Docstring Coverage

Explanation

Docstring coverage is 55.56% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 10 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-10T09:29:23.188403Z 47cfc2b PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Quick104 Quick104 added priority: P2 Limited scope, workaround exists, or polish impact: usability Core flow broken or severely blocked labels Oct 10, 2026 — with Cursor
Comment thread internal/userdb/progress.go Resolved
@silo-kody

silo-kody Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

blurbery and others added 5 commits October 10, 2026 20:41
…second-replay

# Conflicts:
#	scripts/ci/db-contracts.txt
…dle"

This branch only carried that commit so the web launch bundle budget check would pass. Silo-Server#2246 fixed the budget on main, so the change now stays in Silo-Server#2204 alone.

This reverts commit e954671.
…second-replay

# Conflicts:
#	scripts/ci/db-contracts.txt
@Quick104

Copy link
Copy Markdown
Contributor

Review summary (head ff8c3488c)

I found no defects in this change, and I merged main into the branch to clear the scripts/ci/db-contracts.txt conflict.

What I changed on the branch

  • ff8c3488c merges main. The only conflict was the new pins block in scripts/ci/db-contracts.txt; I kept both sides. The branch now differs from main only in this PR's seven files.
  • I corrected the Validation tasks: line in the description. Webhook ingestion — Jellyfin #1238 C1 and C2 have no recorded results yet, so the right verb is unblocks, not changes: unblocks #1238 C1, C2; unblocks #1240 C3, #1241 C3, #1242 C3.

How I checked it

  • I ran the two new regression tests against main with a migrated PostgreSQL 18 (pgvector) database. Both fail there the way [bug] An item marked unplayed then played within one second stays unwatched #2193 describes: the write at .9 after a removal at .5 is dropped, and Jellyfin TogglePlayed and Emby markunplayed then markplayed leave the item unwatched. Both pass on this branch.
  • On the merged head, go test passes for internal/userstore/..., internal/userdb, internal/watchstate, internal/webhooksync, internal/historyimport and internal/watchsync against the same database. The DB contract pins pass, including the two new ones. make lint-changed reports no issues.
  • A multi-angle code review and an independent second review by another model both came back clean. I also traced and ruled out the following:
    • Out-of-order delivery. A removal processed after a same-second play still hides it. That doesn't depend on the precision this PR stores, because removeHistoryItems raises the watermark to MAX(watched_at).
    • A hidden row counted as a duplicate. A row left hidden by a provider-ID merge can block a same-second import, but main drops that import too.
    • The stricter watched_at parse. It can't fail for any production caller: the only one is the AddVisibleHistory fallback, which always passes RFC 3339.
    • Paging and responses. History cursors already truncate to the second on both sides, and responses still format whole seconds.

Remaining

  • On the SQLite user store, unplayed then played within one second still ends up unwatched. The description discloses this, and it's reasonable given that store retires at 1.0.

Validated features: no passed case on the v1.0 board reaches this code. The affected tasks (#1238, #1240–#1242) have no recorded results yet.

User manual: unaffected. The webhook and history-import pages don't describe same-second ordering.

Apple / Android: no client change. Response shapes and the API contract are unchanged, and jellycompat goes through the same store, so it gets the fix too.

Fit: 9/10 · Readiness: 9/10 — ready (assuming CI is green)

  • Fit: watch state should converge on the last action. This fixes it at the store boundary that every import path shares, without adding a setting or new surface.
  • Readiness: the fix is narrow and its boundary tests fail on main and pass here. The import lock still covers the new statement, and existing whole-second rows still dedupe against new imports.

AI-assisted review: Claude Code (claude-opus-5-5), with a second review by Codex (gpt-6.1-sol).

@macroscopeapp

macroscopeapp Bot commented Oct 15, 2026

Copy link
Copy Markdown

The Validation tasks: line claims these cases are unblocked, but the task records do not mark them failed or blocked. The results for #1238 C1–C3 and #1240 C1–C3, #1241 C1–C3, and #1242 C1–C3 are all Not run; the #1238 comment also says its #2178 sandbox run is not a validator result. I found no recorded result for this PR to invalidate or unblock. Please replace the line with:

Validation tasks: none

Automated check: Macroscope check run agent (gpt-6-luna). No validation was performed.

Posted via Macroscope — v1 validation impact

@Quick104

Copy link
Copy Markdown
Contributor

I'm keeping the line. In this repository, unblocks covers any case a change lets run or pass, including cases nobody has run yet. It doesn't mean a recorded failure. The point is to link the PR into each task's timeline before a validator tests it.

The cases are reachable:

none would drop those links.

@Quick104
Quick104 merged commit e58824b into Silo-Server:main Oct 15, 2026
20 checks passed
@blurbery
blurbery deleted the fix/userstore-same-second-replay branch November 6, 2026 00:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

impact: usability Core flow broken or severely blocked priority: P2 Limited scope, workaround exists, or polish

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[bug] An item marked unplayed then played within one second stays unwatched

2 participants