Repository navigation
Conversation
- Add to to serialise concurrent calls to . - Move write from the top of to after completes, so any waiter on only sees the hash updated once is fully populated. - Apply double-check pattern in : fast-path check without the lock, acquire lock, then re-check before calling . This prevents a second concurrent caller from running while the first is still connecting to servers, which would cause intermittent "Tool not found" errors. - Add to verify the fix. Co-Authored-By: ForgeCode <noreply@forgecode.dev>
…t test - refresh_cache now holds init_lock before clearing tools and resetting the config hash, closing the race where reload_mcp could wipe the tool map while an in-flight update_mcp was still populating it - Switch test_concurrent_init_does_not_race to multi_thread flavor (worker_threads = 2) so true parallelism exercises the timing windows that the cooperative scheduler cannot produce Co-Authored-By: ForgeCode <noreply@forgecode.dev>
Response to reviewBoth points are correct and the changes were genuinely needed. Fix 1: The race is real. The breaking sequence:
Any subsequent Fix 2: Since all critical sections cross |
Summary
Fix a race condition in
ForgeMcpServicewhere two concurrentinit_mcpcallers could leave the tool map empty, causing spurious "Tool not found" errors at startup.Context
When Forge starts and multiple requests trigger MCP initialisation simultaneously, the old code wrote
previous_config_hashat the top ofupdate_mcp— before any server connections were established. A second concurrent caller would then see the hash already updated, conclude there was nothing to do, and return early against an emptyself.toolsmap. Any subsequent tool call would fail with "Tool not found" despite the MCP server being correctly configured.Changes
init_lock: Arc<Mutex<()>>toForgeMcpServiceto serialise concurrentinit_mcpcallsupdate_mcpprevious_config_hashwrite to after all MCP connections (successful or failed) complete inupdate_mcp, so any waiter released frominit_locksees a fully populated tool mapKey Implementation Details
The double-checked locking pattern in
init_mcp:is_config_modifiedbefore acquiringinit_lock; return immediately if unchanged (no contention on the common case)init_lock, re-checkis_config_modified(another task may have completed init while we waited), then callupdate_mcpupdate_mcpstampsprevious_config_hashonly afterjoin_allfinishes, guaranteeingself.toolsis fully populated when any waiter is releasedTesting
cargo test -p forge_servicesNew test added:
test_concurrent_init_does_not_race— fires two concurrentget_mcp_servers()calls on a sharedArc<ForgeMcpService>and asserts that after both settle, every registered tool is callable without error.