Title: gh-129724: Intern string constants in the compiler, not per code object by gpshead · Pull Request #159193 · python/cpython · GitHub
Open Graph Title: gh-129724: Intern string constants in the compiler, not per code object by gpshead · Pull Request #159193 · python/cpython
X Title: gh-129724: Intern string constants in the compiler, not per code object by gpshead · Pull Request #159193 · python/cpython
Description: Compiling the same source could give code objects whose constants are shared differently, depending on which strings happened to be interned in the process. marshal then writes different bytes, so .pyc files were not reproducible (gh-129724).
Example
Two functions use an equal set constant. The compiler makes it one frozenset object, unless a string in it is already interned when the code objects are created:
1. fresh interpreter len(marshal.dumps(code))=398 f and g share one frozenset: True
2. same again len(marshal.dumps(code))=398 f and g share one frozenset: True
3. while another code object using the
same strings is alive len(marshal.dumps(code))=408 f and g share one frozenset: False
4. after that code object is freed len(marshal.dumps(code))=398 f and g share one frozenset: True
With this PR all four are 398 bytes with one shared frozenset. The same happened to the __qualname__ constant of a class body: compiling class A: class B: pass twice while the first result is alive gives different bytes on main.
Cause and fix
The compiler merges equal constants of a module through its constant cache. Interning then ran later, once per code object, in intern_constants(). A frozenset cannot be modified, so when one of its strings had to be replaced by an already interned string, that code object got a private copy.
flowchart TB
subgraph before["main"]
direction TB
m1["compiler constant cache
one frozenset F for f and g"] --> m2["code object f
intern_constants()"]
m1 --> m3["code object g
intern_constants()"]
m2 -- "a string of F is
already interned" --> m4["F' = copy of F
with the interned string"]
m3 -- "same" --> m5["F'' = another copy"]
m4 --> m6["f and g no longer share:
marshal writes the set twice"]
m5 --> m6
end
subgraph after["this PR"]
direction TB
n1["compiler constant cache
one frozenset F for f and g"] --> n2["intern_final_constants()
when f is assembled"]
n2 -- "a string of F is
already interned" --> n3["F' built once and
stored in the cache entry of F"]
n3 --> n4["g is assembled:
the cache gives F'"]
n4 --> n5["f and g share F'
whatever was interned before"]
n5 --> n6["intern_constants() in
the code object: nothing
left to replace"]
end
Loading
intern_final_constants() runs in optimize_and_assemble_code_unit(), after the optimizer and before the code object is created, on the constants the unit really ends up with. Strings that never reach a code object are not interned.
Tuples are updated in place. A frozenset or slice is rebuilt at most once, and the result is stored in its constant cache entry so later code units get the same object.
The qualified name of a class is interned by the compiler only where it would not be interned as a constant anyway.
intern_constants() in Objects/codeobject.c is not changed; its should_intern_string() is renamed _PyCode_ShouldInternString() and exported so the compiler uses the same rule.
Behaviour changes
Which strings get interned does not change, with one exception: identifier-like strings inside slice constants are now interned on the default build too, as they already were for every other kind of constant.
Compared with main in a fresh process, 13 of 2078 stdlib files compile to different (smaller) bytes: constants that main always copied are now shared.
compile() is about 0.5% slower on the default build (release, not PGO), which is inside the run-to-run noise.
Tests
TestConstantsIdentity in test_compile compiles a table of cases in child processes prepared in different ways (strings pre-interned, used as names, used as constants, the same source already compiled) and compares both the identity graph of the constants and the marshal output with a fresh process. It also covers tuples of names that are the same object as an equal constant (co_names of methods using a mangled name, keyword names, from lists, __static_attributes__), so that a change which re-creates those tuples per code object fails the test (the current version of draft #122180 does this).
With the marshal PR gh-159192 fixing the other half of gh-129724
Compiling each stdlib file under 14 different process conditions (file order, threads, pre-interned strings, earlier imports, hash seeds, keeping code objects alive) and comparing with one file per process:
default (GIL)
free-threaded
main, files differing in the worst condition
433
63
both PRs, plus the fixes for gh-159184, gh-159185, and gh-159188
0
0
The matrix was only run with all of these applied together. The three other fixes do not affect code compiled from source strings, which is all this matrix compiles.
drafted using Claude, reviewed & iterated upon by me.
(combined with the marshal fix, this will close the title issue)
Open Graph Description: Compiling the same source could give code objects whose constants are shared differently, depending on which strings happened to be interned in the process. marshal then writes different bytes, so...
X Description: Compiling the same source could give code objects whose constants are shared differently, depending on which strings happened to be interned in the process. marshal then writes different bytes, so...
Opengraph URL: https://github.com/python/cpython/pull/159193
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:17092440-a15e-34c4-6b39-738952262f49 |
| current-catalog-service-hash | ae870bc5e265a340912cde392f23dad3671a0a881730ffdadd82f2f57d81641b |
| request-id | 8956:2D40DE:3316822:4107084:6B02156D |
| html-safe-nonce | b4d64638eaef53f6ebe239bb7151cbc43780d6333a3238875086149f994829e1 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI4OTU2OjJENDBERTozMzE2ODIyOjQxMDcwODQ6NkIwMjE1NkQiLCJ2aXNpdG9yX2lkIjoiNjA1NDgyMDI1MTcyNjY0ODY4NSIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 364e42af26a36ca9aad7be9810f7164235e740135baf112655c1eb8d922c74cb |
| hovercard-subject-tag | pull_request:4821617854 |
| 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/159193/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 | Compiling the same source could give code objects whose constants are shared differently, depending on which strings happened to be interned in the process. marshal then writes different bytes, so... |
| 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