Repository navigation
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (3)
WalkthroughEvent dispatch now uses buffered queues and persistent workers, with concurrency-safe test updates. On Linux GTK3, JavaScript execution now waits for WebKit completion through a synchronous C helper. ChangesQueue-based Event Dispatch
Linux Synchronous JavaScript Execution
Estimated code review effort: 3 (Moderate) | ~25 minutes Sequence Diagram(s)sequenceDiagram
participant Caller
participant EventProcessor
participant ListenerWorker
participant WindowWorker
Caller->>EventProcessor: Emit(event)
EventProcessor->>ListenerWorker: enqueue event
EventProcessor->>WindowWorker: enqueue event
ListenerWorker->>ListenerWorker: dispatchEventToListeners(event)
WindowWorker->>WindowWorker: dispatchEventToWindows(event)
sequenceDiagram
participant linuxWebviewWindow
participant execute_js_sync
participant WebKit
participant GMainContext
linuxWebviewWindow->>execute_js_sync: execute JavaScript
execute_js_sync->>WebKit: evaluate JavaScript
WebKit->>execute_js_sync: completion callback
execute_js_sync->>GMainContext: iterate until completion
execute_js_sync-->>linuxWebviewWindow: return after completion
Possibly related issues
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 golangci-lint (2.12.2)level=error msg="[linters_context] typechecking error: pattern ./...: directory prefix . does not contain modules listed in go.work or their selected dependencies" 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
v3/pkg/application/events.go (1)
122-155: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winAdd a shutdown path for EventProcessor
NewWailsEventProcessorstarts two goroutines that block forever on unclosed queues. That is fine for the app singleton, but short-lived processors in tests and benchmarks—likeBenchmarkOnMultipleEventinsideb.Loop()—keep accumulating workers and skew benchmark results. AddClose/Stopand stop the dispatch loops with a done channel or by closing the queues.🤖 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 `@v3/pkg/application/events.go` around lines 122 - 155, Add a shutdown path to EventProcessor so the goroutines started by NewWailsEventProcessor do not leak for short-lived uses. Introduce a Close/Stop method on EventProcessor, track a done signal or close listenerQueue/windowQueue safely, and make runListenerDispatch and runWindowDispatch exit when shutdown is requested. Update NewWailsEventProcessor and the dispatch loops to use the new lifecycle control so tests and benchmarks like BenchmarkOnMultipleEvent can stop workers cleanly.
🤖 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 `@v3/pkg/application/events.go`:
- Around line 200-201: `EventManager.Emit` is currently blocked by synchronous
sends to both `listenerQueue` and `windowQueue`, so a slow window delivery path
can stall callers. Update the `Emit` flow in `EventManager` to avoid blocking on
`windowQueue` backpressure by using a non-blocking enqueue strategy with
overflow handling, such as logging and dropping or otherwise degrading safely,
while keeping `listenerQueue` behavior consistent with the intended delivery
model. Refer to `Emit`, `listenerQueue`, `windowQueue`, and the
`EventIPCTransport.DispatchWailsEvent`/`WebviewWindow.DispatchWailsEvent` path
when making the change.
In `@v3/pkg/application/linux_cgo_gtk3.go`:
- Around line 124-139: `execute_js_sync` can still allow out-of-order `execJS`
completion because it blocks with a nested main loop while another
`webkit_web_view_evaluate_javascript` is already in flight. Update the
`execute_js_sync`/`on_evaluate_javascript_finish` flow so JS executions are
serialized through a single queue or by chaining the next request from the
previous callback. Make sure only one `WebKitWebView` evaluation is active at a
time, and keep the existing synchronous behavior at the `execute_js_sync` call
site.
---
Nitpick comments:
In `@v3/pkg/application/events.go`:
- Around line 122-155: Add a shutdown path to EventProcessor so the goroutines
started by NewWailsEventProcessor do not leak for short-lived uses. Introduce a
Close/Stop method on EventProcessor, track a done signal or close
listenerQueue/windowQueue safely, and make runListenerDispatch and
runWindowDispatch exit when shutdown is requested. Update NewWailsEventProcessor
and the dispatch loops to use the new lifecycle control so tests and benchmarks
like BenchmarkOnMultipleEvent can stop workers cleanly.
🪄 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: CHILL
Plan: Pro
Run ID: 7346d191-d362-4292-a4a9-bec0db30deff
📒 Files selected for processing (3)
v3/pkg/application/events.gov3/pkg/application/events_test.gov3/pkg/application/linux_cgo_gtk3.go
5f00091 to
6825ea2
Compare
|
That’s awesome! Right now I’m outputting SSE data to the frontend and relying on sleep delays to maintain the order. With this solution, everything will work perfectly without any issues. |
Huge thanks to DevLumuz for putting forward this PR! |
Two related fixes for Wails events reaching the page out of order when
Emit() is called rapidly in succession (e.g. streaming many small events
back-to-back):
1. EventProcessor.Emit spawned two bare goroutines per call for dispatch
(listeners, windows), with no ordering guarantee between goroutines from
successive calls. Replaced with one buffered, ordered worker per target —
Emit() stays non-blocking, dispatch is now strict FIFO. Also bounds
in-flight dispatch (dispatchQueueSize), unlike the old unbounded fan-out.
2. linux/gtk3 execJS passed callback=NULL to
webkit_web_view_evaluate_javascript ("fire and forget"): WebKit confirms
the request was accepted, not that it finished executing, so nothing
guaranteed successive evaluate_javascript calls ran in the order they
were dispatched. execJS now waits for the real completion callback, via
the same nested-main-loop technique already used by
clipboard_get_text_sync (linux_cgo.c).
Verified with an isolated repro (500 Emit() calls in a tight loop, no AI/LLM
or app-specific code involved): before, 478/500 (95.6%) arrived out of
order in the page. After, 0/500. Also faster to issue: 2.16ms -> 244µs total
for the 500 calls, since Emit() no longer spawns two goroutines per call.
go test -race ./pkg/application/... passes clean (also fixed two
pre-existing latent races in events_test.go's mock that -race now catches
reliably against the new, more deterministic dispatch timing).
ca078b1 to
eca134f
Compare
|
Thanks — glad this lines up with a real use case. On your questions: the reviews on this PR so far are automated (CodeRabbit). What's still outstanding is an approval from a Wails maintainer, so it's human review that's pending, not a bot. As for timing, I can't give you an estimate — I'm a contributor here, not a maintainer, so the merge decision isn't mine. What I can say is the PR is ready from my side: CI is green, no changes have been requested, and I've just rebased it onto current |
leaanthony
left a comment
There was a problem hiding this comment.
Traced this through the dispatch paths before commenting, because the ordering claim holds for one of the two and not the other.
The window/JS path is genuinely fixed. dispatchEventToWindows is EventManager.dispatch, which iterates listeners and calls DispatchWailsEvent synchronously. So a single worker draining windowQueue does give strict FIFO all the way to ExecJS. That matches the failure described in the code comment and is a real fix for #4914.
The Go-listener path is not ordered, though, and the PR title implies it is. dispatchEventToListeners still spawns a goroutine per listener per event (events.go:256). The worker hands it events in order, but two goroutines started in order have no execution-order guarantee between them, so a Go listener receiving A then B can still run B first. Someone reading "guarantee event dispatch order" would reasonably assume otherwise. Either that go func() needs to go too, or the guarantee should be documented as applying to the frontend only.
Emit can now block, where it previously could not. With a full queue, e.listenerQueue <- thisEvent blocks the caller. Listener callbacks run on their own goroutines so the obvious re-entrancy deadlock does not apply, but DispatchWailsEvent is synchronous: one window stalled in IPC fills windowQueue and every subsequent Emit blocks, including from the main thread. 4096 makes that unlikely rather than impossible. A non-blocking send with an explicit drop-and-log, or a documented note that Emit may block under sustained backpressure, would close it.
Not blocking the PR: bounding in-flight dispatch and fixing frontend ordering are both improvements over goroutine-per-Emit. Flagging so the guarantee that gets documented matches the one that is implemented.
|
I sent my own version of this fix using a mailbox, aka an unbounded channel; it makes Emit non-blocking while still preserving FIFO. I marked you as a co-author. |
|
Hi @DevLumuz — thank you for this, and sorry it sat so long without a real answer. You were ahead of everyone here. You opened this on 6 July, three weeks before #5850 was filed, and your diagnosis was right: There's a credit problem we need to fix, though. @savely-krasovsky intended to co-author you and said so in this thread, but the trailer didn't survive the squash merge, and the changelog entry names only the PR author. So you aren't credited on master for a fix that started with your work. That's our process failing you, and we'll get your name on it. We also finally checked the GTK3 change, which nobody had done until now. Stock master built with The part that's still live is the Go listeners. #5851 only covered the frontend path, so So we'd like to close this one, since it conflicts with master and two of its three parts are now either shipped or measured away. But the listener question is yours and still open. If you want to pick it up against current master we'll review it promptly this time, and if you'd rather not after a month of waiting, that's completely fair — we'll open an issue crediting you so it doesn't get lost again. Thanks also for staying with @heixiaoma here while it was open. |
App.dispatchOnMainThread runs work inline when the caller is already on the UI thread, so an event emitted from the UI thread executed its eval immediately while an event emitted moments earlier from a goroutine was still queued — and the later event arrived first. DispatchWailsEvent now appends to a per-window queue and a single drain on the UI thread empties it in order. Appending under a mutex makes the queue the one ordering authority, whichever thread each event came from. A lock around the dispatch instead would deadlock: it would have to be held across the ExecJS main-thread hop, so a UI-thread emit would block on a lock whose holder is waiting for the UI thread. The queue avoids that because the bound applies to goroutine emitters only — the UI thread is the drainer and is never made to wait. Capacity 64, chosen by measurement. Ordering held and 5000 ev/s was sustained at every size tried, so only tail latency moved, rising with depth (179us p99 at 16, 427us at 1024). Emit also stopped blocking on a main-thread round trip, so emit p50 at 5000 ev/s fell from ~45us to 1-2us. Nothing is dropped when the queue is full: goroutine emitters block until a slot frees, the UI thread appends past the bound and drains inline, and a window destroyed while an emitter waits releases it. Note the bound limits this queue rather than total in-flight memory, since the mailbox added in #5851 is unbounded and sits upstream. Verified on macOS, Ubuntu 26.04 (both the default GTK4 backend and legacy -tags gtk3) and Windows 11 (WebView2): 0 inversions across mixed-source, interleaved-size and 5000 ev/s runs. Six unit tests need no GUI so they run in CI; the headline one drives DispatchWailsEvent and fails without the queue. Also corrects the harness scenario that first reported this, which took its sequence number outside the InvokeAsync callback and so measured its own race. The ~4.4% figure quoted in #5930 is retracted. Prior art: @DevLumuz raised event ordering first in #5757 and is credited on #5851 for the layer that fix addressed. The GTK3 concern from that PR was measured here at 186,047 events with 0 reorders and is not reproduced.
@savely-krasovsky intended to co-author @DevLumuz on #5851 and said so on #5757, but the Co-authored-by trailer did not survive the squash merge and the changelog generator names only the PR author. @DevLumuz opened #5757 on 6 July, three weeks before #5850 was filed, and identified the cause, so the entry should carry both names. Co-authored-by: DevLumuz <[email protected]>
Emit dispatched Go listeners from a goroutine per call, and the dispatch started a goroutine per listener, so a listener registered with Event.On could see two events out of order and run concurrently with itself. wailsapp#5851 ordered the frontend path; this does the same for Go listeners, as discussed in wailsapp#5757. Each listener now owns a mailbox. Emit queues the event to every listener under notifyLock, so the queue order is the emit order, and the mailbox runs the callback one event at a time. Emit still never waits for a callback, and different listeners stay independent: a slow one does not delay the others. Once/OnMultiple counters, cancellation and per-callback panic recovery are unchanged. Events still queued for a listener that is removed (its remover, Off or OffAll) are dropped.
Emit dispatched Go listeners from a goroutine per call, and the dispatch started a goroutine per listener, so a listener registered with Event.On could see two events out of order and run concurrently with itself. wailsapp#5851 ordered the frontend path; this does the same for Go listeners, as discussed in wailsapp#5757. Each listener now owns a mailbox. Emit queues the event to every listener under notifyLock, so the queue order is the emit order, and the mailbox runs the callback one event at a time. Emit still never waits for a callback, and different listeners stay independent: a slow one does not delay the others. Once/OnMultiple counters, cancellation and per-callback panic recovery are unchanged. Events still queued for a listener that is removed (its remover, Off or OffAll) are dropped.
* fix(v3/events): deliver to each Go listener in emit order Emit dispatched Go listeners from a goroutine per call, and the dispatch started a goroutine per listener, so a listener registered with Event.On could see two events out of order and run concurrently with itself. #5851 ordered the frontend path; this does the same for Go listeners, as discussed in #5757. Each listener now owns a mailbox. Emit queues the event to every listener under notifyLock, so the queue order is the emit order, and the mailbox runs the callback one event at a time. Emit still never waits for a callback, and different listeners stay independent: a slow one does not delay the others. Once/OnMultiple counters, cancellation and per-callback panic recovery are unchanged. Events still queued for a listener that is removed (its remover, Off or OffAll) are dropped. * fix(v3/events): free queued events when a listener is removed Removing a listener only marked it, so its queued events stayed in the mailbox until the running callback returned; a callback that never returns kept that backlog forever. Mailbox gains Discard, which drops the waiting messages without waiting for the one in progress, and every removal path calls it. Also state in the docs that the ordering guarantee covers sequential Emit calls; concurrent callers have no defined order. --------- Co-authored-by: taliesin-ai <[email protected]>
Problem
Events emitted rapidly in succession (e.g. a Go backend streaming many small
events back-to-back) can reach the frontend out of order, or with visible
interleaving. Two independent causes:
EventProcessor.Emit(v3/pkg/application/events.go) spawns two baregoroutines per call for dispatch (one for Go listeners, one for windows).
Go gives no ordering guarantee between separately spawned goroutines, so
two events emitted back-to-back can have their window-dispatch (and
therefore their
ExecJScall) run in either order.linux/gtk3
execJS(v3/pkg/application/linux_cgo_gtk3.go) callswebkit_web_view_evaluate_javascriptwithcallback=NULL("fire andforget"). WebKit confirms the request was accepted, not that it
finished executing — WebKit evaluates scripts asynchronously via its
WebProcess, and without a completion callback nothing guarantees that
rapid, back-to-back
evaluate_javascriptcalls execute in the same orderthey were dispatched.
Fix
Replaced the two bare goroutines in
Emit()with one buffered, orderedworker per dispatch target (listeners, windows).
Emit()staysnon-blocking under normal load (buffer of 4096, well above realistic
bursts) — dispatch is now strict FIFO per target, and also bounded,
unlike the previous unbounded goroutine-per-
Emit()fan-out.execJSnow waits for the real WebKit completion callback beforereturning, using the same nested main-loop-iteration technique already
used by
clipboard_get_text_sync(linux_cgo.c) to make an asyncGLib/GTK call appear synchronous from the calling C code — blocking on a
condition variable instead would freeze the very loop that has to keep
running for the completion callback to ever be delivered.
Also fixed two pre-existing latent races in
events_test.go's mock notifierand counter that
-racenow catches reliably against the new, moredeterministic dispatch timing (they were always technically possible, just
rarely triggered by the old bare-goroutine timing).
Verification
Isolated repro: 500
Emit()calls in a tight loop, no app-specific codeinvolved, checking arrival order in the page.
Emit()callsEmit()no longer spawns two goroutines per call)go test -race ./pkg/application/...passes clean.Summary by CodeRabbit