szn

Bug 504 — libthai loader and break context lack thread-safety synchronization (latent)

504. Unsynchronized global state and shared ThBrk pointer

Severity: LOW (latent — safe under single-threaded server architecture)
Status: 🟢 FIXED
Files: src/thai.zig:436-498

Problem

In src/thai.zig, dynamic loading of libthai is handled via mutable module globals:

var libthai_instance: ?LibThai = null;
var libthai_tried = false;

pub fn getLibThai() ?*const LibThai {
    if (!libthai_tried) {
        libthai_tried = true;
        initLibThai();
    }
    if (libthai_instance) |*inst| return inst;
    return null;
}

Furthermore, initLibThai allocates a single global ThBrk* word-breaker context handle (brk = th_brk_new(null)), and findWordBreaks executes libthai.th_brk_wc_find_breaks(libthai.brk, ...) directly on this shared instance.

Concurrency Risk:

Proposed Fix

  1. Add thread-safety documentation clarifying that libthai_instance and ThBrk are explicitly single-threaded and bound to the server thread lifecycle.
  2. If multi-threaded reflow or background workers are introduced in the future:
    • Guard getLibThai() with std.once or atomic initialization.
    • Allocate ThBrk per-thread or pass a local context into th_brk_wc_find_breaks.

Resolution