darktable icon indicating copy to clipboard operation
darktable copied to clipboard

Sporadic segfault at startup: Lua gtk_wrap builds script_manager widgets on a worker thread while main thread realizes the main window

Open mamo2021 opened this issue 2 months ago • 23 comments

Is there an existing issue for this?

  • [x] I checked and did not find my issue in the already reported ones

Describe the bug

darktable 5.6.1 occasionally crashes with SIGSEGV during startup. Restarting usually works fine; the crash is not deterministic.

The core dump shows a race between two threads touching GTK at the same time:

Thread 1 (main thread) is still inside dt_init() (darktable.c:2080) and calls gtk_widget_show() on the main window. During gtk_window_realize() → size negotiation through dtgtk_side_panel_get_preferred_width() (sidepanel.c:36), GTK crashes in gtk_container_adjust_size_request() on a widget inside a GtkFrame / GtkRevealer in the side panel. Thread 7 (Lua async thread, run_async_thread_main) is at the same moment executing GTK code: gtk_wrap() (lua/call.c:666) → g_main_context_invoke_full() → dt_lua_gtk_wrap_callback() runs the callback directly on the Lua thread → image_member() (lua/widget/button.c:163) → gtk_image_new_from_file("/usr/share/darktable/lua-scripts/data/icons/path20.png"). This icon belongs to tools/script_manager.lua.

My interpretation: during startup the GTK main loop is not running yet, so nobody owns the default main context. g_main_context_invoke_full() can therefore acquire the context from the Lua thread and executes the GTK callback there instead of deferring it to the main thread. GTK widgets are then created/modified concurrently with the main thread's size allocation, which leads to the crash when the timing is unlucky.

OpenCL threads (libnvidia-opencl) are idle in the dump, and the crash is not related to image processing.

Steps to reproduce

  1. Enable the script manager in ~/.config/darktable/luarc (require "tools/script_manager").
  2. Start darktable repeatedly.
  3. Occasionally darktable crashes with SIGSEGV before the main window appears.

Expected behavior

darktable starts reliably. GTK calls from Lua (gtk_wrap) should always run on the GUI thread, also during startup before the main loop is running.

Logfile | Screenshot | Screencast

darktable-backtrace-summary.txt (relevant threads 1 and 7) and coredump.txt (full thread apply all bt from coredumpctl gdb)

Commit

No response

Where did you obtain darktable from?

distro packaging

darktable version

5.6.1 (openSUSE Tumbleweed package, Lua API 9.7.0)

What OS are you using?

Linux

What is the version of your OS?

openSUSE Tumbleweed (September 2026), kernel 7.2.6, glibc 2.44, Lua 5.4.8

Describe your system

  • GPU: NVIDIA GeForce RTX 5080, driver 595.99.02 (nvidia-open), OpenCL 3.0 / CUDA 13.2
  • RAM: 96 GB
  • Display server: Wayland session, darktable running as native Wayland client (GDK_BACKEND not set)

Are you using OpenCL GPU in darktable?

Yes

If yes, what is the GPU card and driver?

NVIDIA GeForce RTX 5080, driver 595.99.02 (not involved in the crash, OpenCL threads idle)

Please provide additional context if applicable. You can attach files too, but might need to rename to .txt or .zip

Lua scripts are loaded via tools/script_manager.lua from the system lua-scripts installation (/usr/share/darktable/lua-scripts).

mamo2021 avatar Sep 21 '26 16:09 mamo2021

The button icon handling code just changed so this may be OBE (overtaken by events).

See if you can reproduce on current master. You can grab the weekly build from pixls.us darktable windows insider program.

wpferguson avatar Sep 21 '26 18:09 wpferguson

Not just a startup window — the same root cause hit mid-session on 5.6.1.

darktable 5.6.1 (Arch extra/darktable 2:5.6.1-1), Wayland/Hyprland, gtk3 3.24.52-1, glib2 2.88.3-1, lua54 5.4.9-1, OpenCL disabled. No third-party Lua scripts: no ~/.config/darktable/lua, every lua/script_manager/* preference FALSE — only the bundled tools/script_manager from the default /usr/share/darktable/luarc.

Single occurrence, ~25 s after launch, during the first-time import of a DNG (its XMP sidecar and library.db/data.db were written within the same second). The GTK main loop was fully running, and the main thread was inside a style-updated handler — not starting up.

The failure was not a segfault but glibc heap corruption (SIGABRT). Two threads were concurrently in GTK's CSS-node code.

Worker thread, comm pool-2, a GLib thread pool worker (g_thread_pool_thread_proxy) — the thread the SIGABRT was attributed to. Same path you describe:

lua pool task -> dt_lua_widget_trigger_callback -> Lua
  -> g_main_context_invoke_full -> dt_lua_gtk_wrap_callback -> Lua
  -> gtk_button_set_image -> gtk_button_construct_child
  -> gtk_style_context_get_style -> gtk_css_widget_node_create_widget_path
  -> gtk_container_get_path_for_child -> gtk_widget_path_append_for_widget
  -> gtk_css_node_declaration_add_class
  -> gtk_css_node_declaration_make_writable_resize -> realloc
  -> __libc_message -> abort        <-- corrupt chunk detected

Main thread, concurrently:

gtk_label_style_updated -> gtk_widget_real_style_updated -> gtk_widget_get_style_context
  -> g_object_unref -> gtk_css_node_finalize -> free -> __libc_message -> abort

The callback really did run inline on the pool worker, matching your reading of g_main_context_invoke_full (I confirmed that fast path in glib's gmain.c). But note that "the main loop isn't running yet" doesn't appear to be the only way to hit it: here the main loop was running and the main thread was actively dispatching GTK signals, and the acquire fast path still fired. So the unsafe window may be wider than startup.

Also: src/lua/call.c:666 still calls g_main_context_invoke_full(NULL, ...) on master today, so the bridge itself looks unchanged. I can't say whether 511ed8ce (button images, 2026-09-10) changes how often it is hit.

Core available on request (134 MB zstd via systemd-coredump; contains process memory, so not attached).

wildhuman avatar Oct 02 '26 13:10 wildhuman

Spell it out step by step how to reproduce. You're focused on convincing me there is a problem, but you aren't giving me the information I need to recreate it and understand it.

Did you start darktable with an image specified on the command line? Did you start darktable and then import the image? Was it a fresh darktable config?

I want to be able to recreate the issue, but I can't even figure out where to start with the explanation above.

wpferguson avatar Oct 02 '26 15:10 wpferguson

Correction to my comment above, and answers to your questions.

Correction: I claimed this was "not just a startup window" and that the main loop was fully running. That's wrong — I hadn't established a launch time and inferred one too generously. The main thread's stack ends in dt_init() → gtk_widget_show(), so darktable was still starting up and the main loop was not running. GTK's recently-used log puts the file open at 08:29:25.277, ~3 s before the abort. This is the same startup race as #22357, not a wider window.

Your questions:

  1. Image on the command line? Yes: Command Line: /usr/bin/darktable /home/…/a.dng. It was opened from Thunar — the process cgroup is Thunar's app scope (app-Hyprland-gtk\x2dlaunch-b9df667c.scope → /usr/bin/thunar). So darktable was started with the path, not started and then pointed at an image.
  2. Started darktable, then imported? No. The file was passed at launch and darktable imported it during startup — it wasn't in the library before (newest row, id 5 of 5), and its XMP sidecar was written at 08:29:28.505, in the same second as the abort.
  3. Fresh config? No. An established library (~/.config/darktable, DB snapshots from 2026-09-25, darktable installed 2026-09-14). There is no user luarc — Lua came from the shipped /usr/share/darktable/luarc (the lua/luarc/darktable_first_run_complete=TRUE preference is written by that file), so tools/script_manager was the Lua in play.

Reproduction: I can't give you a reliable recipe. I have not reproduced it, and it's sporadic here too — a later launch with the same image (08:47:52) completed and exited normally. The only pattern that matches your setup: darktable started with an image path (in my case from a file manager) with the shipped luarc/script_manager active, so that image import and gtk_widget_show() overlap.

wildhuman avatar Oct 02 '26 15:10 wildhuman

I wrote a command line script for i in picdir/* ; do dartable $I ; done, which imported a new image into darktable, then I killed darktable, then darktable started again and imported the next image. No problems other than I got tired of clicking to stop darktable.

Tried importing a new folder of images from the command line. No problems.

All my testing was with a clean darktable build of master (yesterdays), with a new configuration file, with and without a user luarc. I'm running on X11, so it's possible that Wayland introduces another variable. I can try wayland in a VM.

wpferguson avatar Oct 02 '26 16:10 wpferguson

Indeed, maybe wayland. I'll consider it an isolated incident and will advise if it happens again and/or I glean any other insights. Many thanks for taking a look!

wildhuman avatar Oct 02 '26 16:10 wildhuman

Tried on wayland 100 times and didn't reproduce.

I'm going to disable all the protections we have in place that prevents Lua GUI stuff from crashing darktable, then try the patch and see what happens.

wpferguson avatar Oct 02 '26 17:10 wpferguson

@wpferguson The initial Claude Code's analysis says:


I checked this on current master (1c4eaea9df). The reporter's analysis is correct, and the problem is still there.

Root cause

At startup, darktable runs luarc (and so script_manager) on a background thread, then carries on building and showing the main window. The GTK main loop only starts after that.

Lua's GTK calls go through gtk_wrap() (src/lua/call.c:666), which uses g_main_context_invoke_full() to hand the work to the GUI thread. Before the main loop starts, nobody owns the main context. In that case glib doesn't hand the work over: it runs it immediately on the calling thread. So script_manager builds its widgets on a Lua worker while the main thread is showing the window. GTK isn't thread-safe, so sometimes that corrupts memory.

I confirmed this with gdb. In one startup with an image on the command line, 205 Lua GTK calls ran on a worker thread while the main thread was still inside dt_init(), sizing and showing widgets. That run didn't crash, but the overlap happens on every startup.

Why it's hard to reproduce

The two threads overlap every time, but a crash needs bad timing. I suspect slow icon loading makes it more likely: both reports have glycin-based image loading, which runs each icon load in a separate process. I haven't tested that. An image on the command line also makes startup longer, which gives the threads more time to overlap.

Fix options

  1. In gtk_wrap(), always queue the call on the GUI thread (e.g. with g_idle_add_full()) instead of using g_main_context_invoke_full(). That's already what happens once darktable is running, so startup would just behave the same way. Shutdown needs checking: a Lua job that calls gtk_wrap() after the main loop has stopped could wait forever. If this works, the darktable_gui_safe flag and the first-run sleep in luarc may no longer be needed.
  2. Don't run luarc until the main loop is running. This changes more, because luarc currently relies on seeing the first switch to lighttable during startup.

I'd go with option 1.


I'm running a few more rounds. I'll keep you posted.

kofa73 avatar Nov 18 '26 17:11 kofa73

@wpferguson They are now pretty sure about the root cause, but not about the complete fix.


The root cause stands: during startup, Lua's GTK calls run on a worker thread while the main thread is still building the window. Corrections to my earlier comment:

  • Glycin: only the original reporter's core shows it. wildhuman's report doesn't say.
  • Image on the command line: not needed. It makes startup longer and the overlap more likely, but the original reporter crashed without one.
  • Likely trigger: script_manager registers its module from the worker, and that rebuilds the module expanders while the main thread is laying them out. Both crash traces fit this, but the core doesn't prove it.
  • Why you might not see it (a guess): with a git-based scripts install, script_manager runs git checks before building its widgets, which can push that work past startup. Both reporters used system-installed scripts, which skip those checks.

Fix:

  • Option 1 is still my choice, but it needs two changes:
    • with no GUI (darktable-cli), call directly, or it hangs forever.
    • shutdown: control workers run Lua import/export hooks synchronously, and shutdown waits for them. If a hook's GTK call is queued after the last event processing, shutdown hangs. A "still running?" check doesn't close that gap. This part isn't designed yet.
  • Option 2 is out: images imported from the command line rely on Lua already running so their import events reach scripts.
  • The same pattern (g_main_context_invoke() from worker threads) also exists outside Lua, e.g. signals and the view switch. Those need separate fixes.

kofa73 avatar Nov 18 '26 19:11 kofa73

Does #22146 fix it?

wpferguson avatar Nov 18 '26 20:11 wpferguson

Does #22146 fix it?

#22146 should fix #22357's startup crash (and more, as it closes the startup race for every caller of g_main_context_invoke), but it needs a drain before dt_control_shutdown() so that queued GUI calls can't hang quit.

Claude Code's quick analysis of the shutdown:


  • The PR keeps ownership until just before dt_control_shutdown() (darktable.c:2807). The last event processing before that is at :2781. In between, dt_ctl_switch_mode_to("") and dt_dbus_destroy() run.
  • Suppose a worker queues a call in that gap. Examples: an export job raising the synchronous DT_SIGNAL_IMAGE_EXPORT_TMPFILE (signal.c:186-188, raised for every exported image), or a Lua export hook calling gtk_wrap(). That worker then waits on its cond for good: releasing the context doesn't run calls that are already queued, and dt_control_shutdown() joins the workers without processing events.
  • On master the same calls run inline on the worker. That is unsafe, but it doesn't hang. Exports do keep running during shutdown: your earlier test had one finish about 12 s after Ctrl+Q.
  • To fix this, the PR needs a drain step at release, similar to the gate and drain in your working-tree change.
  • A minor point: after the release, GTK calls from workers run inline again during dt_control_shutdown(), as on master. The main thread is only joining threads at that stage, so the risk is low.

kofa73 avatar Nov 19 '26 05:11 kofa73

While investigating, they found 12 new issues (I mean bugs to be reported as new). :-(

I had Claude Code add rules to my darktable-review skill (I'll set up a repo and publish the agent skills I've created to help LLMs work with the code, or we can add them to this one -- @TurboGit ), but also asked what we could do programmatically:


While looking into #22357 and #22146, I found more places where a background thread calls GTK directly, or waits for the GUI thread in a way that can hang. Some of these could be caught by a script, similar to dt-lockcheck (#22043). I'd make it a separate script: dt-lockcheck looks at locking in src/iop, while this one would look at which thread runs which code, everywhere in src.

Simple checks it could do:

  1. Find Lua functions that touch GTK but aren't wrapped with dt_lua_gtk_wrap(). For example panel_*, lib:reset and style:apply aren't wrapped, although dt.styles.apply() is.
  2. Find threads that check "should I stop?" without holding the lock, then go to sleep. The control workers in src/control/jobs.c do this, so they can miss the wake-up at shutdown.
  3. Find callbacks queued for the GUI thread that keep a pointer to a module or widget, but never get cancelled when the module is destroyed.
  4. For a pull request, list new places where the GUI thread waits for another thread, so the reviewer can check them.

A full check, "can this background code reach GTK?", is much harder. Many calls go through function pointers, such as an export format's set_params(), which updates the PNG export widgets from the export thread. A simple text-matching script won't follow those.

For that, a runtime check is easier: a small preloaded library that logs a backtrace whenever a GTK function runs outside the main thread. It only catches code that actually runs, so it needs a few test runs: starting with Lua scripts and an image, exporting and then quitting, and Lua hooks.

Some things still need a human, like whether quitting can leave a thread waiting forever.

kofa73 avatar Nov 19 '26 06:11 kofa73

(I mean bugs to be reported as new). :-(

They are not bugs. Lua was only intended to be used in Lighttable, and as long as it's used in lighttable these "bugs" don't occur.

When Lua was added to darktable it was specifically prohibited from being used in darkroom to process images. Using the "buggy" functions in darkroom does cause a crash, which enforces the policy (somewhat harshly 😄 )

We currently skirt the usage of Lua in darkroom by using darktable.gui.action() to manipulate the UI, which doesn't cross the boundary of processing images.

wpferguson avatar Nov 19 '26 16:11 wpferguson

They are not bugs.

You haven't seen them. :-) Not all of them have to do with Lua, at all.

kofa73 avatar Nov 19 '26 18:11 kofa73

@kofa73 is it possible to ask the LLM to prove the bug exists, not just accept the LLM's explanation which sometimes is just wrong. If it can't prove the bug exists, could it at least add print statements that at least show the issue and then run it and provide the output.

When I troubleshoot, I identify the likely culprit, then I add print statements to completely understand the behavior rather than relying on what I think it does based on reading the code. The print statements capture the interactions that aren't obvious from just a code snippet

My reasoning is this. Someone raised an issue, or skipped it and wrote a PR, about aspect ratio. I read the LLM analysis and it was completely wrong. The reason I knew was because I wrote the code. The person posting took it as fact was was set to make changes or have changes made based on the LLM's analysis.

I'm concerned that there are a lot of things getting "fixed" that may not be broken or are not bugs. The people running the LLM's don't have enough knowledge of how darktable works to tell the truth from half truth or hallucination. And the people that do know are so overloaded reading the constant stream of issues and PRs that they don't have enough brain cells left for critical thinking.

wpferguson avatar Nov 19 '26 18:11 wpferguson

is it possible to ask the LLM to prove the bug exists

Yes. Most of the bug reports I posted come with reproducers, often in the form of scripts one can run to trigger a crash or other bug, and the agent starts the software on a virtual X or Wayland screen, uses the GUI, and takes screenshots (check issue 22687 for an example - I'm not adding a hash here because I don't want to add confusing 'mentions' between these unrelated issues). The 12 issues I mentioned are actually candidates, they came up as potential bugs, and I have not had the time to have them investigated, so nothing has been filed, yet.

What were you referring to when you said "They are not bugs. Lua was only intended to be used in Lighttable, and as long as it's used in lighttable these "bugs" don't occur." The shutdown issues do not involve the darkroom. Export can be started from the Lighttable.

kofa73 avatar Nov 19 '26 18:11 kofa73

The shutdown issues do not involve the darkroom. Export can be started from the Lighttable.

but it does involve a set of steps that would/should never happen. Intermediate export is only for handling the export, not for making GUI calls. I don't think we should "fix" code to permit bad programming.

What were you referring to when you said "They are not bugs. Lua was only intended to be used in Lighttable, and as long as it's used in lighttable these "bugs" don't occur."

dt.style_apply()

EDIT:

All of the Lua functions that access internals to perform actions, with the exception of dt.gui_action(), are intended to run in lighttable and not darkroom. There are scripts, such as external editors, that run in darkroom but they only call an external editor on the image, so they don't really process.

wpferguson avatar Nov 19 '26 19:11 wpferguson

Claude Code's response + reproducer (yes, unusual, a tight loop, a stress test).


Agreed. style:apply only touches the GUI when the image is open in darkroom (src/lua/styles.c:255-256).

The same list also had dt.gui.panel_* and lib:reset. Neither one is wrapped, and both crash in lighttable.

How I reproduced it: I used master 1c4eaea9df on headless X11 with a fresh config, and passed an image folder on the command line, so darktable opened in lighttable.

To trigger it, put this in luarc and start darktable with a folder:

local dt = require "darktable"
dt.control.sleep(8000)  -- wait until lighttable is up and the main loop runs
for i = 1, 300 do
        dt.gui.panel_hide_all()
        dt.gui.panel_show_all()
end
  • This crashed 5 times out of 5. The SIGSEGV is on the Lua thread, inside GTK (gdk_window_hide / gtk_widget_map under dt_ui_panel_show).
  • dt.gui.libs.export:reset() in the same loop crashed 3 times out of 3. One of those was glibc's "corrupted size vs. prev_size".
  • Then I routed these functions through dt_lua_gtk_wrap and ran both loops again. All 10 runs finished without a crash.

The loop is a stress test, not normal use. The unmodified examples/panels_demo.lua makes the same calls from the Lua thread: a gdb breakpoint on dt_ui_panel_show shows them there while the main thread runs g_main_loop_run. It did not crash in 10 runs.

About GUI calls during export: official/selection_to_pdf.lua (lines 140-144) reads title_widget.text and no_of_thumbs_widget.value in its storage's finalize_store. finalize_store runs on the export worker (src/lua/luastorage.c:234, called from src/control/jobs/control_jobs.c:2158). Both reads go through gtk_wrap. With only the first commit of #22146, the worker waits for the GUI thread. If you quit during such an export, darktable can hang. The second commit (4a09ae506b) covers that case. I have not run selection_to_pdf to show the hang.


kofa73 avatar Nov 19 '26 19:11 kofa73

You need to test for darktable_gui_safe. It usually takes more than 8 seconds. What you're code does is try access widgets in lighttable before lighttable is initialized. You have to wait for the second time the view is changed to lighttable.

EDIT

When darktable starts it has to set the view to lighttable BEFORE it tries to initialize lighttable. Once the llibs are loaded, the view is changed to lighttable again, but at this point it's OK for Lua to talk to it.

EDIT 2

If the bug is so easily reproducible why don't we see it in the wild?

wpferguson avatar Nov 20 '26 00:11 wpferguson

@wpferguson Look, I was only trying to help. I don't use Lua at all. I tried to check if there were bugs mentioning crashes, so I could use some spare tokens to help fix darktable. Found 22745, which sat there untouched; that one then led me here.

If the bug is so easily reproducible why don't we see it in the wild?

It crashes 100% with a forced reproducer, which can mean sporadic, random crashes in the wild. If you say it's not worth chasing, I'll accept that.

With this in my luarc, darktable crashes after startup.

require "tools/script_manager"
local dt = require "darktable"
while not darktable_gui_safe do dt.control.sleep(100) end
dt.control.sleep(20000)
for i = 1, 300 do
        dt.gui.panel_hide_all()
        dt.gui.panel_show_all()
end

kofa73 avatar Nov 20 '26 05:11 kofa73