Skip to content

feat: tracing of stalled render threads - #4622

Open
Julusian wants to merge 16 commits into
mainfrom
feat/render-stall-recovery
Open

Julusian wants to merge 16 commits into
mainfrom
feat/render-stall-recovery

Conversation

@Julusian

@Julusian Julusian commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

A render task that never returned (eg some text locking up the renderer) held its thread forever; once every
thread was stuck, nothing else was drawn, on surfaces or in the ui.

This adds some logging of the failures, and attempts to recover as gracefully as we can. This includes quarantining the failed draws, and when necessary restarting companion to kill the stalled threads.
The failures are now reported to the ui, so this should be very noticable when this happens, and will hoepfully result in better bug reports instead of confusion over all buttons not drawing.

As we run the drawing in worker-threads, we can't kill one of them directly without restarting all of companion. And we don't want to just keep spawning more, as the threads could be stuck with high cpu and will leak memory

Summary by CodeRabbit

  • New Features
    • Added a render-stall banner showing affected renders, their location or description, and available text.
    • Quarantined renders display a placeholder instead of repeatedly blocking rendering, and can be retried from the banner.
    • The banner reports scheduled or manual restart status, with options to restart immediately or postpone a scheduled restart.
    • Rendering recovers from stalled tasks by replacing worker pools. Lost render threads can trigger a scheduled restart, with safeguards against repeated restart loops.
  • Bug Fixes
    • Preview updates can continue after a rendering or image-encoding failure.

@coderabbitai

coderabbitai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Walkthrough

The render pipeline now times worker tasks, replaces pools after stalls, and quarantines affected draws. A monitor tracks lost threads and restart history. The web UI displays quarantined renders and provides retry and restart controls. Preview encoding failures are handled without stopping later preview updates.

Changes: Render stall recovery

Layer / File(s) Summary
Render task execution and stall detection
companion/lib/Graphics/RenderPool.ts, companion/lib/Graphics/RenderTaskTimeout.ts, companion/lib/Graphics/Controller.ts, companion/test/Graphics/RenderPool.test.ts, companion/test/Graphics/RenderTaskTimeout.test.ts, companion/test/Graphics/helpers/StallingThread.mjs
Render tasks use per-method timeouts. RenderPool replaces pools after stalls, resubmits queued tasks rejected by replaced pools, and tracks terminations and lost threads. GraphicsController uses the pool and exposes its metrics. Tests cover task execution, timeouts, pool replacement, and lost-thread accounting.
Quarantine stalled draws
shared-lib/lib/Model/RenderStall.ts, companion/lib/Data/Cache.ts, companion/lib/Graphics/RenderQuarantine.ts, companion/lib/Graphics/Controller.ts, companion/test/Graphics/RenderQuarantine.test.ts
The quarantine stores draw keys and stall details, persists entries for the current build, and applies a placeholder to quarantined styles. GraphicsController records stalled render details and regenerates renders when quarantine changes. Tests cover key generation, persistence, and placeholder application.
Lost-thread restart monitoring
companion/lib/Graphics/RenderStallMonitor.ts, companion/lib/Registry.ts, companion/lib/UI/TRPC.ts, companion/lib/main.ts, companion/test/Graphics/RenderStallMonitor.test.ts
The monitor publishes render status and schedules restarts based on lost-thread counts and restart history. Registry exposes its router and passes the stalled-thread state to process-exit handling. The process callback uses SIGKILL when render threads may be stuck. Tests cover scheduling, cancellation, postponement, and manual restart status.
Render stall banner and controls
webui/src/App.tsx, webui/src/Layout/RenderStallBanner.tsx, webui/src/Layout/RenderStallBannerView.tsx, webui/src/Layout/RenderStallBanner.css, webui/src/Layout/__tests__/RenderStallBannerView.test.tsx
The connected, unlocked app displays render-stall status. The banner lists quarantined renders and provides retry and restart actions, including postponement for scheduled restarts. Tests cover empty, quarantined, scheduled, and manual states.
Stalled-render retries and preview handling
companion/lib/Graphics/ImageResult.ts, companion/lib/Preview/Graphics.ts, companion/test/Graphics/ImageResult.test.ts, companion/test/Preview/Graphics.test.ts
Image-cache entries are removed after stalled-render failures so later calls can retry. Preview encoding failures are logged and skipped. Tests cover cache retries and subsequent preview updates.
Merge Risk: Low · up to 92d75

Recovery from stalled render threads now works as intended in the common cases. A scheduled restart that fires before startup finishes is retried rather than lost. One remaining edge case: if the restart history cannot be written back after a rejected restart, automatic restart may be disabled sooner than intended. A manual restart still works, so this is minor and can be tidied up as a small follow-up.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title "feat: tracing of stalled render threads" matches the main change. The PR adds a RenderPool that detects and replaces stalled render workers, tracks lost threads, quarantines stalled draws, …
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.
Full details: Title check

Explanation

The title "feat: tracing of stalled render threads" matches the main change. The PR adds a RenderPool that detects and replaces stalled render workers, tracks lost threads, quarantines stalled draws, and adds stall logging and a restart flow. The title names the core theme, which is stalled render threads. It does not cover the quarantine, UI banner, or restart features, but the PR objectives describe those as parts of the same work, so the title is a fair summary of the primary change. The title is concise, uses a conventional prefix, and a teammate scanning history would understand the main purpose.

  • 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

A worker stalls; a fresh pool starts
A marked draw takes a safer place
Lost threads count as minutes pass
Restart choices reach the screen
A later preview finds its way
The render path resumes its pace

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

Nitpick comments: 1

companion/test/Graphics/RenderQuarantine.test.ts: 1

13-13: Trivial · Maintainability & Code Quality · Quick win

Please make both fixture parameters required.

pushed = false and initial = [] make new parameters optional. Remove the defaults and pass false or [] explicitly at each affected call site. This also makes each test's initial state explicit.

As per coding guidelines, “New function parameters are required, not optional,” and arguments must be threaded through all call sites.

Also applies to: 36-36

Source: Coding guidelines

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ecdf89e8-8788-463f-9155-818a5b996bcb
Commits

Reviewing files that changed from the base of the PR and between 38099f7 and fe5bcd6.

Files selected for processing: 20

  • companion/lib/Data/Cache.ts
  • companion/lib/Graphics/Controller.ts
  • companion/lib/Graphics/RenderPool.ts
  • companion/lib/Graphics/RenderQuarantine.ts
  • companion/lib/Graphics/RenderStallMonitor.ts
  • companion/lib/Graphics/RenderTaskTimeout.ts
  • companion/lib/Registry.ts
  • companion/lib/UI/TRPC.ts
  • companion/lib/main.ts
  • companion/test/Graphics/RenderPool.test.ts
  • companion/test/Graphics/RenderQuarantine.test.ts
  • companion/test/Graphics/RenderStallMonitor.test.ts
  • companion/test/Graphics/RenderTaskTimeout.test.ts
  • companion/test/Graphics/helpers/StallingThread.mjs
  • shared-lib/lib/Model/RenderStall.ts
  • webui/src/App.tsx
  • webui/src/Layout/RenderStallBanner.css
  • webui/src/Layout/RenderStallBanner.tsx
  • webui/src/Layout/RenderStallBannerView.tsx
  • webui/src/Layout/__tests__/RenderStallBannerView.test.tsx

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

Comment thread companion/lib/Graphics/Controller.ts Resolved
Comment thread companion/lib/Graphics/RenderPool.ts Resolved
Comment thread companion/lib/Registry.ts
// Once a whole pool's worth of threads are stuck, the stuck ones are probably slowing everything else
this.graphics.renderPoolSize,
new CachedRenderStallRestartHistory(this.#data.cache.defaultTableView),
() => this.exit(true, true)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Minor · Stability & Availability · Quick win

A stall-triggered restart can be dropped when startup has not finished.

ready() starts the render regeneration before it awaits initInstances(). If the render pool reports enough stuck threads and startup is still pending when the 60-second restart countdown fires, exit() returns early because #isReady is still false. The monitor's timer clears itself but leaves its scheduled restart in place. Later stall reports do not reschedule it, so the restart never runs automatically. Only a manual restart from the UI, which is available after startup, recovers the state.

Consider either deferring the restart until #isReady is set, or clearing the monitor's restart state when the request is dropped so a later stall report can schedule it again. Either approach keeps the restart from being lost.

…drawing

A render task that never returned (eg some text locking up the renderer) held its thread forever; once every
thread was stuck, nothing else was drawn, on surfaces or in the ui. Each task now has a timeout, after which its
thread is terminated and replaced, and the button and its draw style are logged so the cause can be found.
Once per run for each button and text, as a stalled draw stalls again at each size and redraw.
process.exit waits for every thread to stop, which a render thread stuck in native code never does, so quitting
(or the launcher going away) left the process running forever. After a stall it is killed instead.
…stalling again

A stalled draw stalled again at each size it was shown at and each time it was redrawn, until every render thread
was stuck. It is now quarantined for the rest of the run, and drawn as a placeholder.
…date

A draw which stalls would stall again after a restart, so the quarantine is kept in the cache, for the build it
stalled on.
…ds which are stuck for good

A stalled thread which can't be terminated (eg stuck in native code) took a place in the pool for good. Its pool is
now replaced, so drawing carries on with new threads, and if it doesn't stop in time it is counted as lost.
…stalls to the ui

Once a pool's worth of render threads are stuck for good, Companion restarts itself a minute later, which can be
postponed. The stalled draws stay quarantined across the restart, so if it has to restart twice within 10 minutes
anyway, the restart is left to the user. The stalled draws and any restart are reported to the ui.
…restart to recover

A banner lists the draws which stalled and are shown as a placeholder, with their text and a link to their page, and
can try them again. When too many render threads are stuck it counts down to the restart, which can be postponed or
done now.
… lost, and stop the one workerpool respawns in a replaced pool
@Julusian
Julusian force-pushed the feat/render-stall-recovery branch from 24e4f16 to 8160c62 Compare November 22, 2026 19:19

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 4c443148-de85-4f15-82d4-5b3e1b545a9b
Commits

Reviewing files that changed from the base of the PR and between fe5bcd6 and 8160c62.

Files selected for processing: 7

  • companion/lib/Graphics/Controller.ts
  • companion/lib/Graphics/RenderPool.ts
  • companion/lib/Graphics/RenderStallMonitor.ts
  • companion/lib/Registry.ts
  • companion/test/Graphics/RenderPool.test.ts
  • companion/test/Graphics/RenderQuarantine.test.ts
  • companion/test/Graphics/RenderStallMonitor.test.ts

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

Comment on lines 1062 to 1083
rotation,
format,
CRASHED_WORKER_RETRY_COUNT
),
).catch((e: unknown) => {
if (e instanceof RenderTaskStalledError) {
// Dump what was being drawn, so that whatever locks up the renderer can be found and reproduced
this.#logger.error(
`Drawing ${subject.description} at ${width}x${height} (rotation ${rotation ?? 0}) stalled, so its render thread is being replaced and it will be drawn as a placeholder. Text: ${JSON.stringify(processedStyle?.text?.text ?? '')}. Draw style: ${stringifyDrawStyleForLog(drawStyle)}`
)
// It holds the failed draw, so mustn't be reused if the draw is allowed again
if (cacheKey && this.#renderLRUCache.peek(cacheKey) === render) this.#renderLRUCache.delete(cacheKey)
this.#quarantineStalledDraw(e, subject, drawStyle)
}
throw e
}),
drawElements,
referencedLocations ?? new Set()
)
this.#renderSources.set(render, { drawStyle, animationFrames })
this.#renderSources.set(render, { drawStyle, animationFrames, subject })
return render
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Minor · Stability & Availability · Quick win

Evict failed draw promises from the ImageResult caches so a retry submits a new render task.

The stall handler's renderLRUCache.delete(cacheKey) never matches an undecorated render, because its key is undecorated:K and no LRU entry uses that key. The failed promise stays in #undecoratedRenders and in the source ImageResult caches. After the quarantine lifts, the source render is reused from the LRU, so a Link-served retry at the same size gets the cached rejection and submits no new worker task. Clearing the stall handler alone does not reach this state, because the undecorated closure has no reference to the source render. Remove rejected entries from the caches where they are stored.

Suggested fix

 		this.#drawNativeCache.set(cacheKey, newBuffer)
+		newBuffer.catch(() => {
+			if (this.#drawNativeCache.get(cacheKey) === newBuffer) this.#drawNativeCache.delete(cacheKey)
+		})
 		return newBuffer
 		this.#drawNativeEncodedCache.set(cacheKey, newDataUrl)
+		newDataUrl.catch(() => {
+			if (this.#drawNativeEncodedCache.get(cacheKey) === newDataUrl) this.#drawNativeEncodedCache.delete(cacheKey)
+		})
 		return newDataUrl

This change applies to every failed drawNative and drawNativeEncoded call, not only stalls. If a sticky failure is intended for other errors, limit the eviction to stalled draws instead.

Comment thread companion/lib/Graphics/Controller.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: e9e5c676-7ef0-4431-b61c-f6694c02a156
Commits

Reviewing files that changed from the base of the PR and between 8160c62 and 92d7502.

Files selected for processing: 8

  • companion/lib/Graphics/Controller.ts
  • companion/lib/Graphics/ImageResult.ts
  • companion/lib/Graphics/RenderStallMonitor.ts
  • companion/lib/Preview/Graphics.ts
  • companion/test/Graphics/ImageResult.test.ts
  • companion/test/Graphics/RenderPool.test.ts
  • companion/test/Graphics/RenderStallMonitor.test.ts
  • companion/test/Preview/Graphics.test.ts
Files with no reviewable changes: 1

  • companion/lib/Graphics/Controller.ts

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

}

if (!this.#requestRestart()) {
this.#restartHistory.save(recentRestarts)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Minor · Stability & Availability · Quick win

Stop automatic retries when a rejected restart cannot be removed from history.

When requestRestart() returns false, the attempted restart is already saved to the restart history. If the rollback save(recentRestarts) also fails, the code ignores that result. The rejected timestamp stays stored, and each retry adds another entry. Two entries in the 10-minute window make a later stall fall back to a manual restart. Switching to manual restart when the rollback fails stops further entries from building up. It also matches the fallback already used when the initial save fails.

Suggested fix

--- "a/companion/lib/Graphics/RenderStallMonitor.ts"
+++ "b/companion/lib/Graphics/RenderStallMonitor.ts"
@@ -159,9 +159,15 @@
 					return
 				}
 
 				if (!this.#requestRestart()) {
-					this.#restartHistory.save(recentRestarts)
+					if (!this.#restartHistory.save(recentRestarts)) {
+						this.#logger.error(`Couldn't remove the failed restart from the history, so it is left to the user`)
+						this.#setRestart({ type: 'manual' })
+						this.#emitStatus()
+						return
+					}
+
 					this.#logger.warn(`Couldn't restart yet, so trying again in ${RESTART_RETRY_MS / 1000}s`)
 					this.#setRestart({ type: 'scheduled', at: Date.now() + RESTART_RETRY_MS })
 					this.#emitStatus()
 				}

This branch has not been deployed

No deployments
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