Skip to content
Merged
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
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,22 @@

All notable changes to this project will be documented in this file.

## 0.4.5

### Fixed

- Serialization output is now deterministic: serializing the same tree gives the
same result in every process. Before, both the order of the nodes
(`serialize_tree_to_json_element`, protobuf `serialize_tree`) and the order of the
properties within a node depended on Python's hash randomization. Nodes are now
serialized in tree order.

### Changed

- `Classifier.all_ancestors()` returns a `list` instead of a `set`, in a
deterministic order: breadth-first, following the direct ancestors in declaration
order.

## 0.4.4

### Fixed
Expand Down
24 changes: 15 additions & 9 deletions src/lionweb/language/classifier.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from abc import abstractmethod
from collections import deque
from typing import Optional, TypeVar

from lionweb.language.language_entity import LanguageEntity
Expand Down Expand Up @@ -50,19 +51,24 @@ def direct_ancestors(self) -> list["Classifier"]:
"""Return the classifiers this classifier directly extends or implements."""
pass

def all_ancestors(self) -> set["Classifier"]:
def all_ancestors(self) -> list["Classifier"]:
"""Compute the transitive closure of all ancestor classifiers.

The order is deterministic: breadth-first, following ``direct_ancestors``
in declaration order, with each ancestor listed once.

Returns:
set[Classifier]: All ancestors reachable through ``direct_ancestors``.
list[Classifier]: All ancestors reachable through ``direct_ancestors``.
"""
result = set()
ancestors = set(self.direct_ancestors())
while ancestors:
ancestor = ancestors.pop()
if ancestor not in result:
result.add(ancestor)
ancestors.update(ancestor.direct_ancestors())
result: list[Classifier] = []
seen: set[Classifier] = set()
to_visit = deque(self.direct_ancestors())
while to_visit:
ancestor = to_visit.popleft()
if ancestor not in seen:
seen.add(ancestor)
result.append(ancestor)
to_visit.extend(ancestor.direct_ancestors())
return result

def all_features(self) -> list[Feature]:
Expand Down
2 changes: 1 addition & 1 deletion src/lionweb/serialization/json_serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def serialize_tree_to_json_element(
if isinstance(classifier_instance, ProxyNode):
raise ValueError("Proxy nodes cannot be serialized")

classifier_instances = set[ClassifierInstance]()
classifier_instances: list[ClassifierInstance] = []
ClassifierInstance.collect_self_and_descendants(
classifier_instance, True, classifier_instances
)
Expand Down
2 changes: 1 addition & 1 deletion src/lionweb/serialization/protobuf_serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ def serialize_node(self, n: "SerializedClassifierInstance") -> PBNode:
def serialize_tree(self, classifier_instance: ClassifierInstance) -> PBChunk:
if isinstance(classifier_instance, ProxyNode):
raise ValueError("Proxy nodes cannot be serialized")
classifier_instances: set[ClassifierInstance] = set()
classifier_instances: list[ClassifierInstance] = []
ClassifierInstance.collect_self_and_descendants(
classifier_instance, True, classifier_instances
)
Expand Down
14 changes: 11 additions & 3 deletions tests/language/test_classifier_ancestors.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ def test_concept(self):
k.add_extended_interface(myInterf)

self.assertEqual(set([b, i, j]), set(a.direct_ancestors()))
self.assertEqual(set([b, i, j, k, myInterf]), set(a.all_ancestors()))
# myInterf is reachable both through b and through i -> k: it is listed once.
# Order: breadth-first, direct ancestors in declaration order.
self.assertEqual([b, i, j, myInterf, k], a.all_ancestors())

def test_annotation(self):
a = Annotation()
Expand All @@ -42,7 +44,9 @@ def test_annotation(self):
k.add_extended_interface(myInterf)

self.assertEqual(set([b, i, j]), set(a.direct_ancestors()))
self.assertEqual(set([b, i, j, k, myInterf]), set(a.all_ancestors()))
# myInterf is reachable both through b and through i -> k: it is listed once.
# Order: breadth-first, direct ancestors in declaration order.
self.assertEqual([b, i, j, myInterf, k], a.all_ancestors())

def test_iface(self):
i = Interface(name="i")
Expand All @@ -53,4 +57,8 @@ def test_iface(self):
i.add_extended_interface(j)
i.add_extended_interface(k)
k.add_extended_interface(myInterf)
k
j.add_extended_interface(myInterf)

self.assertEqual([j, k], i.direct_ancestors())
# myInterf is reachable both through j and through k: it is listed once.
self.assertEqual([j, k, myInterf], i.all_ancestors())
54 changes: 54 additions & 0 deletions tests/serialization/test_deterministic_serialization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import os
import subprocess
import sys
import unittest

SRC_DIR = os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "src"
)

# Serializes the LionCore language (a tree with many nodes) in both formats
SERIALIZE_TREE = """
import sys
from lionweb.self.lioncore import LionCore
from lionweb.serialization import (
create_standard_json_serialization,
create_standard_protobuf_serialization,
)

language = LionCore.get_language()
sys.stdout.write(create_standard_json_serialization().serialize_tree_to_json_string(language))
sys.stdout.write("\\n")
chunk = create_standard_protobuf_serialization().serialize_tree(language)
sys.stdout.write(chunk.SerializeToString(deterministic=True).hex())
"""


class DeterministicSerializationTest(unittest.TestCase):
"""Serializing the same tree must give the same output in every process.

The order of the nodes used to depend on Python's hash randomization, so it
changed from run to run: each serialization runs in a fresh interpreter with a
different PYTHONHASHSEED.
"""

def _serialize_with_hash_seed(self, seed: str) -> str:
env = dict(os.environ)
env["PYTHONPATH"] = os.pathsep.join(filter(None, [SRC_DIR, env.get("PYTHONPATH")]))
env["PYTHONHASHSEED"] = seed
result = subprocess.run(
[sys.executable, "-c", SERIALIZE_TREE],
env=env,
capture_output=True,
text=True,
)
self.assertEqual(result.returncode, 0, result.stderr)
return result.stdout

def test_serialize_tree_output_does_not_depend_on_hash_seed(self):
outputs = {self._serialize_with_hash_seed(seed) for seed in ["1", "2", "3"]}
self.assertEqual(len(outputs), 1)


if __name__ == "__main__":
unittest.main()
Loading