Repository navigation
fix(capture): claim model calls in one file per rollout, not a marker per call - #6216
Conversation
… per call Each captured model call created and deleted its own .capture.pending marker, and readers globbed the whole capture dir to find them: at least three full listings per rollout, and one every 50 ms while a claim was open. On a shared filesystem that is a create and an unlink per call plus repeated listings of a directory that grows with the run. Claims now append to <rollout_id>.capture.claims. A claim resolves when the call's row lands in the capture file, or through a release line when the row never will. Readers open the two per-rollout files by name and never list the dir. The drain poll backs off from 50 ms to 1 s. The snapshot removes the claims file once nothing is outstanding, so the dir keeps one file per rollout. The guarantee from #4593 is unchanged: a claim exists for the call's whole lifetime, readers in other processes and later jobs see it, and a stranded claim still yields model_call_capture_pending. The capture JSONL format is untouched. The health check still honours .capture.pending markers left in run dirs from older releases. Signed-off-by: Wojciech Prazuch <[email protected]>
has_pending resolved claims by scanning the rollout's capture file for landed ids. That file holds full request and response payloads and can reach hundreds of MB, and the scan ran on every drain poll and again in the merge, so a rollout's capture was read about three times instead of once. _record now appends a release line after every write, in a finally around the capture append. It runs in the worker thread after the row is written or has failed, even when the awaiting coroutine was cancelled, so a reader that sees no open claim also sees the row. has_pending reads only the small claims file: claims minus releases. Per call this is a claim append, the capture append and a release append to one existing file per rollout, with no create or unlink per call. Signed-off-by: Wojciech Prazuch <[email protected]>
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
SHIP WITH CARE
I found three RISK issues affecting capture completeness and health measurements. They do not change reward computation. I inspected all 11 changed files and traced the affected writer, snapshot, judge-evidence and health paths. This was a static review; I did not execute tests.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
| else: | ||
| # Nothing is outstanding at the snapshot, so the claims file has done its job. | ||
| with contextlib.suppress(OSError): | ||
| store.clear_all_pending(rollout_id) |
There was a problem hiding this comment.
RISK: Snapshot cleanup can erase a newly admitted call's claim.
A late call can finish mark_pending() after has_pending() returns false but before this unlink. Cleanup then removes the live claim, so a fresh reader reports no pending work while the call is still running. If that writer dies, later readers have no stranded-claim evidence. The append lock does not prevent this because clear_all_pending does not coordinate retirement with appenders. Judge evidence cleanup has the same defect and uses an even earlier cached drained result.
Could you keep settled claims until explicit pre-dispatch cleanup, or introduce retirement coordinated with admissions across processes? Merely locking this inode around check/unlink is insufficient: an appender may already have opened the inode being unlinked. The invariant is that snapshot cleanup cannot erase an outstanding claim or let a successful admission write into an unlinked file.
The smallest safe source correction is to remove both snapshot-retirement blocks:
--- a/nemo_gym/rollouts/model_calls.py
+++ b/nemo_gym/rollouts/model_calls.py
@@
- else:
- # Nothing is outstanding at the snapshot, so the claims file has done its job.
- with contextlib.suppress(OSError):
- store.clear_all_pending(rollout_id)
--- a/environment_servers/swe_together/judge_evidence.py
+++ b/environment_servers/swe_together/judge_evidence.py
@@
- if drained:
- # Nothing is outstanding, so the claims file has done its job.
- with contextlib.suppress(OSError):
- store.clear_all_pending(episode)If taking that approach, remove the unused contextlib imports and update the removal assertions and documentation. Keeping automatic deletion requires a stronger protocol; I have not established a small safe locking patch. Verify any suggested patch before adopting it.
Acceptance, proposed and not executed: seed one released call, pause merge after its false pending read, admit a second call, then resume cleanup while holding the second write. A fresh store must still report pending, a short drain must return false, and a subsequent merge must include model_call_capture_pending. Mirror admission during read_available() in judge collection. After the second write and release, drain must return true and readback must contain both calls. Retain the stranded-claim and late-settled cases in the existing test, claims-only polling, and directory-listing-free reads.
There was a problem hiding this comment.
Fixed. After a snapshot, the check and the delete happen together under the claims lock, so a claim taken in between keeps the file. Test: test_deleting_settled_claims_never_hides_a_call_admitted_meanwhile.
| with self.claims_path_for(rollout_id).open("ab") as handle: | ||
| fcntl.flock(handle.fileno(), fcntl.LOCK_EX) | ||
| try: | ||
| handle.write(orjson.dumps(entry, option=orjson.OPT_APPEND_NEWLINE)) |
There was a problem hiding this comment.
RISK: An unterminated damaged tail swallows the next valid claim.
If the claims file ends with b'{"cla', appending {"claim":"next"}\n produces one malformed line. has_pending skips that entire line and returns false even though mark_pending("r", "next") succeeded. The middleware then forwards the call, so an interrupted append can hide a later live call from completeness checks. The existing damaged-line test terminates its fragment with a newline and misses this case.
Could _append_claim_line establish a line boundary before every entry under its existing exclusive lock? A small replacement for this line is:
| handle.write(orjson.dumps(entry, option=orjson.OPT_APPEND_NEWLINE)) | |
| handle.write(b"\n" + orjson.dumps(entry, option=orjson.OPT_APPEND_NEWLINE)) |
The inspected parser already skips blank lines. Update the exact claims-file assertion in test_record_releases_the_claim_after_the_row_is_written to ignore them. Alternatively, repair only an unterminated tail under the same lock. The invariant is that a damaged previous append cannot consume a later valid claim or release. Keep serialization, claims-only reads and release-after-row ordering unchanged. Verify the suggestion before adopting it.
Acceptance, proposed and not executed: seed b'{"cla', mark next, and expect pending=true; release next and expect false. Also seed a complete outstanding claim followed by an unterminated fragment, append its release, and expect false. Retain rollout isolation, unsafe-ID round-tripping, the assertion that the claim stays open during store.record(), and the cancellation test's assertion that it stays open until the detached write finishes.
There was a problem hiding this comment.
Fixed. Every append starts with a newline. Tests: test_a_torn_tail_cannot_swallow_the_next_claim and ..._a_release.
| pattern = f"{_validate_rollout_id(rollout_id)}.*{_PENDING_SUFFIX}" | ||
| for marker in self._root.glob(pattern): | ||
| marker.unlink(missing_ok=True) | ||
| self.claims_path_for(rollout_id).unlink(missing_ok=True) |
There was a problem hiding this comment.
RISK: Pre-dispatch cleanup leaves stale legacy pending markers behind.
clear_model_call_captures_for_rollouts still relies on this method to clear pending state before reusing a deterministic rollout key. Previously it removed that key's per-call markers; now it removes only the claims file.
For example, leave 0-0.old.capture.pending from an interrupted older run, clear captures for 0-0, then record and release a fresh complete capture under that key. The stale marker survives. The health reader still treats it as outstanding, so a fresh failure row without an attached capture stays unmeasured: rollouts_with_captures is 0 instead of 1.
Could you remove legacy markers for the selected keys at the explicit pre-dispatch boundary? Keep legacy discovery out of polling and merge. A single batch migration scan can avoid the former per-rollout listings, but requires adjusting the new test that forbids listings during clear. I have not established a correction that both discovers arbitrary legacy marker names and keeps that strict no-listing constraint.
Preserve the distinction between stale state for a key being cleared and evidence in an untouched older run: cleanup must not delete markers for other rollouts or attempts, and health must still exclude an uncleared legacy pending capture.
Acceptance, proposed and not executed: create legacy markers for 0-0, 0-0-a1 and 1-0, plus JSONL, incomplete and claims files for 0-0. Clear only 0-0; all its stale files must be gone and the other keys must remain. Record and release one fresh call for 0-0, then use a failure row without ng_model_call_capture with the timeout test helper: expect rollouts_with_captures == 1. Retain the existing legacy-pending case's expected count of 0 when no cleanup occurs.
There was a problem hiding this comment.
Fixed. Pre-dispatch cleanup also removes the earlier .capture.pending markers of the reused IDs. Test: test_clearing_before_dispatch_removes_only_the_cleared_keys_pending_markers.
An append cut short by a crash leaves an unterminated fragment at the end of the claims file. The next entry was appended onto it, the joined line failed to parse and was skipped, and a live claim read as settled. Each entry now starts with a newline, written under the same exclusive lock. The parser already skips blank lines, so a torn tail can no longer swallow a later claim or release. Signed-off-by: Wojciech Prazuch <[email protected]>
The snapshot read the claims as settled and then unlinked the file. A call admitted between the two lost its claim with the file, and a writer that had opened the file before the unlink appended into a dead inode. Either way a later reader saw nothing outstanding. The judge evidence path retired on an even older drain result. CaptureStore.retire_claims_if_settled reads and unlinks under LOCK_EX. After taking that lock, an appender checks that its file is still the one at the path (nlink and inode); if it was retired it reopens and appends to the replacement. Merge, judge evidence and the post-snapshot capture delete all retire through this method, so the capture dir still keeps one file per rollout and no admitted claim can disappear. Signed-off-by: Wojciech Prazuch <[email protected]>
Older releases claimed each call with a `<rollout id>.<token>.capture.pending` marker, and pre-dispatch cleanup used to remove a key's markers before reusing it. Without that, a marker left by an interrupted older run survived the clear, and the health check kept treating the fresh capture for the same key as pending, so its failed row went unmeasured. Pre-dispatch cleanup now lists each capture dir once per call and removes only the markers whose rollout id is one of the cleared keys, never other attempts or rollouts. Polling, merge and the post-snapshot delete stay listing-free, and an uncleared older run is still read as before. Signed-off-by: Wojciech Prazuch <[email protected]>
| # Judged under the appenders' lock now, not from the earlier drain. | ||
| with contextlib.suppress(OSError): | ||
| store.retire_claims_if_settled(episode) |
There was a problem hiding this comment.
NOTE: The judge discards the result of retire_claims_if_settled, so judge_capture_incomplete still depends only on the earlier drain. The comment above the call says the opposite: that the gap is now judged under the appenders' lock.
A judge call can be claimed after the drain returns but before this read. In that case retire_claims_if_settled returns False and keeps the claims file, yet the evidence records no gap. Running the scenario from test_a_judge_call_admitted_during_the_read_keeps_its_claim produces only ['turns_unavailable'], while the claim is still open. The rollout merge already treats the same False as a gap (model_calls.py L209-L210).
The window is narrow, and no reward reads this gap, so the impact is on the accuracy of the evidence, not on scores. Could the judge use the result the way the merge does, counting an OSError as unsettled, and could the test assert the gap?
| # Judged under the appenders' lock now, not from the earlier drain. | |
| with contextlib.suppress(OSError): | |
| store.retire_claims_if_settled(episode) | |
| try: | |
| settled = store.retire_claims_if_settled(episode) | |
| except OSError: | |
| settled = False |
Then change the check at L194 to if not drained or not settled or store.is_incomplete(episode):, and drop the contextlib import, which is no longer used.
There was a problem hiding this comment.
Done. An unsettled or unreadable claims file now adds judge_capture_incomplete.
| ) | ||
| ) | ||
| if store.has_pending(rollout_id): | ||
| if not store.retire_claims_if_settled(rollout_id): |
There was a problem hiding this comment.
NOTE: If retire_claims_if_settled raises an OSError, the merge throws away calls it has already read.
retire_claims_if_settled opens the claims file with mode r+b, so it needs write access. A PermissionError or a read-only filesystem error falls into the broad except below. That handler sets calls = [] and adds model_call_capture_unreadable, even though _read_capture_records had already succeeded. For example, with the claims file made read-only (mode 0444), the merge attaches no calls, while on main it attached the one recorded call. The live collection paths own their capture directory, so this mainly affects callers of the exported function that point it at an archived or shared directory.
Could a failed retire count as unsettled instead, so the calls are kept?
| if not store.retire_claims_if_settled(rollout_id): | |
| try: | |
| settled = store.retire_claims_if_settled(rollout_id) | |
| except OSError: | |
| settled = False | |
| if not settled: |
There was a problem hiding this comment.
Done. An OSError counts as unsettled, so the merge keeps its calls and adds model_call_capture_pending.
| for _ in range(_CLAIM_APPEND_ATTEMPTS): | ||
| # No fsync: readers on other nodes see the line without one, and a crash that loses it ends the call too. | ||
| with path.open("ab") as handle: | ||
| fcntl.flock(handle.fileno(), fcntl.LOCK_EX) |
There was a problem hiding this comment.
NOTE: Claiming a call now takes this exclusive file lock (flock) synchronously on the model server's event loop, because the middleware calls mark_pending directly before forwarding (L1141).
On main, a claim was a single touch. Now _append_claim_line opens the claims file, takes the exclusive lock, runs fstat and stat, writes, unlocks and closes, all on the event loop. On a shared filesystem such as Lustre, each lock request is a round trip to the metadata server. The lock also waits for any other claim or release being appended, or for a retire in progress, to finish. While it waits, every stream on that model server waits too. In a local reproduction where another process held the lock, the event loop stalled for 6.2 s. Lock holds are short in normal runs, so this shows up mainly during the metadata server stalls this PR is meant to ease.
Could the claim run off the event loop, while still happening before the call is forwarded? await asyncio.to_thread(self._store.mark_pending, rollout_id, model_call_id) keeps that order. It shares the default executor with the capture writes, so under a backlog of writes it moves the delay to the start of each call instead of stalling every stream.
There was a problem hiding this comment.
Done. The claim runs in asyncio.to_thread, inside the try, so a cancel during the claim still releases it.
| # Offload the blocking write+fsync so it never stalls the event loop. Shielded: a write | ||
| # cancelled before it starts would leave this call's claim outstanding until the drain timeout. |
There was a problem hiding this comment.
NOTE: The shield does not change behavior, so the comment describes a case that cannot happen.
asyncio.to_thread submits _record to the executor in the same step that first awaits it, before any point where the task can be suspended. A cancellation after that can only stop the wait. The thread still runs _record, and its finally releases the claim. A reproduction cancelled the handler in two ways, through an anyio cancel scope and through a second task.cancel(), each with and without the shield, and the write ran in all four cases. For the same reason, reverting the shield makes no test fail.
Could you drop the shield, or keep it and say what it does protect?
| # Offload the blocking write+fsync so it never stalls the event loop. Shielded: a write | |
| # cancelled before it starts would leave this call's claim outstanding until the drain timeout. | |
| # Offload the blocking write+fsync so it never stalls the event loop. The thread runs | |
| # `_record` even if this task is cancelled while it waits, so the claim is always released. |
There was a problem hiding this comment.
Kept, with a new comment. It matters when the thread pool is busy: a cancelled, still-queued write would never run. test_a_cancelled_write_queued_behind_busy_threads_still_releases_its_claim fails without it.
| return False | ||
| return _has_outstanding_claim(content) | ||
|
|
||
| def retire_claims_if_settled(self, rollout_id: str) -> bool: |
There was a problem hiding this comment.
NOTE: This method is named retire, but in Gym retiring means removing records and leaving a fence that turns away later writes. This method does the opposite.
The token-capture ledger defines two operations (protocols.py L262-L284). Retire removes the records and keeps a fence that discards any record arriving later. Delete removes both the records and the fences, before an ID is reused. The checkpoint stack uses retire the same way. This method deliberately lets a late claim recreate the file, so it is a delete that runs only when nothing is outstanding. clear_all_pending is an unconditional delete before an ID is reused, the same operation as delete_now in clear_token_captures_for_rollouts.
Could these be named delete_claims_if_settled and delete_claims, with the docstrings and the _is_live comment ("not one a reader has retired") updated to match? The check and the unlink should stay together under the lock, as they are now. The rename also reaches the OSError message "was retired on every attempt" (L223), the warning "Could not retire the capture claims" (L277), the comment at L216, and the test names that say retiring.
There was a problem hiding this comment.
Renamed to delete_claims_if_settled and delete_claims.
| def clear_model_call_captures_for_rollouts( | ||
| records: list[Any], capture_dirs: list[Path], *, before_dispatch: bool = True | ||
| ) -> None: | ||
| """Remove stale per-rollout capture files for these records before dispatch. |
There was a problem hiding this comment.
NOTE: This function now does two jobs selected by one boolean, and the first line of its docstring is wrong for one of them.
With before_dispatch=True, it deletes captures, claims and markers from older releases before an ID is reused. With before_dispatch=False, it is the cleanup after a snapshot: it deletes claims only when nothing is outstanding and does not list the directory. The docstring line "Remove stale per-rollout capture files for these records before dispatch" describes only the first job.
Could the post-snapshot cleanup be its own function, called from enrich_run_result? That also removes the default value, which today makes a new call site silently get the pre-dispatch behavior.
There was a problem hiding this comment.
Split. The post-snapshot cleanup is now clear_model_call_captures_after_snapshot.
|
|
||
| if delete_capture and safe_to_delete: | ||
| clear_model_call_captures_for_rollouts([result], capture_dirs) | ||
| clear_model_call_captures_for_rollouts([result], capture_dirs, before_dispatch=False) |
There was a problem hiding this comment.
NOTE: No test checks that this call passes before_dispatch=False.
If the argument is dropped, the call falls back to the pre-dispatch behavior. The post-snapshot cleanup then unlinks a claim taken after the merge, and it lists the capture directory once per rollout. test_clearing_after_a_snapshot_keeps_an_outstanding_claim calls clear_model_call_captures_for_rollouts directly, so it still passes. The test below drives enrich_run_result instead. It passes on this head and fails when the argument is dropped:
Test that pins the post-snapshot cleanup
def test_deleting_a_merged_capture_keeps_a_claim_admitted_after_the_merge(tmp_path, monkeypatch):
import nemo_gym.rollouts.rollout_collection as collection
store = CaptureStore(tmp_path)
store.mark_pending("22-0", "call-1")
store.record("22-0", {"model_call_id": "call-1", "dialect": "responses", "request": {}, "response": {"id": "r"}})
store.clear_pending("22-0", "call-1")
merge = collection.merge_model_call_capture_into_record
def merge_then_admit(record, *args, **kwargs):
merged = merge(record, *args, **kwargs)
store.mark_pending("22-0", "late")
return merged
monkeypatch.setattr(collection, "merge_model_call_capture_into_record", merge_then_admit)
row = {"_ng_task_index": 22, "_ng_rollout_index": 0}
asyncio.run(collection.enrich_run_result(row, dict(row), capture_dirs=[tmp_path], observability_enabled=True, delete_capture=True))
assert not store.path_for("22-0").exists()
assert store.has_pending("22-0") is True| includes `model_call_capture_pending`. The model server claims each call in | ||
| `<rollout_id>.capture.claims` before forwarding it and releases the claim once its record is | ||
| written; the file is removed once the rollout's record is snapshotted with nothing outstanding. |
There was a problem hiding this comment.
NOTE: This paragraph should state two things: the claims file now relies on a lock that every writer shares, and it can be left behind.
- A lock shared by every writer. On
main, readers never deleted a claim, so claims relied only on creating and unlinking files. Now a reader deletes the claims file, and a claim taken at the same moment survives only because both sides take the sameflock. If locks are local to each node (a Lustre mount withlocalflock) and a model server on another node appends claims, a claim can be written into the file that was just unlinked and be lost. In a local reproduction with locks that did not exclude each other, 32 open claims were lost. With a real shared lock, none were. Gym's own model server runs on the collector's node, so the default layout is safe. A model server on another host that shares the capture directory is not. The resume page already states the same requirement (resume.mdx L41-L42). - Files that stay. The claims file is removed only when the snapshot finds no claim outstanding. If a rollout still had a call in flight, or a call arrives after the snapshot, the claims file stays next to its capture file until the same ID is dispatched again.
Could the page say both, and suggest a node-local model_call_capture_dir when the model server and the collector share a node?
There was a problem hiding this comment.
Done. The page covers both, including the node-local lock case.
|
|
||
| def pending_path_for(self, rollout_id: str, model_call_id: str) -> Path: | ||
| return self._root / f"{_validate_rollout_id(rollout_id)}.{_pending_token(model_call_id)}{_PENDING_SUFFIX}" | ||
| def claims_path_for(self, rollout_id: str) -> Path: |
There was a problem hiding this comment.
NOTE: This PR removes CaptureStore.pending_path_for from an exported class, and the old and new claim formats cannot read each other.
Neither Gym nor NeMo RL main (80c0564) calls pending_path_for, so removing it is fine in practice. What changes behavior is running two different releases together. A model server from an older release writes one marker file per call, which the new drain and merge do not read. A call still in flight is then snapshotted without a model_call_capture_pending gap. In the other direction, an older collector ignores claims files. This happens only when a separately started model server runs a different release from the collector.
Could the compatibility section of the description say that the model server and the collector must run the same release, and name claims_path_for and has_pending as the replacements for pending_path_for?
There was a problem hiding this comment.
Done in the description. The model server and the collector must run the same Gym version.
|
|
||
| # Runs from older releases claimed each call with its own `<rollout id>.<call token>.capture.pending` file. | ||
| _PENDING_SUFFIX = ".capture.pending" | ||
| _CLAIMS_SUFFIX = ".capture.claims" |
There was a problem hiding this comment.
NOTE: The glossary reserves "claim" for checkpoint restore, and this PR makes it a file suffix, an on-disk key and a doc term.
key-terminology.mdx L82 defines a claim as a replacement attempt taking a restored record, and L86-L91 lists the only other features allowed their own sense of the word. Capture claims are not on that list, so a reader of model-call-capture.mdx meets a defined term with a different meaning.
The code also uses two vocabularies for one operation. The methods are still mark_pending, clear_pending and has_pending, while the docstrings and the file say claim and release. A failed release logs "Could not clear model-call capture pending" from clear_pending and "Could not release the capture claim" from _record. Comments also say "older releases" for earlier Gym versions next to "release a claim", "dir" for directory, and "the appenders' lock", a name used nowhere else.
Could this PR add capture claims and their release to the list at L86-L91, and use claim and release in the log messages and comments ("earlier Gym versions", "directory", "the claims file's lock")?
There was a problem hiding this comment.
Done. The glossary now lists capture claims as another sense of the word.
In Gym, retire means remove and keep a fence. A claims file is removed with no fence, so rename retire_claims_if_settled to delete_claims_if_settled and clear_all_pending to delete_claims. Logs, comments and the glossary now say take and release a capture claim, earlier Gym versions, and directory. Signed-off-by: Wojciech Prazuch <[email protected]>
The judge ignored the settled check, so a judge call claimed after the drain left no gap. It now adds judge_capture_incomplete. An OSError from the check no longer makes the merge drop the calls it already read. Both count it as unsettled. Signed-off-by: Wojciech Prazuch <[email protected]>
…pre-dispatch one clear_model_call_captures_after_snapshot deletes claims only once settled and lists nothing. enrich_run_result calls it. clear_model_call_captures_for_rollouts loses its before_dispatch flag, so a new caller cannot get the pre-dispatch cleanup by default. A test now drives enrich_run_result. Signed-off-by: Wojciech Prazuch <[email protected]>
The claim waits on the claims file's lock, which stalled every stream on the model server. It now runs in a thread before the call is forwarded, inside the try, so a call cancelled while claiming is recorded and releases its claim. The record write keeps its shield. Without it, a cancel drops a write still queued behind busy threads, and the claim is never released. Signed-off-by: Wojciech Prazuch <[email protected]>
A claims file stays while a call is in flight at the snapshot or arrives after it. Claims rely on one file lock every writer shares, so node-local locks can lose claims from a model server on another host. Signed-off-by: Wojciech Prazuch <[email protected]>
init-nikhil
left a comment
There was a problem hiding this comment.
If the request gets cancelled while the claim is being written, can the release get written first? Looks like the collector could delete that release, then the claim lands afterward and stays pending even though the captured row is already there. Can we wait for the claim write before releasing it?
…claim lands A cancel does not stop the claim's worker thread, so the release could land first; a collector pass could then delete that settled claims file and leave the late claim outstanding. Signed-off-by: Wojciech Prazuch <[email protected]>
|
Thanks for the careful read. All five are addressed in 67bc1f8:
Each fix has a test that fails with the fix removed. |
|
Good catch, thanks. Yes, that could happen. A cancel does not stop the claim's worker thread, so the cancelled call could write its row and release while the claim was still waiting. A collector pass could then delete that settled claims file, and the claim landed in a fresh one and stayed outstanding. Fixed in 5ca6317: the claim now runs as a task that a cancel does not stop, and the cancelled call's write waits for it before appending the release. |
|
/ok to test 5ca6317 |
marcromeyn
left a comment
There was a problem hiding this comment.
Thanks, this is a big step. Cleanup after the snapshot, the reopen check in has_pending, the restored clear_all_pending and the release-order test all look right to me, and so does the cancel-while-claiming fix. What's left:
- Deletion before the row is saved. In
enrich_run_result,clear_model_call_capture_after_snapshotruns in a worker thread, andwriter.write(record)runs only after it returns. A cancel during that await skips the write, while the thread still deletes the capture. A resume reruns the row, so the run isn't corrupted, but the capture of the calls that attempt paid for is gone with nothing written. Could the deletion happen after the shard row is written, and on the return-only path after the result is handed back? - Snapshot vs. settlement. The merge reads the payload and then checks the claims. If call B writes and releases between those two steps, it looks like the record misses B with no gap, and the claims file is removed. Is there something that rules that ordering out?
- Drain deadline. The lock budget is computed before the job is submitted to the default executor, and the await has no timeout, so time spent waiting for a free worker adds to the deadline. Would it hold under a busy executor?
- Other async readers. Agentic IF Realworld (
benchmarks/agentic_if_realworld/rollout_driver.py) and GDPVal (multistage_orchestrator.py) seem to call the synchronous merge from async code, so a held claims lock would pause their loops for the lock wait. Should they offload it too? - Read errors with
delete_capture. An error opening the payload for the snapshot (aPermissionError, say) seems to escape before the merge can reportmodel_call_capture_unreadable. Skipping deletion on that error would keep the existing report. clear_all_pendingon a missing directory. It now raises fromos.scandir, where the old glob returned nothing, which matters for callers usingCaptureStore(create=False).- Cancellation test. It orders the collector pass with a 200 ms sleep. An event or a controlled executor would make it deterministic.
…s under their lock - A recorded shard writes its row before its capture is deleted. enrich_run_result starts the deletion as it returns instead of awaiting it. - The merge reads the capture while holding the claims lock, so no call claims or releases between the read and the settlement check. - The drain bounds each poll by its deadline, time queued for a worker included. - GDPVal, Agentic IF Realworld and the TB4 smoke script merge off the event loop. - A snapshot that can't open the capture skips the deletion. clear_all_pending finds nothing in a missing directory again. - The cancel-while-claiming test runs on a held executor instead of a sleep. Signed-off-by: Wojciech Prazuch <[email protected]>
|
Thanks. All seven are addressed in d0bff13:
Each fix has a test that fails with the fix removed. |
Keeps the module imports clear of main's new import, so the branch merges cleanly. Signed-off-by: Wojciech Prazuch <[email protected]>
Signed-off-by: Wojciech Prazuch <[email protected]>
marcromeyn
left a comment
There was a problem hiding this comment.
Thanks, the claims lock across the read and the check, the bounded drain, the offloaded merges and the executor-driven cancellation test all look right to me. Two things left in the deletion path, and one question:
- Deletion still runs when nothing was saved. In
run_examples,clear_model_call_capture_after_snapshotruns whenever there's a snapshot, butwriter.write(record)returnsNonefor a_ng_no_persistrow that the writer doesn't keep (record_omitted_rolloutsoff), so the capture goes with nothing written. Withrecord_staging_dir, the row is only staged at that point, so the capture is deleted before the shard is published. Could the deletion depend onwrite()returning a path, and for a staged writer happen once it publishes? - Read-only archives get a false pending gap. With
while_locked,delete_claims_if_settledopens the claims file witha+bso it can create it. On a read-only directory (an archived run) that raises, the merge catches it assettled = Falseand addsmodel_call_capture_pending, even though the payload was read in full and nothing is outstanding. Could a failure to create a missing claims file count as settled when there is no claims file to read? - Question, GDPVal: now that the merge runs in
asyncio.to_thread, a cancel during that await infinish()seems to drop the completion it already took off the iterator, so a resume could dispatch the policy again for a finished rollout. Is the current completion still saved on that path?
…ly claims, save GDPVal rollouts through a cancel - A recorded shard deletes a capture only when write() saved its row, and a staged shard only once it is published. - Claims this process cannot write (an archived run) are read under a shared lock; a missing claims file is settled. - GDPVal finishes saving a rollout whose calls are being joined before a cancel goes on. Signed-off-by: Wojciech Prazuch <[email protected]>
|
Thanks. All three are handled in 872e54b:
Each fix has a test that fails with the fix removed. |
Resolve the conflict with #6552 in model_call_capture.py: the claims-file claim now runs on the gated per-call store, and both write paths pass caller_server to _record, which still releases the claim itself. Signed-off-by: Wojciech Prazuch <[email protected]>
marcromeyn
left a comment
There was a problem hiding this comment.
Thanks, all three look right to me, and each new test fails with its fix taken out.
- The capture is now deleted only when
write()saves the row. A staged shard deletes its captures after it is published, and a superseded writer or a failed copy raises before that, so its captures stay for the retry. - A read-only archive reads the claims under a shared lock and gets
model_call_capture_pendingonly while a claim is outstanding. - GDPVal saves the rollout before the cancel goes on, on both the dispatched and the cached
/verifypath.
The merge with main also looks right: it keeps the claim task and the release after the write, next to #6552's capture selection, which returns before claiming for a call it doesn't capture.
One small thing, not blocking: in _finish_despite_cancel, if the save raises while a cancel is pending, the save's error propagates and the cancel is dropped. Raising the cancel there, with the save's error logged, would keep the caller's cancellation intact.
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/46653401214 |
What does this PR do?
Each captured model call created and deleted its own
.capture.pendingmarker, and readers globbed the whole capture directory to find them: at least three full listings per rollout, plus one every 50 ms while a claim was open. On a shared parallel file system that is a file create and unlink per model call, and repeated listings of a directory that grows with the run.Now each rollout has one append-only
<rollout_id>.capture.claimsfile:_recordappends a release after the call's row is written or has failed. The release runs in the worker thread, so it happens even when the caller was cancelled. A call cancelled while claiming still claims, and its release waits for that claim, so a release never lands before its claim.delete_model_call_capture, the capture's device, inode and size are recorded just before the merge reads it. The capture is deleted only under the claims file's lock, with no claim outstanding and the capture unchanged since that snapshot. A row that landed after the snapshot keeps the capture..capture.pendingmarkers of the keys it clears, listing each capture directory once per call.The guarantee from #4593 is unchanged: a claim exists for the call's whole lifetime, readers in other processes and later jobs see it, and a stranded claim still yields
model_call_capture_pending.Validation
pytestontest_base_responses_api_model.py,test_model_calls.py,test_rollout_collection.py,test_health_timeouts.py,test_rollout_health.py,test_streamed_capture_reports.py,test_moved_paths.py: 1597 passed (1585 onmain, no new failures).has_pendingnever opens the capture file; the release follows the row; a cancelled call keeps its claim until its detached write finishes; a reader still waits for an in-flight write; a late call after the snapshot reads as settled; old run directories still read; a held claims lock neither blocks the event loop nor reads as settled;has_pendingfollows a replaced claims file; deleting a merged capture keeps a row or claim that arrived after the merge; a call cancelled while claiming settles even with a collector pass before its claim lands. Each of the last four fails with its fix removed.pre-commit run --files <changed files>passes.Rollouts
N/A: no change to what is captured or to rollout results.
Compatibility and benchmark impact
None for results. The capture JSONL format is unchanged. A new file per rollout while it runs:
<rollout_id>.capture.claims. The health check still honours.capture.pendingmarkers left by earlier Gym versions..capture.pendingmarkers, which the new drain and merge do not read; an earlier collector ignores claims files. This matters only for a separately started model server.CaptureStore.pending_path_foris removed. Useclaims_path_forandhas_pending.CaptureStore.clear_all_pendingstill works but is deprecated: usedelete_claims.localflock), a model server on another host that shares the capture directory can lose claims. Gym's own model server runs on the collector's node, so the default layout is safe.Checklist
model-call-capture.mdx).git commit -s).