Repository navigation
Description
Problem
In src/libsimlin/src/project.rs, the simlin_project_add_model function has the same class of sync_state TOCTOU race as #297 (which covers apply_project_patch_internal in patch.rs).
At lines 362-369:
let prev_state = proj.sync_state.lock().unwrap().take(); // line 362: sets sync_state to None
let new_state = engine::db::sync_from_datamodel_incremental( // lines 363-367: rebuild DB
&mut db,
&project_locked.datamodel,
prev_state.as_ref(),
);
drop(db); // line 368: release DB lock
*proj.sync_state.lock().unwrap() = Some(new_state); // line 369: restore sync_stateBetween drop(db) on line 368 and restoring sync_state on line 369, another thread calling simlin_sim_new can acquire the DB lock, observe sync_state as None, and receive a NotSimulatable error because sync_from_datamodel_incremental is called with prev_state = None, triggering a full resync from scratch rather than using the incremental path.
Why It Matters
This is a correctness issue for multi-threaded callers (Python bindings, concurrent FFI calls). The API is documented as thread-safe, so concurrent add_model + sim_new calls should not produce spurious errors. The impact is a transient NotSimulatable failure that is non-deterministic and difficult to reproduce, making it a particularly confusing bug for users.
Components Affected
src/libsimlin/src/project.rs-simlin_project_add_modelfunction (lines 362-369)
Possible Solutions
The fix should restructure the lock protocol so sync_state is never in a None state visible to concurrent readers. Two straightforward approaches:
-
Hold the DB lock until after sync_state is restored: Move
drop(db)after the sync_state assignment on line 369, so no concurrent reader can observe the intermediate state. -
Clone instead of take: Replace
.take()with.clone()(as suggested for libsimlin: sync_state TOCTOU race in apply_project_patch_internal #297), so sync_state always holds a valid value and concurrent readers see the previous consistent state.
This does NOT warrant restoring the monolithic compilation fallback -- the incremental-only path is correct; the issue is purely about lock ordering.
Context
- Identified during Codex review of PR engine: incremental compilation followup fixes #300
- Same class of bug as libsimlin: sync_state TOCTOU race in apply_project_patch_internal #297 (sync_state TOCTOU in
apply_project_patch_internal), but in a different function - Related to libsimlin: concurrent reads during patch validation observe staged DB state #298 (staged DB state visibility during patch validation)
Activity