|
| 1 | +# CEL Metrics SQL Optimization — V2 (Odoo 17) |
| 2 | + |
| 3 | +Date: 2025-10-02 Status: Ready for implementation Modules: `openspp_metrics`, `openspp_cel/cel_domain` |
| 4 | + |
| 5 | +--- |
| 6 | + |
| 7 | +## Executive Summary |
| 8 | + |
| 9 | +Goal: Make CEL expressions that compare metric values (e.g., |
| 10 | +`metric("education.attendance_pct", me, "2024-09") >= 85`) fast and memory‑safe on large datasets, without |
| 11 | +bypassing Odoo record rules or returning stale/partial data. |
| 12 | + |
| 13 | +Strategy: Two-tier execution |
| 14 | + |
| 15 | +- Tier 1 — SQL Fast Path: Build an `INSELECT` domain against `openspp_feature_value` to let Postgres filter |
| 16 | + candidates with indexes, zero Python materialization of ID lists, and full record-rule enforcement. |
| 17 | +- Tier 2 — Async Refresh: When cache is incomplete/stale or dataset is too large, never block in preview; in |
| 18 | + evaluate mode enqueue background refresh jobs and return once cached. |
| 19 | + |
| 20 | +Key constraints adopted in V2 |
| 21 | + |
| 22 | +- No partial indexes using `NOW()`; use stable composite indexes that work with partitions and the planner. |
| 23 | +- All user-facing queries keep Odoo record rules by using domains; no direct SQL joins for subject tables. |
| 24 | +- Preview never calls external providers (cache-only); evaluate may enqueue refresh via `queue_job`. |
| 25 | + |
| 26 | +--- |
| 27 | + |
| 28 | +## Scope (V2) |
| 29 | + |
| 30 | +Covered |
| 31 | + |
| 32 | +- Subject-level metric comparisons on the current model (e.g., partners, groups): numeric and equality |
| 33 | + operators. |
| 34 | +- Cache completeness/freshness preflight; SQL fast path when fresh and complete. |
| 35 | +- Async refresh queueing in evaluate mode; clear messaging in preview. |
| 36 | +- Index additions, flags, and targeted tests. |
| 37 | + |
| 38 | +Deferred (remain in Python for now) |
| 39 | + |
| 40 | +- Aggregators over relations: `avg_over`, `coverage_over`, `all_over`. |
| 41 | +- Multi-metric SQL fusion (`metric A AND metric B` in one SQL) — future enhancement. |
| 42 | + |
| 43 | +--- |
| 44 | + |
| 45 | +## Current Baseline (as of V2) |
| 46 | + |
| 47 | +Data model: `openspp_feature_value` (JSONB value, keys: `metric`, `provider`, `subject_model`, `subject_id`, |
| 48 | +`period_key`, `params_hash`, `company_id`, plus `coverage`, `as_of`, `fetched_at`, `expires_at`, `error_*`). |
| 49 | + |
| 50 | +Indexes already present |
| 51 | + |
| 52 | +- `idx_ofv_metric_subject_period(company_id, metric, provider, subject_model, subject_id, period_key, params_hash)` |
| 53 | +- `idx_ofv_metric_period(company_id, metric, period_key)` |
| 54 | +- `idx_ofv_provider(company_id, provider)` |
| 55 | + |
| 56 | +Partitioning: HASH(subject_id) with N=16 partitions created automatically on install. |
| 57 | + |
| 58 | +Executor baseline: `_exec_metric` loads candidate IDs in Python then calls |
| 59 | +`openspp.metrics.evaluate(..., mode='fallback')`, filters in Python. This causes full scans and high memory on |
| 60 | +100k+ cohorts. |
| 61 | + |
| 62 | +--- |
| 63 | + |
| 64 | +## V2 Design |
| 65 | + |
| 66 | +### 1) Preview vs Evaluate semantics |
| 67 | + |
| 68 | +- Preview (`cel_mode=preview`, used by Compile & Preview UI): |
| 69 | + |
| 70 | + - Never call providers; use cache-only. |
| 71 | + - If cache not fresh/complete for the cohort, do not fall back to Python refresh. Return a clear |
| 72 | + explain/warning and (optionally) a UI affordance to queue refresh. |
| 73 | + |
| 74 | +- Evaluate (non-preview, e.g., batch/back-end): |
| 75 | + - If cache not fresh/complete and dataset ≥ threshold, enqueue refresh jobs and return (or short-circuit) |
| 76 | + based on feature flag. No silent truncation. |
| 77 | + |
| 78 | +### 2) Cache preflight checker (cheap SQL) |
| 79 | + |
| 80 | +For a given subject model `M`, metric `m`, period `p`, provider `prov`, params_hash `ph`, company `c`, and |
| 81 | +base domain `D`: |
| 82 | + |
| 83 | +- Compute `base_count` = count of distinct records in `M` that satisfy `D` (via standard `search_count(D)`). |
| 84 | +- Compute `have_count` = count of distinct IDs in `M` with |
| 85 | + `id IN (SELECT subject_id FROM openspp_feature_value WHERE company_id=c AND metric=m AND subject_model=M AND period_key=p AND provider=prov AND params_hash=ph AND error_code IS NULL)`. |
| 86 | +- Compute `stale_count` = count of distinct IDs with |
| 87 | + `id IN (SELECT subject_id ... WHERE (expires_at IS NOT NULL AND expires_at <= NOW()) )`. |
| 88 | + |
| 89 | +Status rules |
| 90 | + |
| 91 | +- `fresh_and_complete` when `have_count == base_count` and `stale_count == 0`. |
| 92 | +- `incomplete` when `have_count < base_count`. |
| 93 | +- `stale` when `stale_count > 0`. |
| 94 | + |
| 95 | +Implementation notes |
| 96 | + |
| 97 | +- Use parametrized SQL in a helper; keep it read-only. |
| 98 | +- If `base_count` ≥ `cel.async_threshold`, treat as “large cohort”. |
| 99 | + |
| 100 | +### 3) SQL fast path via SQL domain |
| 101 | + |
| 102 | +When status is `fresh_and_complete` and the comparison is supported, build a domain that embeds the feature |
| 103 | +store predicate: |
| 104 | + |
| 105 | +Domain structure |
| 106 | + |
| 107 | +- Final domain = `AND(D, ('id', 'in', SQL(...)))` |
| 108 | +- Odoo will apply record rules on `M` because `search()` still runs on `M`. |
| 109 | + |
| 110 | +SQL template (numeric compare) |
| 111 | + |
| 112 | +```sql |
| 113 | +SELECT DISTINCT fv.subject_id |
| 114 | +FROM openspp_feature_value fv |
| 115 | +WHERE fv.company_id = %(company_id)s |
| 116 | + AND fv.metric = %(metric)s |
| 117 | + AND fv.subject_model = %(subject_model)s |
| 118 | + AND fv.period_key = %(period_key)s |
| 119 | + AND fv.provider = %(provider)s |
| 120 | + AND fv.params_hash = %(params_hash)s |
| 121 | + AND fv.error_code IS NULL |
| 122 | + AND (fv.expires_at IS NULL OR fv.expires_at > NOW()) |
| 123 | + AND jsonb_typeof(fv.value_json) = 'number' |
| 124 | + AND (fv.value_json::numeric) %(op)s %(rhs)s |
| 125 | +``` |
| 126 | + |
| 127 | +SQL template (string equality/inequality) |
| 128 | + |
| 129 | +```sql |
| 130 | +... AND fv.value_json::text %(op)s %(rhs_text)s |
| 131 | +``` |
| 132 | + |
| 133 | +Supported operators in V2 |
| 134 | + |
| 135 | +- Numeric: `==`, `!=`, `>`, `>=`, `<`, `<=` |
| 136 | +- String: `==`, `!=` (other string ops can be added later; prefer exact matches in V2) |
| 137 | + |
| 138 | +Null/missing/error handling |
| 139 | + |
| 140 | +- Rows with `error_code` are excluded. |
| 141 | +- `NULL` values do not match any predicate (safest default). |
| 142 | + |
| 143 | +Type safety |
| 144 | + |
| 145 | +- Guard with `jsonb_typeof(value_json) = 'number'` before numeric casts. |
| 146 | + |
| 147 | +### 4) Evaluate mode and async refresh |
| 148 | + |
| 149 | +Evaluate behavior (non-preview): |
| 150 | + |
| 151 | +- If status != `fresh_and_complete`: |
| 152 | + - If `base_count >= cel.async_threshold` → enqueue refresh (`openspp.metrics.enqueue_refresh`) in |
| 153 | + micro-batches; return explain with job count. |
| 154 | + - Else (small cohort): call `openspp.metrics.evaluate(..., mode='refresh')` synchronously to fill cache, |
| 155 | + then immediately execute the SQL fast path. |
| 156 | + |
| 157 | +Queue details (existing API) |
| 158 | + |
| 159 | +- Use `with_delay(priority=20, identity_key=...)` when `queue_job` is available; fallback to immediate refresh |
| 160 | + if not. |
| 161 | +- Chunk size: `ir.config_parameter['cel.chunk_size']` (default 10000). |
| 162 | + |
| 163 | +### 5) Provider/params resolution |
| 164 | + |
| 165 | +- Provider label comes from `openspp.metric.registry.get(metric)['provider']` if present; fallback to |
| 166 | + `metric`. |
| 167 | +- `params_hash` should be `""` for CEL V2 unless the CEL translator passes explicit params; keep code ready to |
| 168 | + accept it. |
| 169 | + |
| 170 | +### 6) Indexing plan |
| 171 | + |
| 172 | +Add a subject-first composite index (safe with partitions and planner): |
| 173 | + |
| 174 | +```sql |
| 175 | +CREATE INDEX IF NOT EXISTS idx_ofv_subject_company_metric_period |
| 176 | +ON openspp_feature_value (subject_id, company_id, metric, subject_model, period_key, provider, params_hash); |
| 177 | +``` |
| 178 | + |
| 179 | +Keep others as-is. Do NOT create partial indexes with `NOW()`. |
| 180 | + |
| 181 | +### 7) Feature flags (ir.config_parameter) |
| 182 | + |
| 183 | +- `cel.enable_sql_metrics` (default `true`): master switch for SQL fast path. |
| 184 | +- `cel.preview_cache_only` (default `true`): in preview, never call providers. |
| 185 | +- `cel.async_threshold` (default `50000`): cohort size threshold to force async. |
| 186 | +- `cel.chunk_size` (default `10000`): micro-batch size for refresh. |
| 187 | + |
| 188 | +--- |
| 189 | + |
| 190 | +## Implementation Guide (file-level tasks) |
| 191 | + |
| 192 | +### A) Feature store indexes |
| 193 | + |
| 194 | +File: `openspp_metrics/models/feature_store.py` |
| 195 | + |
| 196 | +- Function `_ensure_indexes()` — add: |
| 197 | + ```python |
| 198 | + cr.execute( |
| 199 | + "CREATE INDEX IF NOT EXISTS idx_ofv_subject_company_metric_period " |
| 200 | + "ON openspp_feature_value (subject_id, company_id, metric, subject_model, period_key, provider, params_hash)" |
| 201 | + ) |
| 202 | + ``` |
| 203 | + |
| 204 | +### B) Executor: preview gating, preflight, SQL fast path |
| 205 | + |
| 206 | +File: `cel_domain/models/cel_executor.py` |
| 207 | + |
| 208 | +1. Preview gating in `_exec_metric` |
| 209 | + |
| 210 | + - Read `cel_mode` from context; if `preview`, set service mode to `cache_only` for any evaluate calls. |
| 211 | + |
| 212 | +2. Add helper `_metric_registry_info(metric) -> (provider, return_type)` |
| 213 | + |
| 214 | + - Query `openspp.metric.registry.get(metric)`; default provider to metric name. |
| 215 | + |
| 216 | +3. Add helper |
| 217 | + `_metric_cache_status_sql(model, base_domain, metric, period_key, provider, params_hash) -> dict` |
| 218 | + |
| 219 | + - Compute `base_count`, `have_count`, `stale_count` as described above using parametrized SQL `INSELECT` on |
| 220 | + `openspp_feature_value`. |
| 221 | + - Return `{'status': 'fresh'|'stale'|'incomplete', 'base': n, 'have': n, 'stale': n}`. |
| 222 | + |
| 223 | +4. Add helper |
| 224 | + `_metric_inselect_sql(model, metric, period_key, provider, params_hash, op, rhs, value_type) -> (sql, params)` |
| 225 | + |
| 226 | + - Build one of the two SQL templates (numeric or string). |
| 227 | + - Map CEL ops to SQL ops; enforce `error_code IS NULL` and freshness. |
| 228 | + |
| 229 | +5. Rewrite `_exec_metric` |
| 230 | + |
| 231 | + - Resolve provider/params. |
| 232 | + - Read flags/thresholds. |
| 233 | + - Call preflight. |
| 234 | + - If `enable_sql_metrics` and status is fresh+complete and operator/type supported: |
| 235 | + - Build `('id', 'inselect', (sql, params))` domain; return `search()` IDs. |
| 236 | + - Else (preview): append explain warning and return `[]` (or fall back to cache-only + Python filter behind |
| 237 | + optional flag, default disabled in V2). |
| 238 | + - Else (evaluate): if `base_count >= async_threshold` enqueue refresh; else call |
| 239 | + `evaluate(..., mode='refresh')` and retry SQL path. |
| 240 | + |
| 241 | +6. Explain |
| 242 | + - Enrich `metrics_info` with `{path: 'sql'|'python'|'queued'|'cache_only', status, base, have, stale}`. |
| 243 | + |
| 244 | +### C) No change to aggregators in V2 |
| 245 | + |
| 246 | +Keep `_exec_agg_metric` as-is. Document that aggregators stay in Python. Future V3 may add SQL GROUP BY over |
| 247 | +through models. |
| 248 | + |
| 249 | +--- |
| 250 | + |
| 251 | +## Testing Plan |
| 252 | + |
| 253 | +Unit tests (fast) |
| 254 | + |
| 255 | +- `TestMetricFastPathNumeric`: seed `openspp_feature_value` for N partners; assert that `>=, >, <=, <, ==, !=` |
| 256 | + match expected IDs via SQL path. Verify `metrics_info.path == 'sql'`. |
| 257 | +- `TestMetricFastPathString`: seed string values; assert equality/inequality behavior. |
| 258 | +- `TestMetricPreflightStatus`: construct cases for fresh, stale, incomplete and assert returned status. |
| 259 | + |
| 260 | +Integration tests (targeted) |
| 261 | + |
| 262 | +- Preview gating: with missing cache, `compile_and_preview` returns `count==0`, explain contains |
| 263 | + “LOW_COVERAGE/CACHE_MISSES”, and `metrics_info.path == 'cache_only'`. |
| 264 | +- Evaluate small cohort: missing cache -> refresh -> SQL path -> IDs correct in one call. |
| 265 | +- Evaluate large cohort: `base_count >= async_threshold` -> enqueue refresh; ensure no provider calls made |
| 266 | + inline; explain marks `queued`. |
| 267 | + |
| 268 | +Security tests |
| 269 | + |
| 270 | +- Create a partner record rule limiting visibility; ensure `search()` with INSELECT does not breach the rule |
| 271 | + (IDs returned are a subset of visible ones). |
| 272 | + |
| 273 | +Performance sanity (optional dev test) |
| 274 | + |
| 275 | +- Seed 50k partners + cached numeric metric; measure search time < 500ms on dev laptop with warm cache. |
| 276 | + |
| 277 | +--- |
| 278 | + |
| 279 | +## Configuration & Rollout |
| 280 | + |
| 281 | +System parameters (defaults) |
| 282 | + |
| 283 | +- `cel.enable_sql_metrics=true` |
| 284 | +- `cel.preview_cache_only=true` |
| 285 | +- `cel.async_threshold=50000` |
| 286 | +- `cel.chunk_size=10000` |
| 287 | + |
| 288 | +Rollout steps |
| 289 | + |
| 290 | +1. Deploy code with SQL fast path behind `cel.enable_sql_metrics`. |
| 291 | +2. Auto-create the new index in `_ensure_indexes()` on module update (metrics core). |
| 292 | +3. Stage validation: run targeted tests; run an EXPLAIN on the INSELECT query to confirm index scans and |
| 293 | + partition pruning. |
| 294 | +4. Enable in production; monitor query times and misses. |
| 295 | + |
| 296 | +Monitoring/logging (minimal) |
| 297 | + |
| 298 | +- Log per-execution path and status at INFO under `odoo.addons.spp_cel_domain`. |
| 299 | +- Optional Prometheus hooks later; not required for V2. |
| 300 | + |
| 301 | +--- |
| 302 | + |
| 303 | +## Acceptance Criteria |
| 304 | + |
| 305 | +- SQL fast path returns the same IDs as the previous Python path for supported comparisons. |
| 306 | +- Preview never calls providers; evaluate queues or refreshes as specified. |
| 307 | +- No result truncation; no silent stale returns when previewing. |
| 308 | +- Record rules remain enforced (no direct SQL leaks). |
| 309 | +- New index is created automatically; no partial index on `NOW()` is introduced. |
| 310 | + |
| 311 | +--- |
| 312 | + |
| 313 | +## Developer Notes & Edge Cases |
| 314 | + |
| 315 | +- Type handling: Only run numeric casts when `jsonb_typeof(value_json)='number'` or value is clearly numeric. |
| 316 | + String comparisons use `::text` equality/inequality only in V2. |
| 317 | +- Errors/missing: Exclude `error_code` rows; treat `NULL` as non-match. |
| 318 | +- Multi-company: Always filter by `company_id` in the subquery; outer `search()` further enforces company |
| 319 | + rules. |
| 320 | +- Params: Keep `params_hash` in all lookups; CEL V2 defaults to empty string unless translator provides |
| 321 | + params. |
| 322 | +- Provider: Prefer registry `provider` label to match cached rows; default to metric name. |
| 323 | +- Thresholds: Use `async_threshold` to decide between synchronous refresh and queueing in evaluate mode. |
| 324 | + |
| 325 | +--- |
| 326 | + |
| 327 | +## Appendix A — Example SQL and Domains |
| 328 | + |
| 329 | +Domain (numeric `>= 85`): |
| 330 | + |
| 331 | +``` |
| 332 | +[('id', 'inselect', (""" |
| 333 | +SELECT DISTINCT fv.subject_id |
| 334 | +FROM openspp_feature_value fv |
| 335 | +WHERE fv.company_id = %(company_id)s |
| 336 | + AND fv.metric = %(metric)s |
| 337 | + AND fv.subject_model = %(subject_model)s |
| 338 | + AND fv.period_key = %(period_key)s |
| 339 | + AND fv.provider = %(provider)s |
| 340 | + AND fv.params_hash = %(params_hash)s |
| 341 | + AND fv.error_code IS NULL |
| 342 | + AND (fv.expires_at IS NULL OR fv.expires_at > NOW()) |
| 343 | + AND jsonb_typeof(fv.value_json) = 'number' |
| 344 | + AND (fv.value_json::numeric) >= %(rhs)s |
| 345 | +""", { |
| 346 | + 'company_id': 1, |
| 347 | + 'metric': 'education.attendance_pct', |
| 348 | + 'subject_model': 'res.partner', |
| 349 | + 'period_key': '2024-09', |
| 350 | + 'provider': 'education.attendance_pct', |
| 351 | + 'params_hash': '', |
| 352 | + 'rhs': 85, |
| 353 | +}))] |
| 354 | +``` |
| 355 | + |
| 356 | +--- |
| 357 | + |
| 358 | +## Appendix B — Task Checklist (copy/paste) |
| 359 | + |
| 360 | +- [ ] Add index in `openspp_metrics._ensure_indexes()`. |
| 361 | +- [ ] Add helpers in `cel.executor`: `_metric_registry_info`, `_metric_cache_status_sql`, |
| 362 | + `_metric_inselect_sql`. |
| 363 | +- [ ] Update `_exec_metric` with preview gating, preflight, SQL fast path, and evaluate async/refresh logic. |
| 364 | +- [ ] Enrich `metrics_info` with path/status for Explain. |
| 365 | +- [ ] Add unit tests: numeric, string, preflight status. |
| 366 | +- [ ] Add integration tests: preview gating, evaluate small/large cohorts. |
| 367 | +- [ ] Verify record rules by a restricted user in a test. |
| 368 | + |
| 369 | +--- |
| 370 | + |
| 371 | +End of V2 |
0 commit comments