-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcel_executor.py
More file actions
1626 lines (1485 loc) · 65.5 KB
/
cel_executor.py
File metadata and controls
1626 lines (1485 loc) · 65.5 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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import logging
from collections.abc import Iterable, Iterator
from typing import Any
from odoo import api, models
from odoo.fields import Domain
from odoo.tools.sql import SQL
from ..exceptions import CELMetricsUnavailableError
from .cel_queryplan import (
AND,
NOT,
OR,
AggMetricCompare,
CountThrough,
CoverageRequire,
ExistsThrough,
FieldAggregateThrough,
LeafDomain,
MetricCompare,
flatten_and,
)
from .cel_sql_builder import SQLBuilder
class CelExecutor(models.AbstractModel):
_name = "spp.cel.executor"
_description = "CEL Executor"
_logger = logging.getLogger("odoo.addons.spp_cel_domain")
# -------------------------------------------------------------------------
# Logging Helpers
# -------------------------------------------------------------------------
def _format_domain_for_log(self, domain: list[Any], max_ids: int = 10) -> str:
"""Format domain for logging, truncating large ID lists.
Converts [("id", "in", [1,2,3,...100000])] to readable format:
[("id", "in", [1,2,3,...10] + "...(99990 more)")]
"""
if not domain:
return "[]"
def truncate_value(val: Any) -> Any:
if isinstance(val, SQL):
return "<SQL subquery>"
if isinstance(val, list | tuple) and len(val) > max_ids:
truncated = list(val[:max_ids])
remaining = len(val) - max_ids
return f"{truncated}...({remaining} more)"
return val
def format_term(term: Any) -> str:
if isinstance(term, tuple | list) and len(term) == 3:
field, op, value = term
formatted_val = truncate_value(value)
return f"({field!r}, {op!r}, {formatted_val})"
if isinstance(term, SQL):
return "<SQL subquery>"
return repr(term)
parts = [format_term(t) for t in domain]
return f"[{', '.join(parts)}]"
# -------------------------------------------------------------------------
# SQL Generation for Scale (millions of records)
# -------------------------------------------------------------------------
def _domain_to_id_sql(self, model: str, domain: list[Any]) -> SQL | None:
"""Convert an Odoo domain to a SQL subquery selecting IDs.
Returns SQL object like: SELECT id FROM res_partner WHERE ...
Returns None if domain cannot be safely converted to SQL.
"""
if not domain:
return None
try:
from odoo.osv import expression as osv_expression
Model = self.env[model]
table = Model._table
# Build the expression and extract query
expr = osv_expression.expression(model=Model, domain=domain)
query = expr.query
# Use query.select() to get the full SQL including FROM clause
# with all JOINs (needed for related field domains like gender_id.uri)
select_sql = query.select(SQL.identifier(table, "id"))
return SQL("(%s)", select_sql)
except Exception as e:
self._logger.debug("[CEL SQL] Failed to convert domain to SQL: %s", e)
return None
def _exists_to_sql(self, p: ExistsThrough) -> SQL | None:
"""Convert ExistsThrough to a SQL subquery.
Returns SQL selecting parent IDs where at least one matching child exists.
"""
try:
through_table = self.env[p.through_model]._table
# Build child filter SQL
child_sql: SQL | None = None
if p.child_plan is not None:
child_domain, requires_exec = self._plan_to_domain(p.child_model, p.child_plan)
if requires_exec:
# Child plan requires execution - can't do SQL fast path
return None
if child_domain:
child_sql = self._domain_to_id_sql(p.child_model, child_domain)
if child_sql is None:
return None
# Build default domain SQL using SQLBuilder
builder = SQLBuilder(self.env)
through_where_parts: list[SQL] = []
if p.default_domain:
default_terms, success = builder.build_default_domain_sql("m", p.default_domain)
if not success:
# Unsupported operator, fall back to Python
return None
through_where_parts.extend(default_terms)
# Build the EXISTS query
if child_sql:
where_child = SQL("m.%s IN %s", SQL.identifier(p.link_field), child_sql)
through_where_parts.append(where_child)
if through_where_parts:
where_clause = builder.where_and(through_where_parts)
result = SQL(
"(SELECT DISTINCT m.%s FROM %s m WHERE %s)",
SQL.identifier(p.parent_field),
SQL.identifier(through_table),
where_clause,
)
else:
result = SQL(
"(SELECT DISTINCT m.%s FROM %s m)",
SQL.identifier(p.parent_field),
SQL.identifier(through_table),
)
return result
except Exception as e:
self._logger.debug("[CEL SQL] Failed to build EXISTS SQL: %s", e)
return None
def _count_to_sql(self, p: CountThrough) -> SQL | None:
"""Convert CountThrough to a SQL subquery.
Returns SQL selecting parent IDs where child count matches the comparison.
Special handling for edge cases:
- count == 0: Parents with NO matching children (NOT IN subquery)
- count < N or count <= N: Fall back to Python (needs special handling for 0-count parents)
- count != N: Fall back to Python (complex edge cases)
- count > 0, count >= N, count > N: Use GROUP BY + HAVING (standard approach)
"""
try:
through_table = self.env[p.through_model]._table
# Build child filter SQL
child_sql: SQL | None = None
if p.child_plan is not None:
child_domain, requires_exec = self._plan_to_domain(p.child_model, p.child_plan)
if requires_exec:
return None
if child_domain:
child_sql = self._domain_to_id_sql(p.child_model, child_domain)
if child_sql is None:
return None
# Build default domain SQL using SQLBuilder
builder = SQLBuilder(self.env)
where_parts: list[SQL] = []
if p.default_domain:
default_terms, success = builder.build_default_domain_sql("m", p.default_domain)
if not success:
# Unsupported operator, fall back to Python
return None
where_parts.extend(default_terms)
if child_sql:
where_parts.append(SQL("m.%s IN %s", SQL.identifier(p.link_field), child_sql))
where_clause = builder.where_and(where_parts)
# Normalize operator
op = p.op
if op == "==":
op = "="
rhs = p.rhs
# Fall back to Python for comparisons that need zero-count parents included
# These are complex to handle correctly in SQL without the parent table:
# - count == 0: Parents with no rows in membership table won't appear in SQL
# - count < N: Must include zero-count parents
# - count <= N: Must include zero-count parents
# - count != N: Complex edge cases with zero-count
if op == "=" and rhs == 0:
return None
if op in ("<", "<="):
return None
if op == "!=":
return None
# Map operator for standard GROUP BY + HAVING approach
# Works for: count > 0, count >= N (N > 0), count > N
op_map = {">": ">", ">=": ">=", "=": "="}
sql_op = op_map.get(op)
if sql_op is None:
return None
# Build the COUNT query with HAVING
return SQL(
"(SELECT m.%s FROM %s m WHERE %s GROUP BY m.%s HAVING COUNT(*) %s %s)",
SQL.identifier(p.parent_field),
SQL.identifier(through_table),
where_clause,
SQL.identifier(p.parent_field),
SQL(sql_op),
rhs,
)
except Exception as e:
self._logger.debug("[CEL SQL] Failed to build COUNT SQL: %s", e)
return None
def _aggregate_to_sql(self, p: FieldAggregateThrough) -> SQL | None:
"""Convert FieldAggregateThrough to SQL subquery.
Uses CTE pattern for clarity and correctness:
WITH allowed_children AS (
SELECT id, {agg_field} FROM {child_table}
WHERE id IN {child_subquery} -- with record rules
)
SELECT m.{parent_col} FROM {through_table} m
JOIN allowed_children c ON c.id = m.{link_col}
WHERE {default_domain conditions}
GROUP BY m.{parent_col}
HAVING {agg_func}(c.{agg_field}) {op} {rhs}
"""
try:
builder = SQLBuilder(self.env)
through_table = self.env[p.through_model]._table
child_table = self.env[p.child_model]._table
# Build child subquery with record rules
child_domain: list[Any] = []
if p.child_plan is not None:
child_domain, requires_exec = self._plan_to_domain(p.child_model, p.child_plan)
if requires_exec:
# Child plan requires execution - can't do SQL fast path
return None
# Convert child domain to SQL (with record rules applied)
child_sql = builder.select_ids_from_domain(p.child_model, child_domain)
if child_sql is None:
return None
# Build WHERE clause for through table from default_domain
where_sql: SQL | None = None
if p.default_domain:
terms, success = builder.build_default_domain_sql("m", p.default_domain)
if not success:
# Unsupported operators in default_domain
return None
if terms:
where_sql = builder.where_and(terms)
# Build the aggregate query using SQLBuilder
return builder.select_grouped_aggregate(
through_table=through_table,
through_alias="m",
child_subquery=child_sql,
parent_col=p.parent_field,
link_col=p.link_field,
agg_func=p.agg_type.upper(),
agg_field=p.agg_field,
child_table=child_table,
having_op=p.op,
having_value=p.rhs,
where=where_sql,
)
except Exception as e:
self._logger.debug("[CEL SQL] Failed to build aggregate SQL: %s", e)
return None
def _plan_to_sql(self, model: str, plan: Any) -> SQL | None:
"""Convert a QueryPlan to SQL subquery if possible.
Returns SQL object or None if SQL conversion is not possible.
"""
if isinstance(plan, LeafDomain):
if plan.model != model:
return None
return self._domain_to_id_sql(plan.model, plan.domain)
if isinstance(plan, ExistsThrough):
return self._exists_to_sql(plan)
if isinstance(plan, CountThrough):
return self._count_to_sql(plan)
if isinstance(plan, FieldAggregateThrough):
return self._aggregate_to_sql(plan)
if isinstance(plan, AND):
# AND of SQL subqueries = INTERSECT
sqls: list[SQL] = []
for node in flatten_and(plan.nodes):
sql = self._plan_to_sql(model, node)
if sql is None:
return None
sqls.append(sql)
if not sqls:
return None
if len(sqls) == 1:
return sqls[0]
# Use INTERSECT for AND
result = sqls[0]
for sql in sqls[1:]:
result = SQL("(%s INTERSECT %s)", result, sql)
return result
if isinstance(plan, OR):
# OR of SQL subqueries = UNION
sqls = []
for node in plan.nodes:
sql = self._plan_to_sql(model, node)
if sql is None:
return None
sqls.append(sql)
if not sqls:
return None
if len(sqls) == 1:
return sqls[0]
result = sqls[0]
for sql in sqls[1:]:
result = SQL("(%s UNION %s)", result, sql)
return result
# NOT, MetricCompare, etc. - fall back to Python execution
return None
def _check_metrics_available(self, metric_name=None):
"""Check if metrics/cache infrastructure is available. Raise CELMetricsUnavailableError if not."""
# Check for new cache table first, then legacy
if "spp.data.value" not in self.env and "spp.indicator" not in self.env:
raise CELMetricsUnavailableError(metric_name)
def _get_cache_table_info(self) -> dict[str, str]:
"""Determine which cache table to use for metric lookups.
Returns dict with:
- table: SQL table name
- model: Odoo model name
- metric_field: Field name for metric/variable name
Prefers spp.data.value (new) over spp.indicator.value (legacy).
"""
# Prefer new unified cache table
if "spp.data.value" in self.env:
return {
"table": "spp_data_value",
"model": "spp.data.value",
"metric_field": "variable_name",
}
# Fallback to legacy indicator cache
elif "spp.indicator.value" in self.env:
return {
"table": "spp_indicator_value",
"model": "spp.indicator.value",
"metric_field": "metric",
}
else:
# Should not reach here if _check_metrics_available is called first
return {
"table": "spp_data_value",
"model": "spp.data.value",
"metric_field": "variable_name",
}
@api.model
def compile_and_preview(
self,
model: str,
expr: str,
limit: int = 50,
offset: int = 0,
fields: list[str] | None = None,
materialize_sql: bool = False,
) -> dict[str, Any]:
import uuid
cfg = self.env.context.get("cel_cfg") or {}
translator = self.env["spp.cel.translator"]
plan, explain = translator.translate(model, expr, cfg)
# Compose base domain
base_domain = cfg.get("base_domain", [])
metrics_info: list[dict[str, Any]] = []
request_id = str(uuid.uuid4())
domain, requires_exec = self._plan_to_domain(model, plan)
final_domain = self._and_domains(base_domain, domain)
count, ids = 0, []
sql_path_used = False
if requires_exec:
# Try SQL fast path first (scales to millions of records)
sql_subquery = self._plan_to_sql(model, plan)
if sql_subquery is not None and not materialize_sql:
# SQL path succeeded - use subquery instead of materializing IDs
final_domain = self._and_domains(base_domain, [("id", "in", sql_subquery)])
sql_path_used = True
self._logger.info("[CEL SQL] Using SQL fast path for expr=%s", expr)
else:
# Fall back to Python execution (may be slow for large datasets)
self._logger.info(
"[CEL SQL] SQL fast path unavailable, falling back to Python for expr=%s",
expr,
)
exec_self = self.with_context(cel_mode="preview", cel_request_id=request_id)
ids = exec_self._execute_plan(model, plan, metrics_info)
# If a fast-path domain override was provided in metrics_info, use it instead of materializing ids
override_domain: list[Any] | None = None
for mi in metrics_info:
od = mi.get("override_domain") if isinstance(mi, dict) else None
if od:
override_domain = od
break
if override_domain:
final_domain = self._and_domains(base_domain, override_domain)
else:
final_domain = self._and_domains(base_domain, [("id", "in", ids)])
# Determine execution path for logging and response
path = "sql" if sql_path_used else ("python" if requires_exec else "domain")
warnings: list[str] = []
# Add warning for Python path (scalability concern)
if path == "python":
warnings.append("Using Python path. May be slow for large datasets.")
# Log for visibility during tests (truncate large ID lists)
try:
self._logger.info(
"[CEL EXEC] model=%s expr=%s explain=%s domain=%s path=%s",
model,
expr,
explain,
self._format_domain_for_log(final_domain),
path,
)
except Exception:
pass
# SCALABILITY FIX: Use search_count() + search(limit=N) instead of loading all IDs
# This bounds memory usage regardless of result set size
count = self.env[model].search_count(final_domain)
# limit=None means count-only mode (no IDs), limit=0 uses default, limit>0 is explicit
preview_data: list[dict[str, Any]] = []
if limit is None:
preview_ids = [] # Count-only mode
elif limit == 0:
# Use the default from the method signature (50)
preview_recordset = self.env[model].search(final_domain, limit=50, offset=offset)
preview_ids = preview_recordset.ids
else:
preview_recordset = self.env[model].search(final_domain, limit=limit, offset=offset)
preview_ids = preview_recordset.ids
# Read full record data if fields requested (for JSON-safe preview)
if preview_ids and fields:
# Replace phone_number_ids with phone for reading, then enrich
read_fields = [f for f in fields if f != "phone_number_ids"]
preview_data = preview_recordset.read(read_fields)
if "phone_number_ids" in fields:
for rec_data in preview_data:
rec_id = rec_data["id"]
partner = preview_recordset.filtered(lambda r, rid=rec_id: r.id == rid)
phones = partner.phone_number_ids.filtered(lambda p: not p.disabled).mapped("phone_no")
rec_data["phone_numbers"] = phones
# Enrich explanation with metrics info if any
metrics_section = ""
if metrics_info:
parts = []
for mi in metrics_info:
# Add lightweight warnings for metrics
mi_warnings = []
cov = float(mi.get("coverage") or 0.0)
if cov < 0.8:
mi_warnings.append("LOW_COVERAGE")
if int(mi.get("misses") or 0) > 0:
mi_warnings.append("CACHE_MISSES")
if mi.get("provider_missing"):
mi_warnings.append("PROVIDER_MISSING")
if mi.get("cache_any_provider_used"):
mi_warnings.append("CACHE_ANY_PROVIDER")
mi["warnings"] = mi_warnings
parts.append(
f"metric={mi.get('metric')} period={mi.get('period_key')} "
f"requested={mi.get('requested')} cache_hits={mi.get('cache_hits')} "
f"fresh={mi.get('fresh_fetches')} coverage={round(cov * 100, 1)}%"
+ (f" warnings={','.join(mi_warnings)}" if mi_warnings else "")
)
metrics_section = " | Metrics: " + "; ".join(parts)
explain = f"{explain}{metrics_section}"
return {
"domain": final_domain,
"domain_text": str(final_domain),
"explain": explain,
"explain_struct": {
"metrics": metrics_info,
"request_id": request_id,
},
"count": count,
"preview_records": preview_data, # Full record data (JSON-safe)
"preview_ids": preview_ids, # New field per spec
"ids": preview_ids, # Backward compatibility (deprecated)
"path": path, # Execution path: sql|python|domain
"warnings": warnings, # Scalability warnings
}
@api.model
def compile_for_batch(self, model: str, expr: str, batch_size: int = 5000) -> Iterator[list[int]]:
"""Compile expression and yield batches of matching IDs.
For processing millions of records without memory exhaustion.
Uses cursor-based pagination (keyset pagination).
Yields:
Lists of IDs, each up to batch_size length
Example:
for batch_ids in executor.compile_for_batch("res.partner", expr):
process_batch(batch_ids) # Process 5000 at a time
"""
cfg = self.env.context.get("cel_cfg") or {}
translator = self.env["spp.cel.translator"]
plan, explain = translator.translate(model, expr, cfg)
base_domain = cfg.get("base_domain", [])
# Try SQL fast path first
sql_subquery = self._plan_to_sql(model, plan)
if sql_subquery is not None:
# SQL path - use cursor-based pagination
domain = self._and_domains(base_domain, [("id", "in", sql_subquery)])
# Use keyset pagination (cursor-based)
last_id = 0
while True:
batch_domain = self._and_domains(domain, [("id", ">", last_id)])
batch = self.env[model].search(batch_domain, limit=batch_size, order="id")
if not batch:
break
yield batch.ids
last_id = batch.ids[-1]
if len(batch) < batch_size:
break
else:
# Python fallback - execute once and paginate results in memory
domain, requires_exec = self._plan_to_domain(model, plan)
if requires_exec:
# Execute plan to get all IDs
ids = self._execute_plan(model, plan)
# Apply base domain to filter
final_domain = self._and_domains(base_domain, [("id", "in", ids)])
all_ids = self.env[model].search(final_domain).ids
else:
# Simple domain path
final_domain = self._and_domains(base_domain, domain)
all_ids = self.env[model].search(final_domain).ids
# Paginate results in memory
for i in range(0, len(all_ids), batch_size):
yield all_ids[i : i + batch_size]
@api.model
def compile_count_only(self, model: str, expr: str) -> dict[str, Any]:
"""Get count of matching records without loading any IDs.
Most efficient method when you only need the count.
Returns:
count: Number of matching records
path: "sql" | "python" | "domain"
warnings: List of warnings
"""
cfg = self.env.context.get("cel_cfg") or {}
translator = self.env["spp.cel.translator"]
plan, explain = translator.translate(model, expr, cfg)
base_domain = cfg.get("base_domain", [])
# Try SQL fast path first
sql_subquery = self._plan_to_sql(model, plan)
if sql_subquery is not None:
# SQL path - efficient count
domain = self._and_domains(base_domain, [("id", "in", sql_subquery)])
count = self.env[model].search_count(domain)
return {"count": count, "path": "sql", "warnings": []}
# Check if simple domain (no execution needed)
domain, requires_exec = self._plan_to_domain(model, plan)
if not requires_exec:
# Simple domain path - efficient count without loading IDs
final_domain = self._and_domains(base_domain, domain)
count = self.env[model].search_count(final_domain)
return {"count": count, "path": "domain", "warnings": []}
# Python fallback - must execute plan to get IDs
ids = self._execute_plan(model, plan)
# Apply base domain to filter
final_domain = self._and_domains(base_domain, [("id", "in", ids)])
# Use search_count for efficiency (respects record rules and base_domain)
count = self.env[model].search_count(final_domain)
return {
"count": count,
"path": "python",
"warnings": ["Count required Python execution"],
}
# Plan → Domain (best effort)
def _plan_to_domain(self, model: str, plan: Any) -> tuple[list[Any], bool]:
if isinstance(plan, LeafDomain):
if plan.model != model:
# different model; cannot express as dotted safely
return [], True
return plan.domain, False
if isinstance(plan, AND):
domains: list[Any] = []
needs_exec = False
for n in flatten_and(plan.nodes):
d, e = self._plan_to_domain(model, n)
needs_exec = needs_exec or e
if d:
domains = self._and_domains(domains, d)
return domains, needs_exec
if isinstance(plan, OR):
# if any side requires exec, mark as exec
left, le = self._plan_to_domain(model, plan.nodes[0])
right, re = self._plan_to_domain(model, plan.nodes[1])
if le or re:
return [], True
return ["|", *left, *right], False
if isinstance(plan, NOT):
d, e = self._plan_to_domain(model, plan.node)
if e:
return [], True
return ["!", *d], False
if isinstance(plan, ExistsThrough | CountThrough | FieldAggregateThrough):
return [], True
return [], True
def _and_domains(self, a: list[Any], b: list[Any]) -> list[Any]:
da = self._ensure_domain_list(a)
db = self._ensure_domain_list(b)
if not da:
return db
if not db:
return da
# Check if any domain contains SQL objects - if so, don't use Domain.AND
# as it serializes SQL objects incorrectly (converts them to string repr)
def contains_sql(domain):
for term in domain:
if isinstance(term, tuple | list) and len(term) == 3:
if isinstance(term[2], SQL):
return True
return False
if contains_sql(da) or contains_sql(db):
# Manual AND: just concatenate (implicit AND in Odoo domains)
# This preserves SQL objects without serialization
return da + db
return list(Domain.AND([da, db]))
def _ensure_domain_list(self, domain: list[Any]) -> list[Any]:
if not domain:
return []
# Handle Odoo 19 Domain objects - convert to list first
if isinstance(domain, Domain):
domain = list(domain)
if isinstance(domain, list):
normalized: list[Any] = []
for term in list(domain):
if (
isinstance(term, list)
and len(term) == 3
and term
and isinstance(term[0], str)
and term[0] not in {"&", "|", "!", "not"}
):
normalized.append(tuple(term))
else:
normalized.append(term)
return normalized
return [domain]
# Execute
def _execute_plan(self, model: str, plan: Any, metrics_info: list[dict[str, Any]] | None = None) -> list[int]: # noqa: C901
if isinstance(plan, LeafDomain):
return self.env[plan.model].search(plan.domain).ids
if isinstance(plan, AND):
# intersection
id_sets = [set(self._execute_plan(model, p, metrics_info)) for p in flatten_and(plan.nodes)]
if not id_sets:
return []
s = id_sets[0]
for other in id_sets[1:]:
s = s.intersection(other)
return list(s)
if isinstance(plan, OR):
ids = set()
for p in plan.nodes:
ids.update(self._execute_plan(model, p, metrics_info))
return list(ids)
if isinstance(plan, NOT):
# CRITICAL FIX: Do not load all IDs into memory (DoS risk on large datasets)
domain, requires_exec = self._plan_to_domain(model, plan.node)
if requires_exec:
raise NotImplementedError(
"Negating complex expressions (like 'exists' or 'count') is not supported "
"due to performance constraints. Please restructure your expression to avoid "
"negating subqueries. For example, instead of 'not members.exists(m, P)', "
"try to express the positive condition."
)
# Use native Odoo domain negation instead of memory-based set operations
negated_domain = ["!"] + domain
return self.env[model].search(negated_domain).ids
if isinstance(plan, ExistsThrough):
return self._exec_exists(plan)
if isinstance(plan, CountThrough):
return self._exec_count(plan)
if isinstance(plan, MetricCompare):
return self._exec_metric(model, plan, metrics_info)
if isinstance(plan, CoverageRequire):
# Only support gating on MetricCompare results for now
if not isinstance(plan.node, MetricCompare):
raise NotImplementedError("require_coverage currently supports only metric() comparisons")
# Evaluate metric comparison and get stats for coverage check
tmp_stats: list[dict[str, Any]] = []
ids = self._exec_metric(model, plan.node, tmp_stats)
cov = 0.0
if tmp_stats:
cov = float(tmp_stats[-1].get("coverage") or 0.0)
if metrics_info is not None:
metrics_info.extend(tmp_stats)
if cov < float(plan.min_coverage or 0.0):
return []
return ids
if isinstance(plan, AggMetricCompare):
return self._exec_agg_metric(model, plan, metrics_info)
if isinstance(plan, FieldAggregateThrough):
return self._exec_field_aggregate(plan)
return []
def _exec_exists(self, p: ExistsThrough) -> list[int]:
# Build membership domain, splitting child predicates to through-model vs child-model
dom: list[Any] = []
if p.default_domain:
dom = self._and_domains(dom, p.default_domain)
mem_dom, child_subplan = self._split_child_membership(p.through_model, p.child_plan)
if mem_dom:
dom = self._and_domains(dom, mem_dom)
if child_subplan is not None:
child_domain, requires_exec_child = self._plan_to_domain(p.child_model, child_subplan)
try:
self._logger.info(
"[CEL EXISTS] child_subplan model=%s plan=%s requires_exec=%s",
getattr(child_subplan, "model", None),
getattr(child_subplan, "domain", None),
requires_exec_child,
)
except Exception:
pass
if requires_exec_child:
child_ids = self._execute_plan(p.child_model, child_subplan)
else:
child_domain = self._ensure_domain_list(child_domain)
try:
self._logger.info(
"[CEL EXISTS] applying child domain=%s on model=%s",
self._format_domain_for_log(child_domain),
p.child_model,
)
except Exception:
pass
child_ids = self.env[p.child_model].search(child_domain).ids
child_ids = [int(i) for i in child_ids if i]
if not child_ids:
try:
self._logger.info(
"[CEL DEBUG EXISTS] child filter empty through=%s parent=%s child_model=%s "
"domain=%s requires_exec=%s",
p.through_model,
p.parent_field,
p.child_model,
self._format_domain_for_log(child_domain),
requires_exec_child,
)
except Exception:
pass
return []
dom = self._and_domains(dom, [(p.link_field, "in", child_ids)])
rows = self.env[p.through_model].search(dom)
# Debug: log domain size for troubleshooting (truncate large ID lists)
try:
self._logger.info(
"[CEL EXEC EXISTS] through=%s parent=%s link=%s mem_dom=%s child_subplan=%s rows=%s",
p.through_model,
p.parent_field,
p.link_field,
self._format_domain_for_log(dom),
child_subplan.__class__.__name__ if child_subplan else None,
len(rows),
)
except Exception:
pass
return list(set(rows.mapped(p.parent_field).ids))
def _exec_count(self, p: CountThrough) -> list[int]: # noqa: C901
cfg = self.env.context.get("cel_cfg") or {}
dom: list[Any] = []
if p.default_domain:
dom = self._and_domains(dom, p.default_domain)
mem_dom, child_subplan = self._split_child_membership(p.through_model, p.child_plan)
if mem_dom:
dom = self._and_domains(dom, mem_dom)
parent_model_name = None
parent_field_desc = self.env[p.through_model]._fields.get(p.parent_field)
if parent_field_desc is not None:
parent_model_name = getattr(parent_field_desc, "comodel_name", None)
base_domain: list[Any] = []
if parent_model_name and cfg.get("root_model") == parent_model_name:
if isinstance(cfg.get("base_domain"), list):
base_domain = cfg.get("base_domain")
candidate_parents: set[int] = set()
if parent_model_name and base_domain:
candidate_parents = set(int(pid) for pid in self.env[parent_model_name].search(base_domain).ids)
if child_subplan is not None:
child_domain, requires_exec_child = self._plan_to_domain(p.child_model, child_subplan)
if requires_exec_child:
child_ids = self._execute_plan(p.child_model, child_subplan)
else:
child_domain = self._ensure_domain_list(child_domain)
try:
self._logger.info(
"[CEL COUNT] applying child domain=%s on model=%s",
self._format_domain_for_log(child_domain),
p.child_model,
)
except Exception:
pass
child_ids = self.env[p.child_model].search(child_domain).ids
child_ids = [int(i) for i in child_ids if i]
try:
self._logger.info(
"[CEL COUNT] child filter results child_model=%s count=%s sample_ids=%s",
p.child_model,
len(child_ids),
child_ids[:10],
)
except Exception:
pass
if not child_ids:
# No matching children; counts are zero for all candidate parents
if not candidate_parents and parent_model_name:
search_domain = base_domain if base_domain else []
candidate_parents = set(int(pid) for pid in self.env[parent_model_name].search(search_domain).ids)
return [pid for pid in candidate_parents if self._compare(0, p.op, p.rhs)]
dom = self._and_domains(dom, [(p.link_field, "in", child_ids)])
rows = self.env[p.through_model].read_group(dom, [p.parent_field], [p.parent_field])
counts: dict[int, int] = {}
for r in rows:
count = int(r.get(f"{p.parent_field}_count") or 0)
pid = r.get(p.parent_field)
if isinstance(pid, tuple):
pid = pid[0]
if pid:
counts[int(pid)] = count
parent_ids: set[int] = set(counts.keys())
if candidate_parents:
parent_ids |= candidate_parents
if not parent_ids and parent_model_name:
search_domain = base_domain if base_domain else []
parent_ids = set(int(pid) for pid in self.env[parent_model_name].search(search_domain).ids)
res: list[int] = []
for pid in parent_ids:
if self._compare(counts.get(pid, 0), p.op, p.rhs):
res.append(pid)
return res
def _compare(self, a: int, op: str, b: int) -> bool:
return {
"=": a == b,
"==": a == b,
">": a > b,
">=": a >= b,
"<": a < b,
"<=": a <= b,
"!=": a != b,
}[op]
def _exec_field_aggregate(self, p: FieldAggregateThrough) -> list[int]: # noqa: C901
"""Execute a field aggregation query (sum, avg, min, max).
This method aggregates a numeric field over members matching a filter
and returns parent IDs where the aggregate value matches the comparison.
Strategy:
- Build membership domain with default_domain and child filter
- Get matching child IDs
- Read field values from children
- Group by parent and compute aggregate
- Compare against rhs and return matching parent IDs
"""
cfg = self.env.context.get("cel_cfg") or {}
dom: list[Any] = []
if p.default_domain:
dom = self._and_domains(dom, p.default_domain)
mem_dom, child_subplan = self._split_child_membership(p.through_model, p.child_plan)
if mem_dom:
dom = self._and_domains(dom, mem_dom)
parent_model_name = None
parent_field_desc = self.env[p.through_model]._fields.get(p.parent_field)
if parent_field_desc is not None:
parent_model_name = getattr(parent_field_desc, "comodel_name", None)
base_domain: list[Any] = []
if parent_model_name and cfg.get("root_model") == parent_model_name:
if isinstance(cfg.get("base_domain"), list):
base_domain = cfg.get("base_domain")
candidate_parents: set[int] = set()
if parent_model_name and base_domain:
candidate_parents = set(int(pid) for pid in self.env[parent_model_name].search(base_domain).ids)
# Get matching child IDs based on filter
child_ids: list[int] = []
if child_subplan is not None:
child_domain, requires_exec_child = self._plan_to_domain(p.child_model, child_subplan)
if requires_exec_child:
child_ids = self._execute_plan(p.child_model, child_subplan)
else:
child_domain = self._ensure_domain_list(child_domain)
child_ids = self.env[p.child_model].search(child_domain).ids
child_ids = [int(i) for i in child_ids if i]
if not child_ids:
# No matching children; aggregate values are 0/null for all parents
if not candidate_parents and parent_model_name:
search_domain = base_domain if base_domain else []
candidate_parents = set(int(pid) for pid in self.env[parent_model_name].search(search_domain).ids)
# For sum, no children means 0; compare 0 against rhs
return [pid for pid in candidate_parents if self._cmp_value(0, p.op, p.rhs)]
dom = self._and_domains(dom, [(p.link_field, "in", child_ids)])
# Get membership records to build parent -> children mapping
memberships = self.env[p.through_model].search(dom)
if not memberships:
return []
# Build parent -> [child_ids] mapping
parent_map: dict[int, list[int]] = {}
for r in memberships:
try:
pid = int(
getattr(r, p.parent_field).id
if hasattr(getattr(r, p.parent_field), "id")
else getattr(r, p.parent_field)
)
cid = int(
getattr(r, p.link_field).id if hasattr(getattr(r, p.link_field), "id") else getattr(r, p.link_field)
)
except Exception:
continue
parent_map.setdefault(pid, []).append(cid)
# Get all unique child IDs
all_child_ids = sorted({cid for lst in parent_map.values() for cid in lst})
if not all_child_ids: