Skip to content

[ryoku] ryogami: workshop previews reuse cached clips and sweep orphan temps - #929

Merged
neur0map merged 2 commits into
Ryoku-dev:unstable-devfrom
LangerSword:fix/ryogami-workshop-preview-reuse
Nov 30, 2026
Merged

neur0map merged 2 commits into
Ryoku-dev:unstable-devfrom
LangerSword:fix/ryogami-workshop-preview-reuse

Conversation

@LangerSword

@LangerSword LangerSword commented Nov 21, 2026 •

Copy link
Copy Markdown

Fixes #920.

Two changes, two commits.

1. Preview reuse keys on recorded source size, not Steam-managed mtimes.

The report's mechanism, traced in the code: ensureVideoPreview does skip when we--<id>-prev.mp4 is newer than the source, so a finished clip is reused. What defeats that check is its comparison basis: Steam revalidation moves workshop source mtimes at every login, so a warm library reads as entirely stale and the daemon re-encodes all of it at every start. The login double start then kills the batch mid-encode, feeding part 2.

Workshop clips now record the source size they were rendered from beside the clip (<prev>.size), and a clip whose size record still matches is reused without a render. Local videos keep the unchanged mtime rule. The Entry wire contract is untouched.

TestWorkshopPreviewReuseIgnoresSteamMtime drives the real ffmpeg path: source mtime pushed an hour into the future, clip replaced by a sentinel, scan, sentinel intact; then the source swapped for a different size, and only that re-renders.

2. Startup sweeps orphan transcode temps.

A killed transcode never cleans its .tmp.* file, and the login restart makes kills routine (the report measured ~840 MB of dead partials over three days). sweepTmpFiles runs once at daemon start, before the first scan, over the four cache media dirs, the only moment no generator can hold a live temp. TestSweepTmpFilesRemovesOnlyTemps covers keep and remove.

On the concurrency observation in the report: renders already run on the performance.maxThumbJobs pool (default 16, 1 to 32, Hub-configurable). With reuse working, a warm boot renders nothing at all, so the pool stops being the bottleneck.

Two e2e tests fail in my sandbox on the clean base tree as well (daemon socket never appears), so they are environmental rather than from this change; every other test in the ryogami module passes, gofmt and vet clean.

(Prepared with an AI agent as the AGENTS.md workflow invites; the mechanism was traced in the real code and every behaviour here is test-driven through the real ffmpeg path.)

Confidence Score: 4/5 · The PR still has the blocking night light boot issue from the earlier review; the new preview issue is non-blocking.RetriggerView in GreptileConfidence Score: 4/5

The PR still has the blocking night light boot issue from the earlier review; the new preview issue is non-blocking.

FindingsFix All in Claude CodeFindings

  1. P1 Boot restore bypasses the schedule. ▶
  2. P2 Changed videos keep old previews ▶
Fix with agent prompt
### Issue 1
ryoku/shell/ipc/nightlight_schedule.go:294-310
The first daylight tick clears `schedArmed` when the backend is still off, but it leaves the saved enabled marker untouched. Login separately starts `ryoku-cmd-nightlight restore`, with no ordering against this tick. If restore runs afterward, it starts the light from that marker after the one-time check has finished. Later ticks see the same `schedLastDesire` and leave it on. Coordinate startup restore with the schedule check so this boot case is covered too.

### Issue 2
ryoku/shell/ryogami/daemon/scan.go:628-629
**Changed videos keep old previews.** The new cache trusts size and `mtime`, but `weVideoSource` rounds the timestamp to whole seconds. If different source bytes arrive with the same size and timestamp second, this returns the old identity without reading the file. `ensureVideoPreview` then keeps the old clip on every later scan, even after the write finishes.

Use a stronger check for whether the file changed, including finer timestamps and file replacement, or clear its saved identity when the source changes.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Workshop previews now reuse saved content identities, and startup removes abandoned temporary files before cache jobs begin.

  • Workshop previews match the source contents before reusing a clip.
  • Ryogami clears abandoned media temp files when it starts.

Reviews (8) · Last reviewed commit: "[global] ryogami: fix preview cleanup an..." · Reviewed by Greptile

Copilot AI lite review requested due to automatic review settings November 21, 2026 00:54

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

@neur0map neur0map left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🔴 Changes requested — 0 critical and 2 major issue(s): see the inline comments and the walkthrough for fixes and an agent-ready prompt.

Comment thread CHANGELOG.md Outdated
Comment on lines +26 to +28
- **Night Light schedules now reconcile the running backend once when they are
enabled or restored, so a light left on during daylight turns off at the next
tick instead of waiting for the next sunrise edge (#919)**

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🟡 minor · Maintainability · fix: medium effort

This PR also changes Night Light scheduling, independently of the Ryogami preview and temp cleanup work. Split the Night Light changes into a separate PR to keep one logical change per PR.

Reply here to discuss, say it's fixed, or explain why it's intended — no mention needed.

Comment thread ryoku/shell/ipc/nightlight_schedule.go Outdated
Comment on lines +294 to +301
if armed != 0 {
if want != n.running() {
var err error
if want {
err = n.intent("on")
} else {
err = n.intent("off")
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🟠 major · Possible Bug · fix: medium effort

Disabling the schedule does not change schedArmed, so an in-flight armed tick can still apply its old want after the user turns scheduling off. Invalidate in-flight ticks on disable and synchronize the backend action with schedule changes so disabling leaves the current state alone.

Reply here to discuss, say it's fixed, or explain why it's intended — no mention needed.

Comment thread ryoku/shell/ryogami/daemon/scan.go Resolved
Comment thread ryoku/shell/ryogami/daemon/scan.go Resolved
@neur0map

neur0map commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

🦊 mika's review

Incremental review: new commits since the last checkpoint.

Summary

  • Reuse Workshop previews across Steam timestamp changes using source identities.
  • Serialize preview publication and record identities alongside rendered clips.
  • Sweep abandoned cache temporary files during startup.
  • Add regression tests for preview reuse, metadata failures, and cleanup.

Change diagram

flowchart LR
  Workshop["Workshop video"] --> Identity["Size and head hash"]
  Identity --> Preview["Preview reuse or render"]
  Preview --> Metadata["Atomic identity record"]
  Startup["Daemon startup"] --> Sweep["Cache temp sweep"]
  Sweep --> Scan["Initial scan"]
Loading

Estimated review effort: 3/5 · risk: high

📁 Walkthrough details

CHANGELOG.md

  • Document the Workshop preview reuse and startup cleanup fixes.
    • Add entries for issue #920.

ryoku/shell/ryogami/daemon/daemon.go

  • Run the cache temp sweep before the startup rescan.
    • Invoke sweepTmpFiles after workspace restoration.

ryoku/shell/ryogami/daemon/scan.go

  • Reuse Workshop previews based on source size and a hash of the first 64 KiB; retain mtime-based reuse for local videos.
  • Serialize renders per preview and publish identity metadata through a temporary file.
  • Add a sweep for temporary artifacts in four wallpaper cache directories.
    • Add refcounted per-preview render locks.
    • Store Workshop source identities in .meta sidecars.
    • Remove stale metadata before publishing replacement clips.
    • Sweep cache files matching *.tmp.*.

ryoku/shell/ryogami/daemon/scan_test.go

  • Add coverage for sweeping temporary cache files while retaining a finished preview.
    • Add TestSweepTmpFilesRemovesOnlyTemps.

ryoku/shell/ryogami/daemon/workshop_previews.go

  • Mark Workshop video sources so preview generation uses identity-based reuse.
    • Set the we flag on scanned Workshop videos.

ryoku/shell/ryogami/daemon/workshop_previews_test.go

  • Add ffmpeg-backed coverage for timestamp changes, changed sources, and preview metadata failures.
  • Check that idle preview lock entries are released.
    • Test reuse after mtime changes and rerendering after source changes.
    • Test unreadable identities and unremovable metadata.
    • Test lock registry cleanup.

Findings

Severity Category Fix effort File Issue
🟠 major correctness medium ryoku/shell/ryogami/daemon/scan.go Possible Bug — A same-size workshop update that changes video data after the first 64 KiB leaves this identity unchanged, so the old preview is reused indefinitely. Hash the complete source or use another reliable content identity; add…
🟡 minor maintainability low ryoku/shell/ryogami/daemon/workshop_previews_test.go Maintainability — The new test comments include reviewer attribution, which the repository forbids in comments. Remove the parenthesized attribution references from these tests.

⚡ Quick fixes by effort

Low effort (apply from the diff):

  • ryoku/shell/ryogami/daemon/workshop_previews_test.go:215 — Maintainability — The new test comments include reviewer attribution, which the repository forbids in comments. Remove the parenthesized attribution references from these tests.

Medium effort (a function-level change):

  • ryoku/shell/ryogami/daemon/scan.go:604 — Possible Bug — A same-size workshop update that changes video data after the first 64 KiB leaves this identity unchanged, so the old preview is reused indefinitely. Hash the complete source or use another reliable content identity; add…
🤖 Prompt for AI agents (click, copy, paste into Claude/Codex)
Fix the following issues found by mika-agent on Ryoku-dev/ryoku#929 (branch fix/ryogami-workshop-preview-reuse):

- ryoku/shell/ryogami/daemon/scan.go:604-610 — Possible Bug (major severity, medium effort): A same-size workshop update that changes video data after the first 64 KiB leaves this identity unchanged, so the old preview is reused indefinitely. Hash the complete source or use another reliable content identity; add…
- ryoku/shell/ryogami/daemon/workshop_previews_test.go:215-217 — Maintainability (minor severity, low effort): The new test comments include reviewer attribution, which the repository forbids in comments. Remove the parenthesized attribution references from these tests.

For each: verify it is real in the current code, apply the smallest correct fix, and run the repo's tests. Skip anything already resolved and say why.
🛠 Deterministic checks run
  • golangci-lint: not installed (skip)

🚦 Merge recommendation: changes_required


🦊 Generated by Mika — the Ryoku org's self-hosted AI code reviewer. Machine findings: verify before merging.

@neur0map neur0map added area:ryoku Ryoku project area type:bug A reported problem labels Nov 21, 2026
Comment thread ryoku/shell/ryogami/daemon/daemon.go Resolved
Comment thread ryoku/shell/ryogami/daemon/scan.go Resolved
Comment thread ryoku/shell/ipc/nightlight_schedule.go Outdated
Comment on lines +294 to +310
if armed != 0 {
if want != n.running() {
var err error
if want {
err = n.intent("on")
} else {
err = n.intent("off")
}
if err != nil {
log.Printf("ryoku-shell: night light schedule tick failed: %v", err)
return // retry on the next tick: do not record an action that did not land
}
}
n.schedMu.Lock()
if n.schedArmed == armed {
n.schedArmed = 0
n.schedLastDesire = want

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Boot restore bypasses the schedule. The first daylight tick clears schedArmed when the backend is still off, but it leaves the saved enabled marker untouched. Login separately starts ryoku-cmd-nightlight restore, with no ordering against this tick. If restore runs afterward, it starts the light from that marker after the one-time check has finished. Later ticks see the same schedLastDesire and leave it on. Coordinate startup restore with the schedule check so this boot case is covered too.

Prompt To Fix With AI
This is a comment left during a code review.
Path: ryoku/shell/ipc/nightlight_schedule.go
Line: 294-310

Comment:
**Boot restore bypasses the schedule.** The first daylight tick clears `schedArmed` when the backend is still off, but it leaves the saved enabled marker untouched. Login separately starts `ryoku-cmd-nightlight restore`, with no ordering against this tick. If restore runs afterward, it starts the light from that marker after the one-time check has finished. Later ticks see the same `schedLastDesire` and leave it on. Coordinate startup restore with the schedule check so this boot case is covered too.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Claude Code Fix in Codex

@LangerSword
LangerSword force-pushed the fix/ryogami-workshop-preview-reuse branch from 9ec56fe to 812f03c Compare November 21, 2026 06:27

@neur0map neur0map left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🔍 Review findings — 1 blocking issue(s): see the inline comments and the walkthrough for details.

🧹 Nitpicks (1) — optional, not blocking
  1. ryoku/shell/ryogami/daemon/scan.go:617-624 — Suggestion: bug — Avoid globbing the cache directory path

    Suggested change

func sweepTmpFiles(cacheDir string) {
  for _, sub := range []string{"wallpaper/thumbs", "wallpaper/thumbs-sm", "wallpaper/video-thumbs", "wallpaper/anim"} {
    dir := filepath.Join(cacheDir, sub)
    entries, _ := os.ReadDir(dir)
    for _, entry := range entries {
      if strings.Contains(entry.Name(), ".tmp.") {
        _ = os.Remove(filepath.Join(dir, entry.Name()))
      }
    }
  }
}

Comment thread ryoku/shell/ryogami/daemon/scan.go Resolved
@LangerSword

Copy link
Copy Markdown
Author

All four findings addressed:

  • Split done. The branch was cut on top of the nightlight branch by mistake; it is now rebased straight onto unstable-dev, so this PR carries only the two ryogami commits plus the review fix below. The Night Light work lives in [ryoku] shell: night light schedule reconciles once on load and change #928 alone.
  • Size record leads. For workshop sources the timestamps never decide anymore: it.we reads the recorded size alone, so a redownload carrying an old manifest mtime onto a changed source cannot reuse a stale clip. The changed source in the test now carries an old mtime, older than the clip, pinning exactly the flagged case.
  • Record write fails safe. writePrevSourceSize reports its error now, and a failed write removes the record rather than leaving a stale one that could later authorize a wrong reuse.
  • The armed-tick finding belongs to [ryoku] shell: night light schedule reconciles once on load and change #928 (it was only in this diff through the branch overlap): the armed tick now re-reads the mode under the lock and drops a schedule that moved while it was in flight; that is pushed there.

Ryogami module suite passes, gofmt and vet clean.

Comment thread ryoku/shell/ryogami/daemon/scan.go Resolved
@LangerSword

Copy link
Copy Markdown
Author

Both round-2 findings addressed.

The record-write window (scan.go:590): the old record is now removed before the replacement clip is published, and the new record is written only after the rename lands. A kill anywhere in the sequence leaves either the new record or none; a stale record describing a replaced clip cannot survive.

The crossed writers (greptile's P2, same family): each clip's render and publication is now serialized per preview path (a sync.Map of mutexes keyed by the clip path). Two overlapping scans can still render different clips in parallel, but the same clip's clip-and-record writes can no longer cross between two writers, so an old clip can never end up described by a new size.

The glob nitpick for the sweep is noted and left as is: filepath.Glob on a fixed, daemon-owned cache directory is safe here, and ReadDir would only save one stat per non-matching entry.

Workshop preview and sweep tests pass, gofmt and vet clean.

@neur0map neur0map left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🔍 Review findings — 2 blocking issue(s): see the inline comments and the walkthrough for details.

Comment thread ryoku/shell/ryogami/daemon/scan.go Resolved
Comment thread ryoku/shell/ryogami/daemon/scan.go Resolved
@LangerSword

Copy link
Copy Markdown
Author

Both round-3 findings addressed.

The same-size update (scan.go:575): valid and the sharper of the two, because it is the failure my size-only fix traded in. The record beside each clip is now an identity, not a byte count: the source's size plus the SHA-256 of its first 64 KiB, stored as one line in <prev>.meta. Steam revalidation never rewrites bytes, so the identity survives a login's touch pass exactly as the size did; a real update swaps the file, and even when the byte count coincides the head moves with it. Hashing 64 KiB of a 500 MiB source is a rounding error next to the transcode it decides. The reuse test pins the case: a one-byte metadata flip (Lavf to Lavq) with the byte count unchanged re-renders, and the recorded identity under the new clip matches the flipped source.

The lock registry (scan.go:551): the per-clip render lock is now refcounted and releases its registry entry when nothing waits on it, so a library that churns videos does not grow it. The crossed-writers guarantee from the round-2 fix is unchanged.

The two e2e failures in the module run are the same environmental pair from before my branch (daemon socket never appears on this sandbox, reproduced on the clean base). Everything else passes, gofmt and vet clean.

@LangerSword

Copy link
Copy Markdown
Author

@neur0map Following up on #929. The round-3 fixes are in head 16b6e6d, but your CHANGES_REQUESTED review is still on the older d225900, so mika hasn't picked up the identity-hash change. Could you re-run the review or dismiss that stale one? I can address anything it finds.

@neur0map neur0map left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🔴 Changes requested — 0 critical and 1 major issue(s): see the inline comments and the walkthrough for fixes and an agent-ready prompt.

Comment thread ryoku/shell/ryogami/daemon/scan.go Outdated
Comment on lines +604 to +610
head := make([]byte, previewHeadBytes)
n, err := io.ReadFull(f, head)
if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
return ""
}
sum := sha256.Sum256(head[:n])
return strconv.FormatInt(size, 10) + ":" + hex.EncodeToString(sum[:8])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🟠 major · Possible Bug · fix: medium effort

A same-size workshop update that changes video data after the first 64 KiB leaves this identity unchanged, so the old preview is reused indefinitely. Hash the complete source or use another reliable content identity; add a test that changes bytes beyond the hashed prefix.

Reply here to discuss, say it's fixed, or explain why it's intended — no mention needed.

Comment on lines +215 to +217
// A source whose identity cannot be computed, and a clip with no identity
// record, are not a match: two empty strings are not evidence the clip is
// current. This is the tail of the size-before-mtime fix (mika 3f8f5d83).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🟡 minor · Maintainability · fix: low effort

The new test comments include reviewer attribution, which the repository forbids in comments. Remove the parenthesized attribution references from these tests.

Reply here to discuss, say it's fixed, or explain why it's intended — no mention needed.

@LangerSword
LangerSword force-pushed the fix/ryogami-workshop-preview-reuse branch from 7abd85e to 3e22fc6 Compare November 23, 2026 15:20
@neur0map

Copy link
Copy Markdown
Member

I've reviewed 5 pushes on this PR automatically, so I'll stop doing full passes here and only check whether open threads get fixed. Add the mika:review label or comment @ryoku-mika review for another full review.

@LangerSword

Copy link
Copy Markdown
Author

Fixed the findings: workshop source identity now hashes the full file, records are written atomically, and reviewer attributions were removed from test comments. New head 3e22fc6.

Comment thread ryoku/shell/ryogami/daemon/scan.go Resolved
@LangerSword

Copy link
Copy Markdown
Author

@ryoku-mika review

@Sipper1236 Sipper1236 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Good change, but hashing only the first 64 KiB misses same-size edits later in a video, so the old preview can stick around. Please key it to the full source.

Note: Fixed: Workshop previews hash the full source and write identity records atomically
@LangerSword
LangerSword force-pushed the fix/ryogami-workshop-preview-reuse branch from 3e22fc6 to b0a59f2 Compare November 24, 2026 16:27
@LangerSword

Copy link
Copy Markdown
Author

Addressed the full-source identity finding (Sipper1236, mika-finding:6206e0b5, Greptile P2).

Finding: previewSourceIdentity hashed only the first 64 KiB. A same-size update that changed later video bytes kept the old identity, so the stale preview was reused.

Fix: previewSourceIdentity now streams the entire source through SHA-256 and still keys the record by byte size plus digest prefix. Callers, the atomic .meta write, and the temp sweep are unchanged.

Tests: added TestPreviewSourceIdentityHashesBeyondFirst64KiB (same size and same opening bytes, one byte changed after 64 KiB, identities differ) and TestWorkshopPreviewRegeneratesOnLateSameSizeChange. The six preview-identity tests pass; go vet is clean. The three E2E socket-startup failures in the full package also fail on pristine HEAD in this environment, so they are unrelated to this change.

Head is b0a59f2, PR head matches it. @ryoku-mika please re-review.

Comment thread ryoku/shell/ryogami/daemon/scan.go Resolved
@LangerSword

Copy link
Copy Markdown
Author

@ryoku-mika review

Fresh pass requested on head b0a59f283cb6. The full-source SHA-256 identity, atomic preview records, and attribution cleanup are in this head. The earlier CHANGES_REQUESTED reviews point to older commits.

Move the startup temp sweep before any generator can create cache files,
match only real temp suffixes so finished thumbnails survive, and memoize
source identity for unchanged files while keeping full-content hashing.

Fixes current-head review findings on Ryoku-dev#929.
@LangerSword

Copy link
Copy Markdown
Author

Pushed 425a120 on top of b0a59f2 for the current-head findings.

  • The startup temp sweep now runs before watchers, restore, or rescan can create cache files.
  • Temp cleanup now matches only the real .tmp.<pid>-<unixnano><ext> suffix, so finished artifacts such as photo.tmp.png.webp survive.
  • Unchanged sources reuse a memoized full-content identity; any stat change forces a fresh hash, so same-size late edits are still detected.
  • The existing full-source SHA-256 identity is unchanged.

Targeted tests pass with -race; go vet ./ and gofmt -l are clean. New tests fail on the previous head for the cleanup-order and finished-thumbnail findings.

@ryoku-mika review

Initial draft by me; final wording written with Hermes Agent.

Comment on lines +628 to +629
if ok && memo.identity != "" && memo.size == it.filesize && memo.mtime == it.mtime {
return memo.identity

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Changed videos keep old previews. The new cache trusts size and mtime, but weVideoSource rounds the timestamp to whole seconds. If different source bytes arrive with the same size and timestamp second, this returns the old identity without reading the file. ensureVideoPreview then keeps the old clip on every later scan, even after the write finishes.

Use a stronger check for whether the file changed, including finer timestamps and file replacement, or clear its saved identity when the source changes.

Prompt To Fix With AI
This is a comment left during a code review.
Path: ryoku/shell/ryogami/daemon/scan.go
Line: 628-629

Comment:
**Changed videos keep old previews.** The new cache trusts size and `mtime`, but `weVideoSource` rounds the timestamp to whole seconds. If different source bytes arrive with the same size and timestamp second, this returns the old identity without reading the file. `ensureVideoPreview` then keeps the old clip on every later scan, even after the write finishes.

Use a stronger check for whether the file changed, including finer timestamps and file replacement, or clear its saved identity when the source changes.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Claude Code Fix in Codex

@neur0map
neur0map merged commit 64c87bc into Ryoku-dev:unstable-dev Nov 30, 2026
3 checks passed
@neur0map

Copy link
Copy Markdown
Member

Thanks for the work here, merged with a cheaper login check on my side so it doesn't hash every video, it goes out with the next update

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

Labels

area:ryoku Ryoku project area type:bug A reported problem

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants