Skip to content

libsimlin: sync_state TOCTOU race in apply_project_patch_internal #297

Closed

Description

@bpowers

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:

  1. Line 441: sync_state.lock().unwrap().take() sets sync_state to None
  2. Lines 442-446: Incremental sync to staged state
  3. 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_incremental with prev_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_internal function (lines 441, 501-523)
  • Root cause: Taking vs. restoring sync_state is not atomic with respect to concurrent patch calls

Possible Solutions

  1. 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.

  2. Lock-based atomicity: Hold sync_state lock for the entire operation (lines 441-530), preventing other threads from observing intermediate None states.

  3. 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

  1. bpowers commented on Feb 24, 2026

    @bpowers
    OwnerAuthor

    Fixed in PR #289 (incremental compilation). Regression test added in PR #314.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions