You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
State manager: concurrent writes to state.json cause data loss #409
During QA for #389, acceptance criteria data was silently lost due to concurrent state file writes. Two parallel bash calls both did read-modify-write on .sequant/state.json — the last writer won and overwrote the first writer's changes.
Reproduction
Run two state update chains in parallel:
# Chain A: writes acceptanceCriteria
npx tsx scripts/state/update.ts init-ac 389 3 && \
npx tsx scripts/state/update.ts ac 389 AC-1 met "done"# Chain B: writes phases + status (reads state before A writes)
npx tsx scripts/state/update.ts complete 389 qa && \
npx tsx scripts/state/update.ts status 389 ready_for_merge
Chain B reads state before Chain A saves, so B's write overwrites A's acceptanceCriteria additions.
Impact
Severity: Low — AC tracking is cosmetic/dashboard-only, doesn't affect workflow behavior
Frequency: Happens when QA skill runs AC updates and phase transitions as parallel bash calls
Data affected:acceptanceCriteria field on issue state (tracking only)
Acceptance Criteria
Concurrent state writes do not silently discard each other's changes
Existing state update CLI (scripts/state/update.ts) works without modification
No performance regression for sequential writes (the common case)
Approach Options
File locking — flock or lockfile around read-modify-write in StateManager.saveState()
Retry with conflict detection — read, modify, compare-and-swap (re-read before write, retry if changed)
Serialize at caller — ensure QA skill never runs state commands in parallel (simplest, least robust)
Option 1 is probably the right balance of correctness and simplicity.
Concurrent state writes do not silently discard each other's changes
MET
withLock() using O_EXCL serializes all read-modify-write cycles; verified by concurrent write test (Promise.all with separate manager instances)
AC-2
Original
Existing state update CLI works without modification
MET
scripts/state/update.ts is unchanged in diff; all 49 existing + 4 new tests pass
AC-3
Original
No performance regression for sequential writes
MET
Lock overhead is openSync+writeSync+closeSync+unlinkSync — microseconds for the common uncontended path; 50ms retry delay only under actual contention
Coverage: 3/3 AC items fully met
CI Status
Check
Conclusion
Impact
build (20.x)
SUCCESS
✅ MET
build (22.x)
SUCCESS
✅ MET
typecheck
SUCCESS
✅ MET
validate-skills
SUCCESS
✅ MET
validate-plugin
SUCCESS
✅ MET
CI Summary: 5 passed, 0 pending, 0 failed
Quality Metrics
Metric
Value
Status
Type issues (any)
0
✅ OK
Deleted tests
0
✅ OK
Files changed
3
✅ OK
Lines added
+322
-
Lines deleted
-128
-
Test Coverage Analysis
Changed File
Tier
Has Tests?
Test File
src/lib/workflow/state-manager.ts
Standard
✅ Yes
src/lib/workflow/state-manager.test.ts
CHANGELOG.md
Optional
N/A
-
Coverage: 1/1 changed source files have corresponding tests
Code Review
Strengths:
Clean approach: withLock() wrapper applied uniformly to all 11 mutating methods
Correct use of O_EXCL flag for atomic lock creation — the right primitive for cross-process file locking
Stale lock detection prevents deadlocks from crashed processes
Cache is cleared inside withLock() before the callback runs, ensuring latest state is read
lockTimeout is configurable via constructor option — good for testing
Lock release in finally block ensures cleanup even on errors
No API surface changes — fully backward compatible
Issues:
Minor (cosmetic): Line 687 in test file calls fs.utcTimesSync?.(...) which is a non-existent Node.js API (typo for fs.utimesSync). The optional chaining makes it a silent no-op rather than a crash, and line 690 correctly calls fs.utimesSync, so the test works. But it's dead code with a typo.
Suggestions:
Remove line 687 (fs.utcTimesSync?.(...)) — it's a no-op due to the typo and the correct call follows on line 690.
Test Quality Review
Category
Status
Notes
Behavior vs Implementation
✅ OK
Tests assert on observable state (data preserved, lock cleaned up), not locking internals
Coverage Depth
✅ OK
Covers: concurrent writes to different fields, rapid sequential writes (10 parallel), stale lock recovery, lock cleanup
Mock Hygiene
✅ OK
No mocks — tests use real filesystem via temp directories
Test Reliability
✅ OK
No timing dependencies; concurrency test uses Promise.all which is deterministic for the lock ordering
Anti-Pattern Detection
Code Patterns
No anti-patterns detected. Lock implementation uses synchronous fs calls appropriately (avoiding async race windows in the lock acquisition itself). Empty catch blocks in releaseLock and stale lock cleanup are justified — they handle benign race conditions between concurrent processes.
Verified working: Yes — 49 tests pass including 4 new concurrency-specific tests; build passes; CI green
Test efficacy: High — concurrent write test uses separate StateManager instances with Promise.all to reproduce the original race condition
Likely failure mode: On NFS or other network filesystems where O_EXCL may not be fully atomic. This is a known limitation of file-based locking and acceptable for .sequant/state.json which is always local.
Verdict confidence: High — implementation is straightforward, well-tested, and CI is green
Verdict: READY_FOR_MERGE
Clean implementation of file-based locking for StateManager. All 3 ACs are met, CI is green, tests are thorough, and there are no API changes. The only finding is a cosmetic typo in a test (fs.utcTimesSync → already handled by the correct fs.utimesSync call below it) — not blocking.
Documentation
CHANGELOG entry added
N/A — No new features/flags requiring README or docs updates
Next Steps
Optional: Remove the dead fs.utcTimesSync?.() call on test line 687 (cosmetic)
Run /docs 409 if documentation generation is desired
Activity
fix(#409): add file locking to StateManager to prevent concurrent wri…
admarble commentedon Mar 24, 2026
Exec Phase: Implementation Complete
AC Coverage
withLock()withO_EXCLfile locking inStateManagerscripts/state/update.tsunchanged; all 45 existing tests passKey Files Changed
src/lib/workflow/state-manager.tswithLock(),acquireLock(),releaseLock()methods; wrapped all 11 mutating methodssrc/lib/workflow/state-manager.test.tsCHANGELOG.md[Unreleased] > FixedTest Coverage Analysis
state-manager.tsQuality Checks
npm run buildnpm run lintnpm teststate-utils.test.tsunrelated to this change)PR
#417
Quality Plan Alignment: N/A - No quality plan in issue
admarble commentedon Mar 24, 2026
QA Review for Issue #409
AC Coverage
withLock()usingO_EXCLserializes all read-modify-write cycles; verified by concurrent write test (Promise.allwith separate manager instances)scripts/state/update.tsis unchanged in diff; all 49 existing + 4 new tests passopenSync+writeSync+closeSync+unlinkSync— microseconds for the common uncontended path; 50ms retry delay only under actual contentionCoverage: 3/3 AC items fully met
CI Status
build (20.x)build (22.x)typecheckvalidate-skillsvalidate-pluginCI Summary: 5 passed, 0 pending, 0 failed
Quality Metrics
any)Test Coverage Analysis
src/lib/workflow/state-manager.tssrc/lib/workflow/state-manager.test.tsCHANGELOG.mdCoverage: 1/1 changed source files have corresponding tests
Code Review
Strengths:
withLock()wrapper applied uniformly to all 11 mutating methodsO_EXCLflag for atomic lock creation — the right primitive for cross-process file lockingwithLock()before the callback runs, ensuring latest state is readlockTimeoutis configurable via constructor option — good for testingfinallyblock ensures cleanup even on errorsIssues:
fs.utcTimesSync?.(...)which is a non-existent Node.js API (typo forfs.utimesSync). The optional chaining makes it a silent no-op rather than a crash, and line 690 correctly callsfs.utimesSync, so the test works. But it's dead code with a typo.Suggestions:
fs.utcTimesSync?.(...)) — it's a no-op due to the typo and the correct call follows on line 690.Test Quality Review
Promise.allwhich is deterministic for the lock orderingAnti-Pattern Detection
Code Patterns
No anti-patterns detected. Lock implementation uses synchronous fs calls appropriately (avoiding async race windows in the lock acquisition itself). Empty catch blocks in
releaseLockand stale lock cleanup are justified — they handle benign race conditions between concurrent processes.CHANGELOG Verification
Result: CHANGELOG requirements met
Self-Evaluation
StateManagerinstances withPromise.allto reproduce the original race conditionO_EXCLmay not be fully atomic. This is a known limitation of file-based locking and acceptable for.sequant/state.jsonwhich is always local.Verdict: READY_FOR_MERGE
Clean implementation of file-based locking for
StateManager. All 3 ACs are met, CI is green, tests are thorough, and there are no API changes. The only finding is a cosmetic typo in a test (fs.utcTimesSync→ already handled by the correctfs.utimesSynccall below it) — not blocking.Documentation
Next Steps
fs.utcTimesSync?.()call on test line 687 (cosmetic)/docs 409if documentation generation is desiredfix(#409): add file locking to StateManager to prevent concurrent wri…