From cae118f3e1960aa146053fa1a31589fa006cc33b Mon Sep 17 00:00:00 2001 From: Rakesh Bakhem Date: Mon, 30 Nov 2026 23:17:37 +0000 Subject: [PATCH] BUG: Refuse a read of pooled element data after its flow data closes Since element data started going back to a pool on close, a reference kept after the flow data closed, for example in Flask g or for logging after the with block, could read the next visitor's results with no error. Before pooling, the same read raised that the results had been closed. Element data given back to a pool is now closed for reading, and the pool hands the next request a copy rather than the same object. So a kept reference raises when read and never sees another request's values, and the pool still saves making new instances. Device detection and IP intelligence give their old results closed message, and the other pooled types raise a new one in core saying the flow data has closed. Tests keep a reference, close, process a second request, and check the old reference raises while the new flow data reads its own values, for the core elements, the engines and both on-premise packages. The core readme now says a read after close raises. --- .../tests/test_element_data_pools.py | 9 ++- .../tests/test_element_data_pools.py | 9 ++- pipeline/fiftyone_pipeline_core/readme.md | 2 +- .../src/fiftyone_pipeline_core/elementdata.py | 33 +++++++-- .../elementdata_dictionary.py | 3 + .../elementdata_pool.py | 16 ++++- .../src/fiftyone_pipeline_core/messages.py | 8 +++ .../tests/test_element_data_pools.py | 67 ++++++++++++++++++- .../tests/test_web_client_side.py | 15 +++-- .../fiftyone_pipeline_engines/aspectdata.py | 3 +- .../tests/test_element_data_pools.py | 7 +- 11 files changed, 155 insertions(+), 17 deletions(-) diff --git a/device-detection/fiftyone_devicedetection_onpremise/tests/test_element_data_pools.py b/device-detection/fiftyone_devicedetection_onpremise/tests/test_element_data_pools.py index f24519f5..79521160 100644 --- a/device-detection/fiftyone_devicedetection_onpremise/tests/test_element_data_pools.py +++ b/device-detection/fiftyone_devicedetection_onpremise/tests/test_element_data_pools.py @@ -32,6 +32,7 @@ from fiftyone_devicedetection_onpremise.devicedetection_onpremise import \ DeviceDetectionOnPremise +from fiftyone_devicedetection_onpremise.constants import RESULTS_CLOSED from fiftyone_devicedetection_onpremise.swig_data import SwigData from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder @@ -82,9 +83,15 @@ def test_a_reused_instance_gives_the_new_request_results(self): first = flowdata.device self.assertTrue(first.ismobile.value()) with self.process(DESKTOP) as flowdata: - self.assertIs(first, flowdata.device) + self.assertIsNot(first, flowdata.device) self.assertFalse(flowdata.device.ismobile.value()) self.assertEqual({}, flowdata.errors) + # The reference kept from the first request raises, as it did + # before the data was pooled, rather than reading this + # request's results. + with self.assertRaises(Exception) as caught: + first.get("ismobile") + self.assertEqual(RESULTS_CLOSED, str(caught.exception)) if __name__ == "__main__": diff --git a/ip-intelligence/fiftyone_ipintelligence_onpremise/tests/test_element_data_pools.py b/ip-intelligence/fiftyone_ipintelligence_onpremise/tests/test_element_data_pools.py index a92441e0..dceaf69c 100644 --- a/ip-intelligence/fiftyone_ipintelligence_onpremise/tests/test_element_data_pools.py +++ b/ip-intelligence/fiftyone_ipintelligence_onpremise/tests/test_element_data_pools.py @@ -32,6 +32,7 @@ from fiftyone_ipintelligence_onpremise.ipintelligence_onpremise import \ IpIntelligenceOnPremise +from fiftyone_ipintelligence_onpremise.constants import RESULTS_CLOSED from fiftyone_ipintelligence_onpremise.swig_data import SwigData from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder @@ -79,7 +80,13 @@ def test_a_reused_instance_has_no_address_from_the_last_request(self): first = flowdata.ip self.assertTrue(first.get("ip").has_value()) with self.process(TestConstants.IPV6_ADDRESS) as flowdata: - self.assertIs(first, flowdata.ip) + self.assertIsNot(first, flowdata.ip) + # The reference kept from the first request raises, as it did + # before the data was pooled, rather than reading this + # request's results. + with self.assertRaises(Exception) as caught: + first.get("ip") + self.assertEqual(RESULTS_CLOSED, str(caught.exception)) self.assertFalse(flowdata.ip.get("ip").has_value()) self.assertEqual(TestConstants.IPV6_ADDRESS, flowdata.ip.get("ipv6").value()) diff --git a/pipeline/fiftyone_pipeline_core/readme.md b/pipeline/fiftyone_pipeline_core/readme.md index e02c1a58..c35c6656 100644 --- a/pipeline/fiftyone_pipeline_core/readme.md +++ b/pipeline/fiftyone_pipeline_core/readme.md @@ -56,7 +56,7 @@ def index(): ## Element data is reused -Some flow elements reuse their element data from one request to the next. When a flow data is closed, by calling `close()` or at the end of a `with` block, its element data goes back to a pool, and a later request may change its values. So read the values you need before the flow data is closed, and don't keep a reference to element data, such as `flowdata.device`, after that. Keeping one isn't supported, and reads aren't checked for it. A value you've already read is unchanged. +Some flow elements reuse their element data from one request to the next. When a flow data is closed, by calling `close()` or at the end of a `with` block, its element data goes back to a pool, and a later request gets a copy of it. So read the values you need before the flow data is closed. A reference to element data, such as `flowdata.device`, that you keep after that raises an exception when you read a property from it, and never gives you another request's values. A value you've already read is unchanged. ## Requirements diff --git a/pipeline/fiftyone_pipeline_core/src/fiftyone_pipeline_core/elementdata.py b/pipeline/fiftyone_pipeline_core/src/fiftyone_pipeline_core/elementdata.py index d5d56481..b2845fa5 100644 --- a/pipeline/fiftyone_pipeline_core/src/fiftyone_pipeline_core/elementdata.py +++ b/pipeline/fiftyone_pipeline_core/src/fiftyone_pipeline_core/elementdata.py @@ -180,10 +180,11 @@ class ElementData(object): directly or by FlowData.close. A FlowElement may take its instances from an ElementDataPool, and - closing the FlowData gives them back for a later request to reuse. So - keeping a reference to ElementData after its FlowData is closed is not - supported, because another request may then change its values. Reads - are not checked for this. + closing the FlowData gives them back for a later request to reuse. An + instance given back is closed for reading, and a later request gets a + copy of it rather than the instance itself. So a reference kept after + the FlowData is closed raises when it is read, and never reads another + request's values. """ @@ -214,6 +215,11 @@ def __init__(self, flow_element): # default, so data whose constructor does not call this one has it too. _finished = False + # Set once the instance has been given back to an ElementDataPool, when + # its FlowData has closed. A read then raises. The pool hands a later + # request a copy, so this instance is never opened again. + _closed_for_reading = False + def __setattr__(self, name, value): """! @@ -258,6 +264,22 @@ def _clear(self): self._finished = False + def _check_readable(self, key): + + """! + Raise if the instance has gone back to its FlowElement's pool, so a + reference kept after its FlowData closed reads nothing. + + @type key: str + @param key: what is being read, for the message + @raise Exception: when the FlowData has been closed + """ + + if self._closed_for_reading: + flow_element = self.__dict__.get("flow_element") + raise Exception(Messages.ELEMENT_DATA_CLOSED.format( + key, getattr(flow_element, "datakey", ""))) + def get(self, key): """! @@ -269,9 +291,12 @@ def get(self, key): @rtype: mixed @return: Returns specified property from the data + @raise Exception: when the FlowData has been closed and the data + has gone back to its FlowElement's pool """ + self._check_readable(key) return self.get_internal(key.lower()) def __getattr__(self, key): diff --git a/pipeline/fiftyone_pipeline_core/src/fiftyone_pipeline_core/elementdata_dictionary.py b/pipeline/fiftyone_pipeline_core/src/fiftyone_pipeline_core/elementdata_dictionary.py index 841e02ea..2b9e18e4 100644 --- a/pipeline/fiftyone_pipeline_core/src/fiftyone_pipeline_core/elementdata_dictionary.py +++ b/pipeline/fiftyone_pipeline_core/src/fiftyone_pipeline_core/elementdata_dictionary.py @@ -74,9 +74,12 @@ def as_dictionary(self): @rtype: dict @return: Returns a dictionary of items in an ElementData + @raise Exception: when the FlowData has been closed and the data + has gone back to its FlowElement's pool """ + self._check_readable("as_dictionary") return self.contents def get_internal(self, key): diff --git a/pipeline/fiftyone_pipeline_core/src/fiftyone_pipeline_core/elementdata_pool.py b/pipeline/fiftyone_pipeline_core/src/fiftyone_pipeline_core/elementdata_pool.py index d5bf1b85..ab6af98e 100644 --- a/pipeline/fiftyone_pipeline_core/src/fiftyone_pipeline_core/elementdata_pool.py +++ b/pipeline/fiftyone_pipeline_core/src/fiftyone_pipeline_core/elementdata_pool.py @@ -40,7 +40,10 @@ class ElementDataPool(object): An instance from the pool has no values and is open for writing, as take() calls its _clear method, which a class with values of its own - overrides to drop them. An instance a cache may hold never goes back, + overrides to drop them. An instance given back is closed for reading, + and take() returns a copy of it, so a reference a caller kept after + closing its FlowData raises when read and never sees a later request's + values. An instance a cache may hold never goes back, because the cache shares it with other requests, and the instances of a FlowData that is not closed are left to the garbage collector. @@ -76,7 +79,13 @@ def take(self): with self._lock: if not self._instances: return None - element_data = self._instances.pop() + given_back = self._instances.pop() + # A copy, made without calling the class, whose __getattr__ reads + # properties. The instance given back stays closed for reading, so + # a reference to it kept after its FlowData closed still raises. + element_data = object.__new__(type(given_back)) + element_data.__dict__.update(given_back.__dict__) + element_data._closed_for_reading = False element_data._clear() return element_data @@ -96,6 +105,9 @@ def give_back(self, element_data): # the cache did not keep. The specification asks for no less. if getattr(element_data.flow_element, "cache", None) is not None: return + # Closed for reading whether or not the pool keeps it, so a read + # after close raises the same way every time. + element_data._closed_for_reading = True with self._lock: if len(self._instances) < self.maximum_instances: self._instances.append(element_data) diff --git a/pipeline/fiftyone_pipeline_core/src/fiftyone_pipeline_core/messages.py b/pipeline/fiftyone_pipeline_core/src/fiftyone_pipeline_core/messages.py index d183e5e3..26a2e15f 100644 --- a/pipeline/fiftyone_pipeline_core/src/fiftyone_pipeline_core/messages.py +++ b/pipeline/fiftyone_pipeline_core/src/fiftyone_pipeline_core/messages.py @@ -61,6 +61,14 @@ class Messages(): "FlowElement that writes it has finished processing. ElementData is " "written only while the FlowElement that provides it processes.") + # A read of ElementData whose FlowData has been closed, once the data + # has gone back to its FlowElement's pool. This takes the key read and + # the element's data key as format arguments. + ELEMENT_DATA_CLOSED = ( + "'{}' cannot be read from the '{}' ElementData, because its " + "FlowData has been closed. Read the values needed before closing " + "the FlowData.") + # The usage sharing element is not the last Flow Element. This takes the # element's class name, its position counting from 1 and the number of # Flow Elements as format arguments. diff --git a/pipeline/fiftyone_pipeline_core/tests/test_element_data_pools.py b/pipeline/fiftyone_pipeline_core/tests/test_element_data_pools.py index 8c848388..a9928a94 100644 --- a/pipeline/fiftyone_pipeline_core/tests/test_element_data_pools.py +++ b/pipeline/fiftyone_pipeline_core/tests/test_element_data_pools.py @@ -200,7 +200,7 @@ def test_a_reused_instance_has_no_values_from_the_last_request(self): first = flowdata.get("pooled") with process(pipeline, "second", 2) as flowdata: second = flowdata.get("pooled") - self.assertIs(first, second) + self.assertIsNot(first, second) self.assertIsNone(second.get("first")) self.assertEqual(2, second.get("second")) self.assertEqual("second", second.last_name) @@ -220,7 +220,7 @@ def test_a_core_element_reuses_its_instance_with_new_values(self): first = flowdata.sequence session = first.get("session-id") with process(pipeline) as flowdata: - self.assertIs(first, flowdata.sequence) + self.assertIsNot(first, flowdata.sequence) self.assertNotEqual(session, flowdata.sequence.get("session-id")) self.assertEqual(1, flowdata.sequence.get("sequence")) @@ -256,6 +256,69 @@ def test_a_flow_data_not_closed_leaves_its_instances_to_the_gc(self): self.assertEqual([], [ref for ref in made if ref() is not None]) +# Each core element that takes its ElementData from a pool, with a property +# its data holds once processed. +CORE_POOLED = [("sequence", "sequence"), ("jsonbundler", "json"), + ("javascriptbuilder", "javascript"), + ("set-headers", "responseheaderdictionary")] + +CLOSED = "has been closed" + + +class ReadAfterCloseTests(unittest.TestCase): + + """A reference to pooled ElementData kept after its FlowData closed + raises when read, and never reads a later request's values, which the + later FlowData reads as its own.""" + + def test_a_kept_reference_raises_once_its_flow_data_has_closed(self): + pipeline = build(PooledElement()) + with process(pipeline, "first", 1) as flowdata: + kept = flowdata.pooled + with self.assertRaises(Exception) as caught: + kept.get("first") + self.assertIn(CLOSED, str(caught.exception)) + + def test_a_kept_reference_never_reads_the_next_request(self): + pipeline = build(PooledElement()) + with process(pipeline, "first", 1) as flowdata: + kept = flowdata.pooled + with process(pipeline, "second", 2) as flowdata: + for read in (lambda: kept.get("second"), + lambda: kept.get("first"), lambda: kept["second"], + lambda: kept.second, kept.as_dictionary): + with self.assertRaises(Exception) as caught: + read() + self.assertIn(CLOSED, str(caught.exception)) + self.assertEqual(2, flowdata.pooled.get("second")) + self.assertIsNone(flowdata.pooled.get("first")) + + def test_each_core_element_refuses_a_read_after_close(self): + pipeline = PipelineBuilder().build() + with process(pipeline, "first", 1) as flowdata: + kept = {key: flowdata.get(key) for key, _ in CORE_POOLED} + with process(pipeline, "second", 2) as flowdata: + for key, name in CORE_POOLED: + with self.subTest(key): + with self.assertRaises(Exception) as caught: + kept[key].get(name) + self.assertIn(CLOSED, str(caught.exception)) + self.assertIsNot(kept[key], flowdata.get(key)) + self.assertIsNotNone(flowdata.get(key).get(name)) + + def test_data_a_full_pool_leaves_behind_still_refuses_reads(self): + pipeline = build(PooledElement(bound=1)) + one = process(pipeline, "one", 1) + two = process(pipeline, "two", 2) + kept = (one.pooled, two.pooled) + one.close() + two.close() + for data in kept: + with self.assertRaises(Exception) as caught: + data.get("one") + self.assertIn(CLOSED, str(caught.exception)) + + class PoolLookupTests(unittest.TestCase): def test_an_element_names_the_pool_it_keeps(self): diff --git a/pipeline/fiftyone_pipeline_core/tests/test_web_client_side.py b/pipeline/fiftyone_pipeline_core/tests/test_web_client_side.py index 19c1164f..81329aa8 100644 --- a/pipeline/fiftyone_pipeline_core/tests/test_web_client_side.py +++ b/pipeline/fiftyone_pipeline_core/tests/test_web_client_side.py @@ -316,8 +316,9 @@ def test_the_json_served_is_the_json_builders_json(self): """The JavaScript Builder specification says the endpoint the script calls back MUST return JSON in the same form as the JSON within the script, which is the JSON Builder's. The flow data the - endpoint processes is kept, so the body can be compared with its - JSON.""" + endpoint processes keeps its JSON as it closes, because its + ElementData can't be read once it has closed, so the body can be + compared with that JSON.""" pipeline = PipelineBuilder({ "javascript_builder_settings": {"endpoint": "/json"}, @@ -327,7 +328,13 @@ def test_the_json_served_is_the_json_builders_json(self): def create_and_keep(): flowdata = create_flowdata() - processed.append(flowdata) + close = flowdata.close + + def keep_and_close(): + processed.append(flowdata.jsonbundler.json) + close() + + flowdata.close = keep_and_close return flowdata app = Flask(__name__) @@ -342,7 +349,7 @@ def json_endpoint(): self.assertEqual(200, response.status_code) self.assertEqual(1, len(processed)) - self.assertEqual(processed[0].jsonbundler.json, response.get_json()) + self.assertEqual(processed[0], response.get_json()) self.assertEqual(42, response.get_json()["switchable"]["answer"]) def test_a_post_with_a_matching_etag_is_refused(self): diff --git a/pipeline/fiftyone_pipeline_engines/src/fiftyone_pipeline_engines/aspectdata.py b/pipeline/fiftyone_pipeline_engines/src/fiftyone_pipeline_engines/aspectdata.py index fa02ff16..6c3d1471 100644 --- a/pipeline/fiftyone_pipeline_engines/src/fiftyone_pipeline_engines/aspectdata.py +++ b/pipeline/fiftyone_pipeline_engines/src/fiftyone_pipeline_engines/aspectdata.py @@ -64,7 +64,8 @@ def get(self, key): restricted properties, saying so, or where the data has no value for it, with the message the missing property service gives """ - + + self._check_readable(key) if hasattr(self.flow_element, "restricted_property_keys"): if key.lower() not in self.flow_element.restricted_property_keys: diff --git a/pipeline/fiftyone_pipeline_engines/tests/test_element_data_pools.py b/pipeline/fiftyone_pipeline_engines/tests/test_element_data_pools.py index d9e17f7c..56d39e4d 100644 --- a/pipeline/fiftyone_pipeline_engines/tests/test_element_data_pools.py +++ b/pipeline/fiftyone_pipeline_engines/tests/test_element_data_pools.py @@ -104,8 +104,13 @@ def test_an_engine_without_a_cache_reuses_its_instance(self): with process(pipeline, "first") as flowdata: first = flowdata.pooled with process(pipeline, "second") as flowdata: - self.assertIs(first, flowdata.pooled) + self.assertIsNot(first, flowdata.pooled) self.assertEqual("second", flowdata.pooled.get("name")) + # The reference kept from the first request refuses reads + # rather than reading the second request's values. + with self.assertRaises(Exception) as caught: + first.get("name") + self.assertIn("has been closed", str(caught.exception)) if __name__ == "__main__":