Title: gh-129724: gh-156504: Make marshal output independent of reference counts by gpshead · Pull Request #159192 · python/cpython · GitHub
Open Graph Title: gh-129724: gh-156504: Make marshal output independent of reference counts by gpshead · Pull Request #159192 · python/cpython
X Title: gh-129724: gh-156504: Make marshal output independent of reference counts by gpshead · Pull Request #159192 · python/cpython
Description: marshal.dumps() could give different bytes for the same value, because the writer used the reference count of each object to decide whether a later occurrence may refer back to it (FLAG_REF). The count depends on what else in the process holds a reference to the object, and on the free-threaded build on which thread owns it. This is the cause of gh-156504 and one of the two causes of gh-129724 (the other is in the compiler: see the companion PR gh-159193).
FLAG_REF is now set on exactly the objects that are written more than once in the dump.
Example
>>> x = float('1.5')
>>> marshal.dumps([float('1.5')]).hex(' ') # refcount 1
'5b 01 00 00 00 67 00 00 00 00 00 00 f8 3f'
>>> marshal.dumps([x]).hex(' ') # refcount 2: main sets FLAG_REF (0x80)
'5b 01 00 00 00 e7 00 00 00 00 00 00 f8 3f'
With this PR both calls return the first form. Where an object really is written twice, the index of the reference no longer counts objects that were flagged for nothing:
value: [a, b, b] a = 1.5 and b = 2.5, both also referenced from elsewhere
main: [ 3 FLOAT|REF 1.5 FLOAT|REF 2.5 REF #1 ] a is flagged for nothing, so b is #1
this PR: [ 3 FLOAT 1.5 FLOAT|REF 2.5 REF #0 ] only b is flagged, so b is #0
How
The reader numbers the flagged objects in the order it meets them, so the writer cannot know the index of a reference until it knows which earlier objects end up flagged. It still makes a single pass over the objects, and fixes up the output at the end.
flowchart TB
subgraph before["main"]
direction TB
b1["w_ref(obj)"] --> b2{"refcount == 1?"}
b2 -- yes --> b3["write object
no flag"]
b2 -- no --> b4{"seen before?"}
b4 -- no --> b5["write object + FLAG_REF
index = number flagged so far"]
b4 -- yes --> b6["write TYPE_REF index"]
end
subgraph after["this PR"]
direction TB
a1["w_ref(obj)"] --> a2{"refcount == 1?"}
a2 -- yes --> a3["write object
(cannot occur twice)"]
a2 -- no --> a4{"seen before?"}
a4 -- no --> a5["write object, no flag yet
remember offset of its type byte"]
a4 -- yes --> a6["mark object shared
write TYPE_REF + provisional index
remember its position"]
a5 --> a7
a6 --> a7["w_resolve_refs(), once, at the end:
set FLAG_REF on shared objects,
number them, rewrite TYPE_REF indexes"]
end
Loading
A reference count of 1 is still used, but only as a shortcut to skip the hash table: such an object cannot occur twice, so the result is the same without it.
Interned strings are no longer flagged unconditionally.
The reader is unchanged and the format version is not bumped. Old and new readers load old and new output.
PyMarshal_WriteObjectToFile() now builds the data in memory and writes it with one fwrite(), since the flags are only known at the end. Nothing is written if the object cannot be marshalled. Documented in Doc/c-api/marshal.rst.
Compatibility
The bytes of every .pyc change (fewer flags), which is why Programs/test_frozenmain.h is regenerated. marshal.loads() gives the same objects with the same sharing.
The generated pycs can be loaded by prior Python versions, but this kind of change might be considered disruptive for some when considering a backport. Realistically: prior versions are all "broken" by not producing stable output in real world scenarios, so any bug fixes going in that stabilize how things work are going to lead to some newly generated bytecode changing vs what was seen in the past, as already happens between runs compiling the same source file under different process state today.
Related: #159197 is stacked on top of this.
Performance
Release builds, not PGO, compared with main:
default (GIL)
free-threaded
dumps of the code objects of the stdlib
3.7% slower
4.3% slower
dumps dominated by references (millions of TYPE_REF)
5-9% slower
dumps of unshared data (1M distinct floats)
32% faster
loads of the new output
3-5% faster
Writer memory grows by 8 bytes per object with a reference count above 1.
Tests
ReferenceTestCase in test_marshal checks exact bytes: single occurrences are not flagged whatever their reference count, interned strings, references at every buffer offset, objects seen before and after the ones they share with, NaNs in sets. test_capi.test_marshal checks that nothing is written on error.
drafted using Claude, reviewed & iterated upon by me.
Fixes #156504
Open Graph Description: marshal.dumps() could give different bytes for the same value, because the writer used the reference count of each object to decide whether a later occurrence may refer back to it (FLAG_REF). The ...
X Description: marshal.dumps() could give different bytes for the same value, because the writer used the reference count of each object to decide whether a later occurrence may refer back to it (FLAG_REF). The ...
Opengraph URL: https://github.com/python/cpython/pull/159192
X: @github
Domain: github.com
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /:user_id/:repository/pull/:id/files(.:format) |
| route-controller | pull_requests |
| route-action | files |
| fetch-nonce | v2:0e4a13e6-2a4c-aca8-ca99-701fbd4eec90 |
| current-catalog-service-hash | ae870bc5e265a340912cde392f23dad3671a0a881730ffdadd82f2f57d81641b |
| request-id | DB6A:A71F9:32E04B9:4067B55:6B020AED |
| html-safe-nonce | 7d4c4a3e749713e7494919cee7fb1cbebb1a78ca8a07936653504e8e17158e4c |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJEQjZBOkE3MUY5OjMyRTA0Qjk6NDA2N0I1NTo2QjAyMEFFRCIsInZpc2l0b3JfaWQiOiI2MTQ2OTkyODgyNzEzNzU4NDQ1IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | 31f499d034e390bc1ea8bcd5fe9c5a50ae6caafd836d5667172c4f26ab92a1d1 |
| hovercard-subject-tag | pull_request:4821554667 |
| github-keyboard-shortcuts | repository,pull-request-list,pull-request-conversation,pull-request-files-changed,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/python/cpython/pull/159192/files |
| twitter:image | https://avatars.githubusercontent.com/u/68491?s=400&v=4 |
| twitter:card | summary_large_image |
| og:image | https://avatars.githubusercontent.com/u/68491?s=400&v=4 |
| og:image:alt | marshal.dumps() could give different bytes for the same value, because the writer used the reference count of each object to decide whether a later occurrence may refer back to it (FLAG_REF). The ... |
| og:site_name | GitHub |
| og:type | object |
| hostname | github.com |
| expected-hostname | github.com |
| None | 87e774ee7c6b3bee0490394e4d3e57ec9dbc956f74b87ea685dc8996c1676456 |
| turbo-cache-control | no-preview |
| diff-view | unified |
| go-import | github.com/python/cpython git https://github.com/python/cpython.git |
| octolytics-dimension-user_id | 1525981 |
| octolytics-dimension-user_login | python |
| octolytics-dimension-repository_id | 81598961 |
| octolytics-dimension-repository_nwo | python/cpython |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 81598961 |
| octolytics-dimension-repository_network_root_nwo | python/cpython |
| turbo-body-classes | logged-out env-production page-responsive full-width |
| disable-turbo | true |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 423dbb54c5e7bfecc838eb387c1435eb3d0e760d |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
Links:
Viewport: width=device-width