Python: fix(core): persist compaction annotations in file-backed history #10359
Under umask 022, rewriting a transcript restricted to 0600 creates a 0644 staging file and replaces the history with it, exposing the conversation to other local users where directory access permits. Create staging files restrictively before writing and preserve the original file's access restrictions when replacing it. The JSON replacement at _sessions.py:2840–2841 has the same issue.
Python dictionary equality is not type-sensitive: a stored property with value 1 compares equal to an incoming value of True. Replaying an ID-matched message with that change therefore returns no update, and the next load still returns the integer even though JSON and MessagePack distinguish these payloads. Use a type-sensitive payload comparison and add a regression for a type-only update.
A literal-safe 240-character session ID produces a valid 248-character MessagePack filename, but the staging name grows to 286 characters and annotation updates fail with ENAMETOOLONG on filesystems with a 255-byte component limit. Use a short fixed prefix plus the UUID so updates work for histories the append path can create. The JSON temporary name at _sessions.py:2838 has the same issue.
<!-- ccr-overview-v2 -->
🟡 Changes recommended
Transcript rewrites can expose restricted conversation files through permissive staging-file permissions, while long session IDs and type-only property changes also cause annotation updates to fail or be silently skipped.
<details open>
<summary><strong>3 open issues</strong></summary>
</details>
<details>
<summary><strong>What changed in this PR</strong></summary>
This PR updates Python’s FileHistoryProvider to persist changed payloads, including compaction annotations, when a save replays the full stored transcript. It leaves compaction-provider integration outside this change.
Changes:
| File | Description |
| ---- | ----------- |
| python/packages/core/tests/core/test_sessions.py | Adds persistence and replay regression tests for both formats. |
| python/packages/core/AGENTS.md | Documents rewrite behavior and partial-replay limits. |
| python/packages/core/agent_framework/_sessions.py | Detects changed stored payloads and atomically replaces history files. |
</details>
<sub>Review effort: Balanced</sub>
Reproduced under umask 022: a history chmod'd to 0600 came back 0644 after the rewrite (assert 420 == 384).
Fixed in 326a1a528. Both formats now share _staging_history_file, which reads the history's access bits, creates the staging file with os.open(..., O_WRONLY | O_CREAT | O_EXCL, mode), and re-applies the mode with os.chmod after writing, since os.open masks it with the umask. A history that does not exist yet gets 0600. The probe now reports before 0o600 / after 0o600 under umask 022, and a regression pins it for both formats.
Confirmed: a property changed from 1 to True was skipped, and the next load still returned int.
Fixed in 326a1a528 with _same_stored_payload, which requires type(left) is type(right) at every level and recurses through mappings and lists instead of relying on ==. The probe now returns True / bool, and a type-only regression covers both formats.
Confirmed on APFS: a 240-character literal-safe session ID produces a 246-byte .jsonl / 248-byte .msgpack name that the append path accepts, and the rewrite failed with OSError errno=63.
Fixed in 326a1a528: the staging name is now .history-<uuid4 hex>.tmp, independent of the history filename. Both formats rewrite that session successfully, and the regression also asserts no .history-*.tmp is left behind.
All three reproduced locally on 811ac09ac before changing anything, then fixed in 326a1a528.
Restricted transcripts. With umask 022, a history chmod'd to 0600 came back 0644 after the rewrite (assert 420 == 384). Both formats now share one staging helper: it reads the history's access bits, creates the staging file with os.open(..., O_WRONLY | O_CREAT | O_EXCL, mode), and re-applies the mode with os.chmod after writing because os.open masks it with the umask. A history that does not exist yet gets 0600. Probe after the fix: before 0o600 / after 0o600 under umask 022.
Type-only payload changes. Confirmed: a property changed from 1 to True was skipped and the next load still returned int. Comparison now walks the serialized payload and requires type(left) is type(right) at every level, recursing through mappings and lists. Probe after the fix returns True / bool.
Staging filename length. Confirmed on APFS: a 240-character literal-safe session ID yields a 246-byte .jsonl / 248-byte .msgpack name that the append path accepts, and the rewrite failed with OSError errno=63. The staging name is now .history-<uuid4 hex>.tmp, independent of the history filename. Both formats now rewrite that session successfully, and the test also asserts no .history-*.tmp is left behind.
Six new regressions, both formats. Red check with the previous _sessions.py and these tests unchanged: 6 failed, with exactly the three symptoms above (assert 420 == 384, assert 1 is True, Errno 63 File name too long). After the fix, full packages/core/tests non-integration: 9848 tests, 0 failures, 0 errors, 25 skipped.
I also checked the failure path explicitly for both formats: forcing an encode rejection leaves the history byte-identical and removes the staging file. Ruff 0.17.4 check and format pass; Pyright 1.1.414 over 107 core files reports only the two pre-existing _skills.py PyYAML findings.
Verified the core of this change and the surrounding machinery rather than just the new tests:
msgspec's Encoder.encode_into overwrites the buffer from position 0 (verified locally — encoding {'a': 1} then {'b': 2} into the same bytearray leaves only the second record, length 4), so _rewrite_msgpack_messages writing len(record) + record per message is correct, matching the existing append path._updated_stored_messages correctly requires the incoming prefix to cover the whole stored transcript (stored_count == len(existing)), so the partial-replay test's "no rewrite of records it did not carry" holds.Two questions:
1. The rewrite decision compares message.to_dict() of the incoming messages against the stored ones. Is to_dict() stable across reconstructions of the same run — i.e. does it carry any volatile field (generated id, timestamp) that would differ on a fresh reconstruction and force a full rewrite on every save even when nothing meaningful changed? The "skips rewrite when nothing changed" test replays the same objects, so it would not catch a volatile field.
2. The JSON rewrite materializes the whole merged transcript into one string before writing, while the msgpack rewrite streams record by record. For very large transcripts that is a full in-memory copy plus the staging file; is that accepted (the JSON read path already loads the whole file), or worth streaming line by line like the append path does?
Non-blocking: the change is well tested across both formats, including the type-only (1 vs True) payload case.
nan never equals itself, so once any stored message carries a NaN in additional_properties (a score, a usage metric) every replay counts it as changed and rewrites the whole file on each save. checked both json and msgpack, the inode changes on an identical replay
if isinstance(left, float) and math.isnan(left):
return math.isnan(right)
return bool(left == right)
fixed this plus a test in this commit, you can just cherry pick it instead of redoing it: https://github.com/its-amann/agent-framework/commit/829fa566026feb90e301e0ab2de31be6cc119f37
Thanks. Cherry-picked as ce986772184cd97e53b23b5ac416d540233d41f7, preserving the original commit and authorship.
Validation on that head:
test_sessions.py: 214 passed._sessions.py: 0 errors.The tests used Python 3.14.5, pytest 9.2.0, msgspec 0.22.0 and pydantic 2.14.1 in an existing non-iCloud environment, with agent_framework imported from this branch.
Thanks for checking both the reconstruction and memory cases.
1. to_dict() does not add a wall-clock timestamp during serialization. Any message_id already present is part of the stored payload and is reused by get_messages, rather than regenerated during reconstruction. I added test_reconstructed_replay_does_not_rewrite for both JSON and MessagePack. It saves messages, reconstructs fresh objects from disk, saves those objects, and asserts that the history inode is unchanged. This covers the case that replaying the same Python objects could miss.
2. JSON now writes one serialized record at a time into the staging file in 2a92d8c4f, instead of joining the full transcript into another string. A write-level regression expects separate b'"one"\n', b'"two"\n, and b'"three"\n writes. Allocation is therefore per message rather than an additional full-transcript string.
I also merged current main; the pushed head is f5403d367f6b14f4dc893e4dce523a07d3b7a946. On that merged head, the full test_sessions.py is 217 passed, Ruff check and format pass, and Pyright 1.1.414 reports 0 errors for both changed Python files.
he-yufeng
Motivation & Context
FileHistoryProvider.save_messagesappends only the messagesfilter_new_messagesreports as unseen. Compaction excludes stored messages by annotating them in place (set_excludedwritesadditional_properties), so the next save carries the same transcript with changed payloads on records that are already on disk — and writes nothing. The exclusion never reaches the file.InMemoryHistoryProviderkeepsMessageobjects insession.state, so the identical annotation is durable there. With a file-backed transcript the result is thatskip_excluded=Truekeeps returning the full history and the context grows every turn.Reproduced on
mainwith a local fake chat client, six turns,SlidingWindowStrategy(keep_last_groups=2):| history provider | model-call message counts | stored | persisted
_excluded| loaded next turn || --- | --- | --- | --- | --- |
|
InMemoryHistoryProvider| 1, 3, 5, 5, 5, 5 | 12 | 8 | 4 ||
FileHistoryProvider| 1, 3, 5, 7, 9, 11 | 12 | 0 | 12 |Description & Review Guide
save_messagescompares payloads as serialized dicts and rewrites the changed records together with the new tail. Both formats replace the file atomically through a sibling temporary file andos.replace, matching whatFileSessionStorealready does. MessagePack records are encoded into the staging file, so a record the reader would reject never reaches the history and the previous file stays byte-identical.skip_excludedbehaves the same as with the in-memory provider. The append path is unchanged for the ordinary case: a save with only new messages still appends, and an unchanged replay leaves the file byte-identical with no write and no mtime change. A shorter suffix replay still only appends, so a partial replay never rewrites records it did not carry._updated_stored_messages: it requireslen(incoming) - len(new_messages) == len(existing), which is deliberately narrower than "any matched suffix". That keeps the rewrite confined to transcripts the caller actually carried in full, at the cost of not updating annotations when a caller replays only a suffix. Also worth a look: the rewrite holds the same per-file thread and async locks as the append path, so concurrent writers keep the existing serialization.This does not change
CompactionProvider. Itsafter_runreadssession.state[history_source_id]["messages"], which file-backed and vector-backed providers leave empty; making compaction reach those providers is a separate design question and is not attempted here. This change fixes the persistence contract of the provider itself: a save that carries updated stored messages persists them.Related Issue
N/A - no existing issue covers this. I searched
FileHistoryProviderandskip_excludedacross issues and PRs; #8546 is about the in-memory provider storing by reference under per-service-call persistence, which is the opposite direction, and no open PR touchesFileHistoryProvider. I can open an issue for the provider-side contract if you prefer that ordering.AI Assistance
AI assistance details: implementation, tests, documentation, and this PR description. I reviewed the final diff line by line and ran the suites reported below.
Contribution Checklist
<details>
<summary>Local results on <code>811ac09ac</code></summary>
Python 3.14.2,
agent_frameworkresolving to this checkout.packages/core/tests, non-integration: 9842 tests, 0 failures, 0 errors, 25 skipped (JUnit retained)._sessions.pyrestored tomainand the new tests unchanged, 4 failed / 202 passed, failing onKeyError: '_excluded'. Restoring the fix returns the suite to green.jsonandmsgpack: annotations reach disk; unchanged replay leaves bytes and mtime untouched; an updated record keeps its position while later messages append; content-identified repeats stay separate records; a rejected batch restores the previous file including the pending annotation; a partial suffix replay appends without rewriting earlier records.git diff --check: clean.composeunknown-type findings in_skills.py._sessions.pyhas no diagnostics. This is not a clean full-core typing result.</details>