Skip to content

refactor: consolidate atomic writes and locking to use fileutil primitives#113

Open
xzq-xu wants to merge 1 commit intoHKUDS:mainfrom
xzq-xu:refactor/consolidate-fileutil
Open

refactor: consolidate atomic writes and locking to use fileutil primitives#113
xzq-xu wants to merge 1 commit intoHKUDS:mainfrom
xzq-xu:refactor/consolidate-fileutil

Conversation

@xzq-xu
Copy link
Copy Markdown
Contributor

@xzq-xu xzq-xu commented Mar 31, 2026

Summary

  • Fix concurrent state corruption in routing_policy.py: _save_state performed atomic writes but lacked advisory locking. Multiple processes (e.g. several agents running inbox watch) could interleave read_state → mutate → _save_state and silently lose updates. All read-modify-write cycles (decide, flush_due, record_dispatch_result) are now wrapped in file_locked().
  • Deduplicate locking code in store/file.py: FileTaskStore._write_lock reimplemented the full 22-line platform-specific fcntl/msvcrt locking pattern already provided by fileutil.file_locked(). Replaced with a one-liner, removing sys, contextmanager, tempfile, and platform imports.
  • Deduplicate atomic write in store/file.py: _save_unlocked reimplemented mkstemp + os.replace + cleanup already provided by fileutil.atomic_write_text(). Replaced with a one-liner.
  • Remove unnecessary JSON round-trip in router.py: json.loads(message.model_dump_json(...)) serialized to string then immediately deserialized. Replaced with direct message.model_dump(...).

Net result: -34 lines, one concurrency bug fixed, three modules now consistently use the project's own fileutil primitives.

Test plan

  • All 459 tests pass
  • Ruff lint clean
  • Lock file path for FileTaskStore unchanged (.tasks.lock in tasks root)
  • routing_policy state persistence verified through existing test_runtime_routing.py suite

Made with Cursor

@xzq-xu xzq-xu force-pushed the refactor/consolidate-fileutil branch from 4581d6a to af0a2ec Compare April 3, 2026 03:31
- store/file.py: replace 22-line _write_lock with file_locked() and
  replace _save_unlocked with atomic_write_text(), removing duplicated
  platform-specific locking code (sys, fcntl/msvcrt, contextmanager,
  tempfile imports all removed).
- routing_policy.py: wrap read-modify-write cycles in file_locked()
  to prevent concurrent processes from losing state updates; replace
  hand-rolled mkstemp+replace in _save_state with atomic_write_text().
- router.py: replace json.loads(model_dump_json()) with model_dump()
  to eliminate unnecessary serialization round-trip.

Made-with: Cursor
@xzq-xu xzq-xu force-pushed the refactor/consolidate-fileutil branch from af0a2ec to c2fdee1 Compare April 7, 2026 02:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant