GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — cel-python/cel_expr_python/cel_parallel_test.py at main · yarikoptic/cel-python Expand file tree/ Copy pathcel_parallel_test.pyMore file actions 276 lines (233 loc) · 9.05 KB / Copy pathcel_parallel_test.pyFile metadata and controls276 lines (233 loc) · 9.05 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 # Copyright 2026 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Multi-threaded tests for cel-python.""" import collections.abc import concurrent.futures import dataclasses import gc import logging import time from typing import Any from absl.testing import absltest from cel_expr_python import cel from cel.expr.conformance.proto2 import test_all_types_pb2 as test_all_types_pb @dataclasses.dataclass(frozen=True) class _TestCase: expr: str data: collections.abc.Callable[[int], dict[str, Any]] expected: collections.abc.Callable[[int], Any] _NUM_EVALUATIONS = 10000 _NUM_COMPILATIONS = 1000 _TEST_MSG = test_all_types_pb.TestAllTypes(single_int64=100) _TEST_CASES = [ _TestCase( expr="var_int * var_int", data=lambda n: {"var_int": n}, expected=lambda n: n * n, ), _TestCase( expr="var_str + '_' + string(var_int)", data=lambda n: {"var_str": "num", "var_int": n}, expected=lambda n: f"num_{n}", ), _TestCase( expr="var_int % 2 == 0", data=lambda n: {"var_int": n}, expected=lambda n: n % 2 == 0, ), _TestCase( expr="[var_int, var_int + 1, var_int + 2]", data=lambda n: {"var_int": n}, expected=lambda n: [n, n + 1, n + 2], ), _TestCase( expr="var_int_map[var_int]", data=lambda n: {"var_int_map": {n: f"val_{n}"}, "var_int": n}, expected=lambda n: f"val_{n}", ), _TestCase( expr="var_msg.single_int64 + var_int", data=lambda n: {"var_msg": _TEST_MSG, "var_int": n}, expected=lambda n: 100 + n, ), _TestCase( expr=( "cel.expr.conformance.proto2.TestAllTypes{" " single_int64: var_int, single_string: var_str" "}" ), data=lambda n: {"var_int": n, "var_str": f"msg_{n}"}, expected=lambda n: test_all_types_pb.TestAllTypes( single_int64=n, single_string=f"msg_{n}" ), ), _TestCase( expr="{'key': var_str, 'value': var_int}", data=lambda n: {"var_str": f"val_{n}", "var_int": n}, expected=lambda n: {"key": f"val_{n}", "value": n}, ), _TestCase( expr="[var_int, var_int + 1, var_int + 2].all(x, x >= var_int)", data=lambda n: {"var_int": n}, expected=lambda n: True, ), ] class CelParallelTest(absltest.TestCase): def setUp(self): super().setUp() self.env = cel.NewEnv( variables={ "var_int": cel.Type.INT, "var_str": cel.Type.STRING, "var_int_map": cel.Type.Map(cel.Type.INT, cel.Type.STRING), "var_msg": cel.Type("cel.expr.conformance.proto2.TestAllTypes"), }, functions=[ cel.FunctionDecl( "custom_fn", [ cel.Overload( "custom_fn_int", return_type=cel.Type.INT, parameters=[cel.Type.INT], ) ], ) ], ) self.object_counts_before_test = self._grab_object_counts() def tearDown(self): """Tears down the test environment.""" super().tearDown() gc.collect() # Assert that all Arenas have been garbage-collected self.assertEqual(cel._InternalArena._get_instance_count(), 0) self._check_for_leaks() def _grab_object_counts(self) -> dict[str, int]: gc.collect() all_objects = gc.get_objects() type_counts = {} for obj in all_objects: obj_type = type(obj) type_counts[obj_type.__name__] = type_counts.get(obj_type, 0) + 1 return type_counts def _check_for_leaks(self): type_counts = self._grab_object_counts() for key, count in type_counts.items(): if count != self.object_counts_before_test.get(key, 0): self.fail( f"Object count for {key} did not match expected count. " f"Expected: {self.object_counts_before_test.get(key, 0)}, " f"Actual: {count}", ) def _test_eval(self, multi_threaded: bool): compiled_exprs = [self.env.compile(tc.expr) for tc in _TEST_CASES] def eval_expr(n: int) -> Any: idx = n % len(_TEST_CASES) test_case = _TEST_CASES[idx] expr = compiled_exprs[idx] data = test_case.data(n) return expr.eval(data=data).plain_value() start_time = time.perf_counter() if multi_threaded: with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor: results = list(executor.map(eval_expr, range(_NUM_EVALUATIONS))) else: results = [eval_expr(n) for n in range(_NUM_EVALUATIONS)] duration_ms = (time.perf_counter() - start_time) * 1000 mode = "Multi-threaded" if multi_threaded else "Sequential" logging.info("%s evaluation duration: %.2f ms", mode, duration_ms) self.assertLen(results, _NUM_EVALUATIONS) for i, res in enumerate(results): test_case = _TEST_CASES[i % len(_TEST_CASES)] self.assertEqual(res, test_case.expected(i)) def testMultiThreadedEval(self): self._test_eval(multi_threaded=True) def testSequentialEval(self): self._test_eval(multi_threaded=False) def _test_compile(self, multi_threaded: bool): def compile_and_eval(n: int) -> Any: test_case = _TEST_CASES[n % len(_TEST_CASES)] expr = self.env.compile(test_case.expr) data = test_case.data(n) return expr.eval(data=data).plain_value() start_time = time.perf_counter() if multi_threaded: with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor: results = list(executor.map(compile_and_eval, range(_NUM_COMPILATIONS))) else: results = [compile_and_eval(n) for n in range(_NUM_COMPILATIONS)] duration_ms = (time.perf_counter() - start_time) * 1000 mode = "Multi-threaded" if multi_threaded else "Sequential" logging.info("%s compilation duration: %.2f ms", mode, duration_ms) self.assertLen(results, _NUM_COMPILATIONS) for i, res in enumerate(results): test_case = _TEST_CASES[i % len(_TEST_CASES)] self.assertEqual(res, test_case.expected(i)) def testMultiThreadedCompilation(self): self._test_compile(multi_threaded=True) def testSequentialCompilation(self): self._test_compile(multi_threaded=False) def testSharedValueConcurrentAccess(self): expr_scalar = self.env.compile("var_int * 2") expr_list = self.env.compile("[var_int, var_int + 1, var_int + 2]") expr_map = self.env.compile("{'key': var_str, 'value': var_int}") def run_concurrent_value_test(n: int): val_scalar = expr_scalar.eval(data={"var_int": n}) val_list = expr_list.eval(data={"var_int": n}) val_map = expr_map.eval(data={"var_str": f"k_{n}", "var_int": n}) def read_values(_): # Concurrently access plain_value, value, type, and repr # on shared instances self.assertEqual(val_scalar.plain_value(), n * 2) self.assertEqual(val_scalar.value(), n * 2) self.assertEqual(val_scalar.type(), cel.Type.INT) self.assertNotEmpty(str(val_scalar)) plain_list = val_list.plain_value() self.assertEqual(plain_list, [n, n + 1, n + 2]) list_accessors = val_list.value() for idx, item in enumerate(list_accessors): self.assertEqual(item.plain_value(), n + idx) self.assertEqual(item.value(), n + idx) self.assertEqual(item.type(), cel.Type.INT) self.assertNotEmpty(str(item)) plain_map = val_map.plain_value() self.assertEqual(plain_map, {"key": f"k_{n}", "value": n}) map_accessors = val_map.value() self.assertEqual(map_accessors["key"].plain_value(), f"k_{n}") self.assertEqual(map_accessors["key"].value(), f"k_{n}") self.assertEqual(map_accessors["value"].plain_value(), n) self.assertEqual(map_accessors["value"].value(), n) with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor: list(executor.map(read_values, range(50))) for i in range(10): run_concurrent_value_test(i) def testConcurrentCustomFunction(self): expr = self.env.compile("custom_fn(var_int)") def eval_custom_fn(n: int): fn = cel.Function( "custom_fn", [cel.Type.INT], False, lambda x: x * 2, return_type=cel.Type.INT, ) act = self.env.Activation({"var_int": n}, functions=[fn]) res = expr.eval(act) self.assertEqual(res.value(), n * 2) with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor: results = list(executor.map(eval_custom_fn, range(100))) self.assertLen(results, 100) if __name__ == "__main__": absltest.main() |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |