Repository navigation
fix(core): survive concurrent state writes and null tool-call names - #4048
Conversation
JsonFileAgentStateStore wrote every atomic replacement through a fixed "<file>.tmp" sibling. Two threads persisting the same session state concurrently race on that path: one thread's move consumes the file the other is still writing, surfacing as NoSuchFileException and potentially moving interleaved (corrupt) bytes into place, which later fails state loads with MalformedInputException. Use a per-write unique tmp name so each move is independent. ToolRequestConfig.resolveTool passed a model-supplied tool name straight into an immutable map; a tool call without a name NPE'd and killed the whole turn instead of degrading to the existing "Tool not found" result. Resolve null names to not-found.
Unique tmp names are no longer reclaimed by a later save, so a write that fails mid-flight would leave its tmp sibling on disk forever. Delete it on failure, and assert no tmp survives the concurrent-save test.
ningmao-hlyz
left a comment
There was a problem hiding this comment.
The null-name fix is right; ToolExecutor already handles a null tool and the constructor rejects null keys. The concurrency fix needs another round: the new test fails on Windows, and appendToList is not covered.
| @@ -316,16 +323,39 @@ private void writeHashFile(Path hashFile, String hash) throws IOException { | |||
| } | |||
|
|
|||
| private static void atomicWriteString(Path file, String content) throws IOException { | |||
There was a problem hiding this comment.
Unique tmp names fix the tmp race, not the target race. Writers still move into the same agent_state.json, and Windows locks the target during another thread's replace. The new test fails 3/3 on Windows with AccessDeniedException. A per-target lock around write+move fixes it; retrying the move is weaker.
| Files.move(tmp, file, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); | ||
| } | ||
|
|
||
| private void appendToList(Path file, List<? extends State> items) throws IOException { |
There was a problem hiding this comment.
The list path is still unsynchronized. save(List) lands here when the hash matches and the list grew, then appends into the target with no tmp file and no lock. A 4-thread x 20 read-modify-write probe kept 47 of 80 entries and threw 13 times. The same per-target lock around read-hash-count + append/rewrite covers it; a JVM lock is enough for two threads, multi-process needs FileChannel.lock().
| } | ||
| Files.move( | ||
| tmp, file, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); | ||
| } catch (IOException e) { |
There was a problem hiding this comment.
toJson(item) in rewriteEntireList throws JsonException (a RuntimeException), so this catch misses serialization failures. Saving a list with an unserializable State leaves k.jsonl.*.tmp behind. Catch RuntimeException too, or clean up in a finally.
| assertTrue(loaded.isPresent()); | ||
| // The winner is whichever thread moved last; it must be a complete, intact document. | ||
| assertTrue(loaded.get().value().matches("v\\d+")); | ||
| assertTrue(loaded.get().count() >= 0 && loaded.get().count() < iterations); |
There was a problem hiding this comment.
count() >= 0 && count() < iterations is true for any winner, and value and count are not checked as a pair. A document mixing value from one write and count from another would pass. Assert the pair.
Unique tmp names fixed the tmp-file race but not the target race: two threads still replace the same agent_state.json, and Windows rejects the replace with AccessDeniedException while another thread holds the target (CI failed 3/3 on windows-latest). Add striped per-target-file locks around write+move. The list save path needs the same lock around its whole read-hash-count + append/rewrite sequence, or two concurrent saves can append the same tail twice and interleave an append with a rewrite. The hash file is only written while holding the list file's lock. Also clean up tmp files in a finally: toJson throws a RuntimeException (not IOException), which the previous catch missed, so a list containing an unserializable State would leave its unique tmp file behind forever. Tests now encode the writer in both fields of TestState so a torn document mixing fields from two writes cannot pass, and a concurrent read-modify-write probe covers the list path (asserting intact lines, no duplicates, no tmp leftovers).
|
Thanks for the thorough review — all four points are addressed in eb8237d:
On the ubuntu-latest |
Writer-side locking alone still failed on Windows (AccessDeniedException in rewriteEntireList's move while another thread read the same file): on Windows an open read handle blocks another thread's replace of the same target, so readers and writers must share the per-file lock. Apply it to get, getList, and the single-key delete for consistency.
|
Follow-up (2552513): writer-side locking alone still failed the list test on Windows — |
ningmao-hlyz
left a comment
There was a problem hiding this comment.
Follow-up review after the latest updates — the locking and cleanup fixes land well. Two comments marked [P0] question whether the guarantee holds beyond a single store instance; the rest are smaller notes.
| */ | ||
| private static final int LOCK_STRIPES = 64; | ||
|
|
||
| private final ReentrantLock[] writeLocks = createLockStripes(); |
There was a problem hiding this comment.
[P0] These locks are per-instance, so the guarantee is single-store, single-JVM.
Two JsonFileAgentStateStore instances on the same root (e.g. two agents each constructing their own store against the default ~/.agentscope/state, L95) don't exclude each other — the races this PR fixes reproduce as before. Suggestion: make the stripe table static, keyed by normalized absolute path — a ~3-line diff, no behavior change for single-instance use. For cross-process (shared NAS) deployments I'd document single-process ownership in the Javadoc rather than reach for FileChannel.lock(): file locks are advisory and unreliable on NFS (even SQLite, the one project that made multi-process file locking truly work, documents this), and the Python implementation of this project offers only SQL and Redis backends — no file store — so pointing multi-process users at another AgentStateStore matches how the family already solved it.
Nit: the field is still writeLocks / "Striped write locks", but get/getList now take the same locks — fileLocks fits better.
There was a problem hiding this comment.
Done in c8b684d. The stripes are now static (SESSION_LOCKS), keyed by the session directory's normalized absolute path, so every instance in the JVM shares them. sessionOperationsWaitForAnInFlightSave runs each operation on a second store constructed with root.resolve("."), so differently spelled roots must land on the same stripe. Reverting either the static table or the normalization made all eight cases fail in the mutation check.
For cross-process use I followed your suggestion rather than adding FileChannel.lock(): the class Javadoc now states that a session must be owned by one process at a time and points multi-process deployments at a database-backed AgentStateStore.
I used SESSION_LOCKS rather than fileLocks because the key is now the session directory, not an individual file. This also lets session deletion share the lock with every file operation inside that session.
| // toJson can throw a RuntimeException mid-write; the finally keeps unique tmp | ||
| // names (never reclaimed by a later write) from piling up. No-op after a | ||
| // successful move. | ||
| deleteQuietly(tmp); |
There was a problem hiding this comment.
[P0] The append path has no such protection: a serialization failure leaves a partially applied save.
When the hash matches and the list only grows, save routes to appendToList (L186–195), which opens the target directly with CREATE, APPEND — no tmp, no rollback. If toJson throws mid-loop, the first k−1 lines are already in the file and writeHashFile (L154) never runs: the failed save has partially taken effect, and the stored hash no longer matches the file. A retry self-heals via the prefix-hash mismatch in needsFullRewrite, but without a retry the dirty tail items stay visible to getList despite the reported failure.
There was a problem hiding this comment.
Fixed the serialization-failure case in c8b684d. appendToList now serializes and encodes the entire tail before opening the target, so a toJson failure cannot leave any new item behind. It then writes the prepared buffer through a FileChannel, looping until the buffer is drained. If a write throws IOException, it attempts to truncate back to the original size; a rollback failure is attached as a suppressed exception rather than hidden.
failedAppendLeavesListUntouched saves [a, b], then attempts [a, b, c, <unserializable>], and asserts that both .jsonl and .hash remain byte-identical and getList still returns [a, b]. A subsequent valid append also succeeds. Reverting to the old streaming append makes this test fail because c is left behind. The mid-write I/O rollback branch is not unit-tested; exercising it requires I/O fault injection.
To be explicit about the remaining boundary: this is not a transaction across the list and hash files. A successful list write followed by a failed hash write, or an interruption that closes the channel and prevents rollback, can leave changed data with a stale hash. The existing prefix-hash check repairs that on the next save; it does not make those failure cases invisible before a retry.
| @Override | ||
| public void delete(String userId, String sessionId, String key) { | ||
| Path file = getStatePath(userId, sessionId, key); | ||
| ReentrantLock lock = lockFor(file); |
There was a problem hiding this comment.
Directory-level operations sit outside this lock discipline: delete(userId, sessionId) (L257) deletes the whole session dir, and clearAllSessions() (L303), exists() (L252), listSessionIds() (L279) are all unlocked — concurrent with a save/get, Windows fails to delete open files and Linux can remove a dir mid-write.
Also worth fixing in this PR: single-key delete removes only key.json, leaving key.jsonl / key.hash behind, which getList will keep serving. Could this delete both shapes plus the hash file under the same lock?
There was a problem hiding this comment.
Fixed in c8b684d. With the lock keyed by session directory:
delete(userId, sessionId)andexists()take the session lock.clearAllSessions()deletes each session under that session's lock. Its existence check runs inside the lock, so an already-deleted session is skipped and not counted.- Both
saveoverloads create the session directory inside the lock, so a save queued behind a delete recreates it instead of writing into a removed directory. - Single-key deletion removes
key.json,key.jsonl, andkey.hashunder the same lock, matching COS/OSS and Mongo.deleteKeyRemovesStateListAndHashchecks that both state shapes disappear and an unrelated key remains intact.
listSessionIds() deliberately stays unlocked: it enumerates the user directory's entries and does not open session files. A per-session lock would not make a listing across multiple sessions atomic. A concurrently created or deleted session may or may not appear; the code comment now documents that behavior. Similarly, clearAllSessions() synchronizes each deletion rather than providing a global snapshot transaction.
The parameterized cross-instance test covers get, getList, both save overloads, key deletion, session deletion, exists, and clearAllSessions while a save holds the session lock.
| int iteration = Integer.parseInt(parts[1]); | ||
| assertEquals(writer, loaded.get().count() / 1000); | ||
| assertEquals(iteration, loaded.get().count() % 1000); | ||
| assertTrue(writer < threads); |
There was a problem hiding this comment.
Nit: writer / iteration are parsed from the winning document, and every writer emits values within [0, threads) / [0, iterations) by construction — these two asserts can never fail. The pair equality above is the real check; these can go.
Two coverage gaps: ① tmp cleanup is only asserted on the success path — the finally added for a mid-rewrite serialization failure has no test; ② saveListSurvivesConcurrentReadModifyWrite covers getList-vs-save on the .jsonl, but get-vs-save on key.json (the tmp+replace path this PR's reader locking targets) is only read after all writers finish.
There was a problem hiding this comment.
Done in c8b684d. The two always-true range assertions are gone; assertConsistentPair now checks the writer/iteration encoded in both fields of every written document read by these tests.
For the coverage gaps:
failedRewriteLeavesListUntouchedforces serialization to fail after the rewrite has started, then asserts the original list is byte-identical, remains readable, and no.tmpfile is left. Removing the cleanup infinallymakes the test fail.saveSurvivesConcurrentWritesToSameKeynow runs four readers alongside eight writers across two store instances and checks everyagent_state.jsonthey observe. Get-vs-save on the tmp+replace path is exercised during writes, not just afterward.
I also mutation-checked the fixes individually: per-instance locks, missing path normalization, removal of each operation's lock, the old streaming append, missing rewrite tmp cleanup, and .json-only key deletion. All 12 mutations failed their corresponding tests.
Validation on local JDK 17: the 19 state-store tests passed five consecutive runs; the full agentscope-core suite passed with 3,037 tests, zero failures/errors, and nine skipped. Spotless also passed. This is local macOS validation, not a claim that the updated Windows CI has already passed.
The striped locks were per instance, so two JsonFileAgentStateStore instances on the same root (e.g. two agents each building their own store on the default ~/.agentscope/state) did not exclude each other and the races fixed earlier came back. Make the stripes static and key them by the session directory's normalized absolute path. They still do not span processes: the Javadoc now states that a session must be owned by one process at a time and points multi-process deployments at a database-backed store, since file locks are unreliable on NFS. Keying the locks by session rather than by file lets the directory operations join the same discipline: delete(session), clearAllSessions() and exists() now take the session lock, so deleting a session can no longer race a save or read of a file inside it. listSessionIds() only reads directory entries and stays unlocked. delete(key) now also removes the key's .jsonl and .hash files, so getList no longer serves a deleted list. appendToList serialized and wrote item by item into the live file, so a toJson failure part-way left the earlier items behind with a stale hash. Serialize the whole tail first, write it as one buffer, and truncate back to the original size if the write fails. Tests: readers now run during the concurrent writes and check every document they see, the always-true range asserts are gone, a parameterized test checks that each session operation of a second instance waits for an in-flight save, and new tests cover a failed append, a failed rewrite (no tmp file left behind) and single-key delete.
ningmao-hlyz
left a comment
There was a problem hiding this comment.
Re-checked at c8b684d on Windows (JDK 17): 19/19 pass, five consecutive runs. With main's JsonFileAgentStateStore swapped back under the same tests, 13 of the 19 fail, so the new tests do hold the old code to account.
Two things this change introduces that I would fix before merge.
The stripes couple unrelated sessions. lockFor picks one of 64 locks by path.hashCode(). 200 session directories under one root landed on 58 stripes in my count, so a few unrelated sessions share a lock, and since appendToList serializes the whole tail while holding it, one session's save makes the others wait. LocalSessionStorage and WorkspaceManager both keep a ConcurrentHashMap<Path, ReentrantLock> per path instead. That key needs canonicalizing as well: normalize() resolves neither symlinks nor Windows 8.3 names, so C:\Users\ADMINI~1\state and C:\Users\Administrator\state end up on different locks. LocalSessionStorage already calls toRealPath() on its root, and this root exists by the end of the constructor.
delete(key) now leaves an empty session directory. After the last key goes, the directory stays behind and exists(), listSessionIds() and clearAllSessions() still count that session. In a probe I get 0 files in the directory and exists() == true. Removing the directory when it empties, still under the lock, would match COS and JDBC; pinning today's behaviour with a test is the other option.
One optimization, your call: reads now take the same exclusive lock, so concurrent get and getList calls serialize. A ReentrantReadWriteLock would keep them parallel for one more lock type. exists() also waits on the session lock to run a stat, which is the one place it surprised me.
Nit on the description: it still only covers the unique tmp name, so the squash commit reads as if that was the whole fix.
Resolve the store root to its real path and use JVM-wide per-session locks so root aliases synchronize without coupling unrelated sessions. Retain lock entries so deletion cannot split queued and new operations across different locks. Remove the session directory after its last key is deleted, while still holding its lock and after closing the directory stream. Cover prior stripe collisions, alias-root locking, last-key deletion and recreation.
|
Thanks for the Windows re-check and the additional review. Follow-up to #4048 (review) — addressed in 88bb030:
I kept exclusive reader locking for now; a read/write lock remains a separate optimization, rather than expanding this correctness fix. The PR description has been rewritten to cover the complete implementation and its boundaries. Local macOS / JDK 17 validation: 33 state-store executions passed five consecutive runs with no skips; the full core suite ran 3,088 tests with zero failures/errors and nine skipped. Spotless passed without bypassing its check. The new tests produced 13 assertion failures and one timeout before this follow-up fix. No claim of a Windows pass for the new commit or I/O fault-injection coverage; those validation boundaries remain explicit in the description. |
ningmao-hlyz
left a comment
There was a problem hiding this comment.
One gap from your body I could close: this host's java.io.tmpdir is the 8.3 form, so C:\Users\ADMINI~1\... and C:\Users\Administrator\... resolve to the same root and contend on the same lock. A read through one store was still blocked after 300 ms while the other held the session lock. Symbolic links ran here rather than being skipped.
save, get and getList still resolve getSessionDir twice, while delete(key) and exists() resolve it once. The shape you used in delete costs less.
unrelatedSessionsDoNotShareLocks recomputes floorMod(hash, 64) to find a pair that used to collide. 64 is gone from the production code, so a comment saying it mirrors the removed stripe count would help.
Nothing blocking from my side.
Derive every operation's session lock and state, list and hash paths from a single getSessionDir call, so a lock and the files it guards always come from the same directory value. Drop the now-unused lockFor(userId, sessionId) overload. Name the former 64-stripe count in unrelatedSessionsDoNotShareLocks, since the production code no longer defines it.
|
Thanks for running the 8.3 and symbolic-link cases on Windows; that closes the validation gap I had left open in the description. Both nits are addressed in bf54e5b:
Local macOS / JDK 17: the 33 state-store executions passed five consecutive runs with no skips; the full core suite ran 3,088 tests with zero failures/errors and nine skipped; Spotless passed. The description now records your Windows results for 88bb030 and notes that CI still needs to validate bf54e5b. |
|
LGTM |
AgentScope-Java Version
2.1.0-SNAPSHOT
Description
Fix two production failures observed in a long-running deployment using a NAS-backed
JsonFileAgentStateStore.1. Concurrent state persistence
A fixed
<file>.tmpsibling let concurrent saves consume or overwrite each other's temporary file, causingNoSuchFileExceptionand corrupt state. Unique temporary names alone did not protect concurrent replacement of the target, particularly on Windows.The complete fix now includes:
finally, including serialization failures.ConcurrentHashMap<Path, ReentrantLock>locking across store instances. Unrelated sessions no longer share a stripe. Lock entries are retained so queued operations and later writes cannot acquire different locks after session deletion.toRealPath()so stores opened through root aliases use the same lock key.exists(), and each deletion performed byclearAllSessions(). Save creates its session directory inside the lock. Each per-session operation resolves its session directory once and derives both its lock and its file paths from that value.Concurrency boundaries: these are JVM locks, not cross-process locks; each session must be owned by one process. Shared multi-process sessions should use a database-backed store. Separate read-modify-write calls remain last-writer-wins. Listing is weakly consistent, and clearing sessions is synchronized per deletion rather than as a global transaction. List and hash writes are not a two-file transaction: hash-write or interrupted-I/O failures can leave changed data with a stale hash until the next save.
2. Missing tool-call names
ToolRequestConfig.resolveToolpreviously passed a null model-supplied name into an immutable map, causing an NPE during permission evaluation. Null names now resolve to not-found, matching the executor's existingTool not foundbehavior.Validation
Local macOS / JDK 17, at
bf54e5b92:c8b684d46implementation, the regressions added in88bb03077produced 13 assertion failures and one timeout; all 14 new executions pass with the fix.agentscope-core: 3,088 tests run, zero failures/errors, nine skipped.git diff --checkpassed without skipping the formatting check.Command for the full core suite:
mvn -o -T1C -pl agentscope-core -am test -Djacoco.skip=trueWindows, at
88bb03077, as reported by the reviewer:java.io.tmpdiruses the 8.3 short form. Stores opened throughC:\Users\ADMINI~1\...andC:\Users\Administrator\...resolved to the same root and contended on the same session lock: a read through one store was still blocked after 300 ms while the other held the lock.CI at
88bb03077: the Windows and Linux builds passed.Remaining validation gaps: the Windows checks above have not been repeated for
bf54e5b92, which only changes how each operation derives its lock and file paths; Windows and Linux CI should validate the latest head. The symbolic-link cases skip on hosts that cannot create links. Mid-write I/O rollback is not fault-injection-tested. JaCoCo was disabled for the local test run; no coverage result is claimed.Checklist