diff --git a/pipeline/fiftyone_pipeline_core/src/fiftyone_pipeline_core/flowdata.py b/pipeline/fiftyone_pipeline_core/src/fiftyone_pipeline_core/flowdata.py index 35b0c5ad..5d433bfe 100644 --- a/pipeline/fiftyone_pipeline_core/src/fiftyone_pipeline_core/flowdata.py +++ b/pipeline/fiftyone_pipeline_core/src/fiftyone_pipeline_core/flowdata.py @@ -25,6 +25,104 @@ from .messages import Messages import traceback import sys +from collections.abc import MutableMapping + + +def _find(node, key): + + # Follows the links from the node given to the first, so newest, node + # for the key. + while node is not None: + if node.key == key: + return node + node = node.next + return None + + +class _ElementDataNode(object): + + """! + One Element Data in a FlowData's list. A node never changes once it is + in the list, so a reader follows the links with no lock. + """ + + __slots__ = ("key", "element_data", "next") + + def __init__(self, key, element_data, next): + self.key = key + self.element_data = element_data + self.next = next + + +class ElementDataView(MutableMapping): + + """! + The Element Data of a FlowData, keyed by data key, as the list was when + the view was taken. Adds made elsewhere after that are not seen, so a + reader part way through always sees a whole list. + + Setting a key adds to the FlowData, and this view then shows the list + as it is after the add. Element Data is not removed, so del, pop, + popitem and clear raise TypeError. copy gives a dict. + + Iteration gives each key once, in the order the keys were first added. + While a Pipeline processes, each Flow Element adds its own in turn, so + that is Pipeline order. Element Data added another way, such as before + processing, is listed by when it was added. + """ + + def __init__(self, flowdata, head): + self._flowdata = flowdata + self._head = head + + def _latest(self): + # The list holds the newest first, so it is sorted into the order + # the keys were added, keeping the newest Element Data for each. + nodes = [] + node = self._head + while node is not None: + nodes.append(node) + node = node.next + latest = {} + for node in reversed(nodes): + latest[node.key] = node.element_data + return latest + + def __getitem__(self, key): + node = _find(self._head, key) + if node is None: + raise KeyError(key) + return node.element_data + + def __setitem__(self, key, element_data): + self._flowdata._add(key, element_data) + # This view now shows the list with the add, as a mapping should. + self._head = self._flowdata._head + + def __delitem__(self, key): + raise TypeError("Element Data is not removed from a FlowData") + + def __iter__(self): + return iter(self._latest()) + + def __len__(self): + return len(self._latest()) + + def __repr__(self): + return repr(self._latest()) + + def copy(self): + return self._latest() + + def keys(self): + return self._latest().keys() + + def values(self): + return self._latest().values() + + def items(self): + return self._latest().items() + class FlowData: """! @@ -33,6 +131,11 @@ class FlowData: It passes evidence to FlowElements in the Pipeline These elements can return ElementData or populate an errors object + The Element Data is kept in a linked list, newest first. An add puts a + new node at the head with a plain write and takes no lock, because no + parallel group adds at the same time. Readers follow the links with no + lock. + A FlowData is not safe to use from several threads at once. It is used by one thread at a time, and where one is shared across threads, the caller is responsible for any locking, for example by wrapping each use @@ -52,7 +155,8 @@ def __init__(self, pipeline): """ - self.data = {} + # The newest node of the Element Data list. See data. + self._head = None self.errors = {} self.pipeline = pipeline self.processed = False @@ -170,12 +274,15 @@ def get(self, flow_element_key): """ try: - return self.data[flow_element_key.lower()] - + node = _find(self._head, flow_element_key.lower()) except Exception: + node = None + if node is None: return self.pipeline.element_not_found(flow_element_key, self) + return node.element_data + def __getattr__(self, flow_element_key): """! @@ -221,7 +328,43 @@ def set_element_data(self, element_data): """ # Kept under the data key in lower case, which is how get reads it. - self.data[element_data.flow_element.datakey.lower()] = element_data + self._add(element_data.flow_element.datakey.lower(), element_data) + + def _add(self, key, element_data): + + # A new node at the head. A reader that has already read the head + # keeps the list it saw. + self._write_head(_ElementDataNode(key, element_data, self._head)) + + def _write_head(self, head): + + # The only write of the list, with a plain write, as no parallel + # group adds at the same time. + self._head = head + + @property + def data(self): + + """! + The Element Data in this FlowData, keyed by data key in lower case, + as the list is now. Iteration gives Pipeline order. + + @rtype: ElementDataView + """ + + return ElementDataView(self, self._head) + + @data.setter + def data(self, contents): + + # Replaces the list with the contents given, in their order. The + # new list is built first and put in place with one write, so a + # reader sees the old list or the new one. The mapping given is + # copied, so later changes to it are not seen. + head = None + for key, element_data in contents.items(): + head = _ElementDataNode(key, element_data, head) + self._write_head(head) def set_error(self, flow_error): diff --git a/pipeline/fiftyone_pipeline_core/tests/test_flowdata_element_data_list.py b/pipeline/fiftyone_pipeline_core/tests/test_flowdata_element_data_list.py new file mode 100644 index 00000000..694a658a --- /dev/null +++ b/pipeline/fiftyone_pipeline_core/tests/test_flowdata_element_data_list.py @@ -0,0 +1,253 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +""" +A Flow Data keeps its Element Data in a linked list, as the thread safety +page of the specification says. An add puts a new node at the head with a +plain write and takes no lock. A node never changes once added, so a reader +that has started sees a whole list, as it was when it read the head. +""" + +import threading +import unittest + +from fiftyone_pipeline_core.basiclist_evidence_keyfilter import \ + BasicListEvidenceKeyFilter +from fiftyone_pipeline_core.elementdata_dictionary import \ + ElementDataDictionary +from fiftyone_pipeline_core.flowelement import FlowElement +from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder + + +class AddsItsData(FlowElement): + """Adds Element Data holding its own name.""" + + def __init__(self, datakey): + super(AddsItsData, self).__init__() + self.datakey = datakey + + def get_evidence_key_filter(self): + return BasicListEvidenceKeyFilter([]) + + def process_internal(self, flowdata): + flowdata.set_element_data( + ElementDataDictionary(self, {"name": self.datakey})) + + +class ReadsWhileItAdds(AddsItsData): + """Starts to list the Element Data already added, adds its own part way + through, then finishes the list, as a reader on another thread would + meet an add.""" + + def process_internal(self, flowdata): + values = flowdata.data.values() + reading = iter(values) + self.first = next(reading) + super(ReadsWhileItAdds, self).process_internal(flowdata) + self.rest = list(reading) + self.taken_before = list(values) + + +def pipeline(*elements): + builder = PipelineBuilder({ + "add_javascript_builder": False, + "use_setheader_properties": False}) + for element in elements: + builder.add(element) + return builder.build() + + +def lock_types(): + return (type(threading.Lock()), type(threading.RLock())) + + +class ElementDataListTests(unittest.TestCase): + + def test_a_reader_part_way_through_is_not_upset_by_an_add(self): + reader = ReadsWhileItAdds("reader") + flowdata = pipeline( + AddsItsData("one"), AddsItsData("two"), reader).create_flowdata() + + flowdata.process() + + names = [reader.first.name] + [data.name for data in reader.rest] + self.assertEqual(["one", "two"], names) + + def test_a_view_taken_before_an_add_keeps_the_list_it_saw(self): + reader = ReadsWhileItAdds("reader") + flowdata = pipeline( + AddsItsData("one"), AddsItsData("two"), reader).create_flowdata() + + flowdata.process() + + self.assertEqual( + ["one", "two"], [data.name for data in reader.taken_before]) + self.assertEqual( + ["one", "two", "reader"], + [data.name for data in flowdata.data.values()]) + + def test_element_data_is_listed_in_pipeline_order(self): + flowdata = pipeline( + AddsItsData("one"), AddsItsData("two"), + AddsItsData("three")).create_flowdata() + + flowdata.process() + + self.assertEqual(["one", "two", "three"], list(flowdata.data)) + + def test_the_newest_add_for_a_key_is_the_one_read(self): + element = AddsItsData("one") + flowdata = pipeline(element).create_flowdata() + first = ElementDataDictionary(element, {"name": "first"}) + second = ElementDataDictionary(element, {"name": "second"}) + + flowdata.set_element_data(first) + flowdata.set_element_data(second) + + self.assertIs(second, flowdata.get("one")) + self.assertEqual(["one"], list(flowdata.data)) + + def test_an_add_takes_no_lock(self): + """A smoke test. It looks only at the FlowData's own attributes, so + a lock kept anywhere else would not be seen.""" + flowdata = pipeline(AddsItsData("one")).create_flowdata() + + flowdata.process() + + held = [name for name, value in vars(flowdata).items() + if isinstance(value, lock_types())] + self.assertEqual([], held) + + def test_a_write_through_a_view_shows_in_that_view(self): + element = AddsItsData("one") + flowdata = pipeline(element).create_flowdata() + view = flowdata.data + first = ElementDataDictionary(element, {"name": "first"}) + second = ElementDataDictionary(element, {"name": "second"}) + third = ElementDataDictionary(element, {"name": "third"}) + + view["first"] = first + view.update({"second": second}) + view.setdefault("third", third) + + self.assertIs(first, view["first"]) + self.assertIs(second, view["second"]) + self.assertIs(third, view["third"]) + self.assertEqual(["first", "second", "third"], list(view)) + self.assertIs(first, flowdata.get("first")) + + def test_a_copy_is_a_dict_of_the_element_data(self): + flowdata = pipeline( + AddsItsData("one"), AddsItsData("two")).create_flowdata() + flowdata.process() + + copy = flowdata.data.copy() + + self.assertIs(dict, type(copy)) + self.assertEqual(["one", "two"], list(copy)) + self.assertIs(flowdata.get("two"), copy["two"]) + + def test_element_data_is_not_removed(self): + flowdata = pipeline( + AddsItsData("one"), AddsItsData("two")).create_flowdata() + flowdata.process() + + def remove(view): + del view["one"] + + for removal in ( + remove, + lambda view: view.pop("one"), + lambda view: view.popitem(), + lambda view: view.clear()): + with self.assertRaises(TypeError): + removal(flowdata.data) + self.assertEqual(["one", "two"], list(flowdata.data)) + + def test_setting_data_copies_the_mapping_given(self): + element = AddsItsData("one") + flowdata = pipeline(element).create_flowdata() + given = {"one": ElementDataDictionary(element, {"name": "one"})} + + flowdata.data = given + given["two"] = ElementDataDictionary(element, {"name": "two"}) + + self.assertEqual(["one"], list(flowdata.data)) + + def test_setting_data_replaces_the_whole_list_at_once(self): + element = AddsItsData("one") + flowdata = pipeline(element).create_flowdata() + flowdata.data = { + "old": ElementDataDictionary(element, {"name": "old"})} + seen = [] + + class Contents(dict): + # Lists the Element Data part way through the replacement, as + # a reader on another thread could. + def items(self): + for key, value in dict.items(self): + yield key, value + seen.append(list(flowdata.data)) + + flowdata.data = Contents({ + "a": ElementDataDictionary(element, {"name": "a"}), + "b": ElementDataDictionary(element, {"name": "b"})}) + + self.assertEqual([["old"], ["old"]], seen) + self.assertEqual(["a", "b"], list(flowdata.data)) + + def test_a_reader_on_another_thread_always_sees_a_whole_list(self): + element = AddsItsData("one") + flowdata = pipeline(element).create_flowdata() + keys = ["key%d" % index for index in range(2000)] + seen = [] + failures = [] + done = threading.Event() + + def read(): + try: + while not done.is_set(): + listed = list(flowdata.data) + # A whole list is every key added so far, in order. + if listed != keys[:len(listed)]: + failures.append(listed) + seen.append(len(listed)) + except Exception as error: + failures.append(error) + + reader = threading.Thread(target=read) + reader.start() + try: + for key in keys: + flowdata.data[key] = ElementDataDictionary( + element, {"name": key}) + finally: + done.set() + reader.join() + + self.assertEqual([], failures) + self.assertTrue(seen) + self.assertEqual(keys, list(flowdata.data)) + + +if __name__ == "__main__": + unittest.main()