Skip to content

bpo-34722: Consistent serialization of sets in bytecode #9472

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions Lib/test/test_compileall.py
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,30 @@ def test_workers_available_cores(self, compile_dir):
self.assertTrue(compile_dir.called)
self.assertEqual(compile_dir.call_args[-1]['workers'], None)

def test_deterministic_serialization(self):
# http://bugs.python.org/issue34722
# We have to test this in subprocesses since the nondeterminism
# revolves around the hash seed.
with open(os.path.join(self.pkgdir, 'set.py'), 'w') as f:
f.write("def test(x):\n")
f.write(" if x in {'ONE', 'TWO', 'THREE'}:\n")
f.write(" pass\n")

def compile_dir():
self.assertRunOK(
'-q',
'--invalidation-mode=unchecked-hash',
self.pkgdir,
)
for file in sorted(os.listdir(self.pkgdir_cachedir)):
with open(os.path.join(self.pkgdir_cachedir, file), 'rb') as f:
yield f.read()

serialized = list(compile_dir())
for _ in range(5):
shutil.rmtree(self.pkgdir_cachedir)
self.assertEqual(serialized, list(compile_dir()))


if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Ensures that sets / frozensets marshal in a consistent order by sorting the
serialised items before writing them. This will result in somewhat slower
serialisation but bytecode files using set literals in certain contexts will
now serialise deterministically where it didn't before.
24 changes: 17 additions & 7 deletions Python/marshal.c
Original file line number Diff line number Diff line change
Expand Up @@ -496,7 +496,7 @@ w_complex_object(PyObject *v, char flag, WFILE *p)
w_object((PyObject *)NULL, p);
}
else if (PyAnySet_CheckExact(v)) {
PyObject *value, *it;
PyObject *value, *l;

if (PyObject_TypeCheck(v, &PySet_Type))
W_TYPE(TYPE_SET, p);
Expand All @@ -509,17 +509,27 @@ w_complex_object(PyObject *v, char flag, WFILE *p)
return;
}
W_SIZE(n, p);
it = PyObject_GetIter(v);
if (it == NULL) {
l = PySequence_List(v);
if (l == NULL) {
p->depth--;
p->error = WFERR_UNMARSHALLABLE;
return;
}
while ((value = PyIter_Next(it)) != NULL) {
w_object(value, p);
Py_DECREF(value);
for (i = 0; i < n; i++) {
value = PyList_GetItem(l, i);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the PyList_GetItem() and PyList_SetItem() calls added in this patch should be replaced with the PyList_GET_ITEM() and PyList_SET_ITEM() macros.

Also, PyMarshal_WriteObjectToString() should be checked for failure.

value = PyMarshal_WriteObjectToString(value, Py_MARSHAL_VERSION);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will lost the identity of objects. For example, in {(o, 1), (o, 2)} you will get different objects after marshalling/unmarshalling.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure I can get the same objects back at present?

    def test_object_identity(self):
        o = 'test'
        obj = {(o, 1), (o, 2)}
        data = marshal.dumps(obj)
        v = marshal.loads(data)
        ids_before = {id(x) for x in obj}
        ids_after = {id(x) for x in marshal.loads(data)}
        self.assertEqual(ids_before, ids_after)

AssertionError: Items in the first set but not the second:
139864671036808
139864645838728

Maybe I'm misunderstanding what you mean, or that's not a good test case?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Additional tests were added in #13736. Rebase your PR and make the tests be success.

PyList_SetItem(l, i, value);
}
if (PyList_Sort(l) == -1) {
Py_DECREF(l);
p->depth--;
p->error = WFERR_UNMARSHALLABLE;
return;
}
for (i = 0; i < n; i++) {
w_object(PyList_GetItem(l, i), p);
}
Py_DECREF(it);
Py_DECREF(l);
if (PyErr_Occurred()) {
p->depth--;
p->error = WFERR_UNMARSHALLABLE;
Expand Down