fix(checkpoint): guard _touch_project against non-dict project metadata - #22639
Closed
wesleysimplicio wants to merge 1 commit into
Closed
Conversation
Problem
=======
`tools.checkpoint_manager._touch_project` reads the project metadata
file with `json.loads(meta_path.read_text(...))`, then immediately does:
meta["workdir"] = str(_normalize_path(working_dir))
The `except` block only catches `(OSError, ValueError)`. When the file
parses successfully but returns a non-dict value (a list `[]`, `null`,
or a scalar from a corrupted or hand-truncated write), `json.loads`
succeeds without error and `meta` is set to, e.g., `[]`. The subsequent
subscript assignment then raises `TypeError: list indices must be
integers or slices, not str`, which is NOT caught by the narrow except
clause.
This TypeError propagates up through `_take` to `ensure_checkpoint`,
where the broad `except Exception` safety net swallows it. The effect
is that `ensure_checkpoint` silently returns False for the entire
session — all checkpoints are skipped for the affected working directory
without any user-visible error.
Root cause
==========
Missing `isinstance(meta, dict)` guard after `json.loads`, identical in
pattern to bugs fixed in `cron/jobs.py` (NousResearch#22569) and
`tools/process_registry.py` (NousResearch#22544). The same guard is already
present one function below in `_list_projects` (line 506), but was
inadvertently omitted in `_touch_project`.
Fix
===
Add two lines after the try/except:
```python
if not isinstance(meta, dict):
meta = {}
```
This matches the existing guard in `_list_projects` and ensures a fresh
empty dict is used whenever the persisted value is not a mapping —
preserving the `created_at` semantics via `setdefault` on the next line.
Tests
=====
`TestTouchProjectMalformedMeta` covers four non-dict root values
(`[]`, `null`, `42`, `"oops"`). Each writes a corrupted metadata file,
calls `_touch_project`, and asserts: (a) no exception raised, (b) the
metadata file is rewritten as a valid dict containing `last_touch` and
`workdir`. All four fail on main with `TypeError`, pass with fix.
Full `tests/tools/test_checkpoint_manager.py` regression: 77 passed.
Contributor
There was a problem hiding this comment.
Pull request overview
This PR hardens tools.checkpoint_manager._touch_project against corrupted-but-JSON-valid project metadata by ensuring the parsed metadata is a dict before performing key assignments, preventing a TypeError that could silently disable checkpointing for a session.
Changes:
- Add a post-
json.loadsshape guard in_touch_projectto coerce non-dict payloads to{}. - Add a regression test suite covering several non-dict JSON payloads and asserting
_touch_projectrepairs the metadata file.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
tools/checkpoint_manager.py |
Adds isinstance(meta, dict) guard to prevent TypeError when metadata JSON root is not an object. |
tests/tools/test_checkpoint_manager.py |
Adds parametrized regression tests for malformed metadata shapes to ensure _touch_project does not raise and rewrites valid metadata. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Comment on lines
+616
to
+622
| When ``json.load`` succeeds but returns a non-dict (e.g. a list ``[]``, | ||
| ``null``, or a scalar), the subsequent ``meta["workdir"] = ...`` raises | ||
| ``TypeError: list indices must be integers…``. This TypeError propagates | ||
| uncaught out of ``_touch_project`` and up through ``_take`` into | ||
| ``ensure_checkpoint``, where it is swallowed by the broad ``except | ||
| Exception`` safety net — but the effect is that the checkpoint is silently | ||
| skipped for the entire session. |
Contributor
|
Merged via salvage PR #22848. salvage cherry-picked your commit; authorship preserved. Thanks for the contribution! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
tools.checkpoint_manager._touch_projectparses the project metadata file withjson.loads, then immediately subscript-assigns into the result:When the file parses successfully but returns a non-dict (
[],null,42, etc. — from a corrupted or truncated write),json.loadsdoes not raise, theexcept (OSError, ValueError)clause is skipped, andmeta["workdir"] = ...raisesTypeError: list indices must be integers or slices, not str.This
TypeErroris not caught in_touch_projector_take. It propagates toensure_checkpoint's broadexcept Exceptionsafety net, which silently returnsFalse— disabling all checkpoints for the affected working directory for the entire session, with no user-visible error.Root cause
Missing
isinstance(meta, dict)guard afterjson.loads. The same guard is already present in_list_projects(line 506 of the same file) but was omitted in_touch_project. Same pattern as fixes incron/jobs.py(#22569) andtools/process_registry.py(#22544).Fix
try: meta = json.loads(meta_path.read_text(encoding="utf-8")) except (OSError, ValueError): meta = {} + if not isinstance(meta, dict): + meta = {} meta["workdir"] = str(_normalize_path(working_dir))Two lines, matching the existing guard in
_list_projects.Tests
TestTouchProjectMalformedMetacovers four non-dict payloads ([],null,42,"oops"):<store>/projects/<hash>.json_touch_project— asserts no exception raisedlast_touchandworkdirpresentAll four cases fail on
mainwithTypeError, pass with the fix. Fulltests/tools/test_checkpoint_manager.pyregression: 77 passed.