Repository navigation
Description
Problem
In src/libsimlin/src/patch.rs, the apply_project_patch_internal function has a critical time-of-check to time-of-use (TOCTOU) race condition involving sync_state. The problem occurs between taking sync_state at line 441 and restoring it at lines 518-520:
- Line 441:
sync_state.lock().unwrap().take()sets sync_state to None - Lines 442-446: Incremental sync to staged state
- Lines 501-523: If patch is rejected or dry_run, attempt to restore prev_state
Between steps 1 and 3, another thread calling apply_project_patch_internal can:
- Observe
sync_state == None(because it was taken in step 1) - Call
sync_from_datamodel_incrementalwithprev_state = None - Resync the DB from scratch based on the original datamodel
- Hit the reject/dry-run branch (lines 501-523)
- Execute line 520:
*sync_state.lock().unwrap() = None - Return without restoring the original sync state
Result: The salsa DB and sync handles become inconsistent with the committed project state.
Why It Matters
This is a correctness issue affecting multi-threaded callers (Python bindings, any concurrent patch calls). While the WASM/TS path is single-threaded, the API is documented as thread-safe (lines 544-547). A concurrent patch call during validation/revert can corrupt the DB state permanently, causing silent failures in subsequent simulations.
Affected Component
src/libsimlin/src/patch.rs-apply_project_patch_internalfunction (lines 441, 501-523)- Root cause: Taking vs. restoring sync_state is not atomic with respect to concurrent patch calls
Possible Solutions
-
Clone instead of take (safest, minimal change): Clone prev_state instead of taking it at line 441, only update sync_state on commit (line 529). Concurrent readers would observe a consistent state.
-
Lock-based atomicity: Hold sync_state lock for the entire operation (lines 441-530), preventing other threads from observing intermediate None states.
-
Read-write lock: Use RwLock instead of Mutex to allow concurrent reads but exclusive writes during patch application.
Context
Identified during code review of PR #289 (incremental compilation implementation).
Activity
libsimlin: fix sync_state TOCTOU race in simlin_project_add_model
libsimlin: add deterministic patch race regressions
libsimlin: add deterministic patch race regressions (#314)
bpowers commentedon Feb 24, 2026
Fixed in PR #289 (incremental compilation). Regression test added in PR #314.