fsanyoto commited on
Commit
c92b0aa
·
verified ·
1 Parent(s): 8bbb700

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "current": "ddcde31",
3
  "releases": [
4
  {
5
  "version": "v75",
 
1
  {
2
+ "current": "2ae4569",
3
  "releases": [
4
  {
5
  "version": "v75",
VERSION CHANGED
@@ -1 +1 @@
1
- ddcde31
 
1
+ 2ae4569
api/routes_admin.py CHANGED
@@ -2091,8 +2091,13 @@ def _confines_to_one_bu(tree):
2091
  return any(kids) if node.get("conj") == "or" else all(kids)
2092
  if node.get("colId") != "dba":
2093
  return True # every other condition: assume satisfied
2094
- want = str(node.get("value") or "").strip().lower()
2095
  op = node.get("op")
 
 
 
 
 
 
2096
  if op == "eq":
2097
  return brand.lower() == want
2098
  if op == "neq":
@@ -2107,6 +2112,8 @@ def _confines_to_one_bu(tree):
2107
  return True
2108
  return True # an op that cannot judge a brand does not confine
2109
 
 
 
2110
  nodes, conj = (tree.get("nodes") or []), tree.get("conj", "and")
2111
  root = {"conj": conj, "children": nodes}
2112
  admitted = {b for b in ("Fisch", "Royal", "Both") if admits(root, b)}
 
2091
  return any(kids) if node.get("conj") == "or" else all(kids)
2092
  if node.get("colId") != "dba":
2093
  return True # every other condition: assume satisfied
 
2094
  op = node.get("op")
2095
+ if op in fe.MULTI_VALUE_OPS:
2096
+ # HOTFIX 2026-09-23: `dba is any of [Royal]` is the shape the condition builder writes
2097
+ # now, and `perm_scope` already reads it. Falling to "cannot judge" here made a save
2098
+ # that KEPT the BU condition read as one that removed it, and refused it as bu_widening.
2099
+ return fe._match_multi_value(op, brand, fe.parse_filter_values(node.get("values")))
2100
+ want = str(node.get("value") or "").strip().lower()
2101
  if op == "eq":
2102
  return brand.lower() == want
2103
  if op == "neq":
 
2112
  return True
2113
  return True # an op that cannot judge a brand does not confine
2114
 
2115
+ from harness import filter_eval as fe
2116
+
2117
  nodes, conj = (tree.get("nodes") or []), tree.get("conj", "and")
2118
  root = {"conj": conj, "children": nodes}
2119
  admitted = {b for b in ("Fisch", "Royal", "Both") if admits(root, b)}
api/routes_connected_tables.py CHANGED
@@ -62,6 +62,8 @@ def connected_table_rows(table_key: str,
62
  sorts: str = Query(default=None),
63
  search: str = Query(default=None),
64
  related: str = Query(default=None),
 
 
65
  session: Session = Depends(require_session)):
66
  """ONE WINDOW over a connected grid — `{fields, rows, total, totalUnfiltered, offset, limit,
67
  limits, identity, recordsMutable}`, whichever connector the rows come from.
@@ -89,4 +91,5 @@ def connected_table_rows(table_key: str,
89
  import routes_odoo_tables
90
  return routes_odoo_tables.odoo_table_rows(
91
  table_key, offset=offset, limit=limit, filters=filters, filterConj=filterConj,
92
- sorts=sorts, search=search, related=related, session=session)
 
 
62
  sorts: str = Query(default=None),
63
  search: str = Query(default=None),
64
  related: str = Query(default=None),
65
+ groupBy: str = Query(default=None),
66
+ groupKey: str = Query(default=None),
67
  session: Session = Depends(require_session)):
68
  """ONE WINDOW over a connected grid — `{fields, rows, total, totalUnfiltered, offset, limit,
69
  limits, identity, recordsMutable}`, whichever connector the rows come from.
 
91
  import routes_odoo_tables
92
  return routes_odoo_tables.odoo_table_rows(
93
  table_key, offset=offset, limit=limit, filters=filters, filterConj=filterConj,
94
+ sorts=sorts, search=search, related=related, groupBy=groupBy, groupKey=groupKey,
95
+ session=session)
api/routes_odoo_tables.py CHANGED
@@ -22,6 +22,7 @@ import base64
22
  import hashlib
23
  import hmac
24
  import json
 
25
  import time
26
  from contextlib import contextmanager
27
 
@@ -250,7 +251,8 @@ def odoo_tables_status(brief: bool = Query(False),
250
  else:
251
  n = -1 # unknown, and never reported as zero
252
  mirror_refreshed = mirror_stamp(
253
- spec or {}, cur=cur, table_key=key, rt=session.runtime)
 
254
  except Exception: # noqa: BLE001
255
  n = -1
256
  connection_id = str(((table.get("connector") or {}).get("connectionId")
@@ -2301,6 +2303,155 @@ def _views_as_cohorts(tree, table_key, session, spec, cols, base_where, wall_par
2301
  return tree, sets
2302
 
2303
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2304
  def _may_see_view(session, vid, store):
2305
  """May this caller open that saved view? The same predicate the view rail asks.
2306
 
@@ -2541,8 +2692,12 @@ def _compiled_read(table_key, session, *, filters=None, filterConj="and", sorts=
2541
  # the reader is held to, exactly as `viewSets` resolves inside the rows the client holds) and
2542
  # before `_leaf_cols` below, so the leaf never reaches the sentence that explains a column with
2543
  # no mirror expression. One place learns it; `/rows` and `/aggregates` share this compiler.
 
2544
  tree, cohort_sets = _views_as_cohorts(tree, table_key, session, spec, cols,
2545
  base_where, wall_params, cur, limits)
 
 
 
2546
 
2547
  # ── the predicate, pushed down ────────────────────────────────────────────────────────────
2548
  # ⛔ `_PSEUDO_COLS` is subtracted BEFORE the missing-column test. `__cohort__` and `__view__`
@@ -2667,8 +2822,12 @@ def _materialised_read(table_key, session, query, related):
2667
  "cols": bindings, "where": None}
2668
  cols = _filter_columns(spec, fields)
2669
  limits = list(payload.get("limits") or [])
 
2670
  tree, cohorts = _views_as_cohorts(query["filters"], table_key, session, spec, cols,
2671
  None, [], cur, limits)
 
 
 
2672
  missing = _leaf_cols(tree) - _PSEUDO_COLS - set(cols)
2673
  if missing:
2674
  raise err(400, "filter_unsupported", "A filter names a column unavailable to this account.")
@@ -2689,7 +2848,42 @@ def _materialised_read(table_key, session, query, related):
2689
  "frm": {"table": "pinned_rows"}, "limits": limits, "payload": payload}
2690
 
2691
 
2692
- def _materialised_window(table_key, session, offset, limit, filters, filterConj, sorts, search, related):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2693
  from harness import datastore
2694
 
2695
  query = _selection_query({"filters": _json_arg(filters, "filters"), "filterConj": filterConj,
@@ -2697,8 +2891,13 @@ def _materialised_window(table_key, session, offset, limit, filters, filterConj,
2697
  with _materialised_read(table_key, session, query, related) as read:
2698
  spec = read["spec"]
2699
  order = _fs().compile_order_by(query["sorts"], read["cols"], tiebreak_sql=spec["id"])
2700
- win = datastore.window(select=f'{spec["id"]} AS pid', where=read["where"],
2701
- params=tuple(read["params"]), order_by=order or spec["id"],
 
 
 
 
 
2702
  offset=offset, limit=limit or None, cur=read["cur"], **read["frm"])
2703
  payload = read["payload"]
2704
  by_id = {int(row["pid"]): row for row in payload["rows"]}
@@ -2721,6 +2920,8 @@ def odoo_table_rows(table_key: str,
2721
  sorts: str = Query(default=None),
2722
  search: str = Query(default=None),
2723
  related: str = Query(default=None),
 
 
2724
  session: Session = Depends(require_session)):
2725
  """ONE WINDOW over a connected grid, read straight from the mirror (contract C2).
2726
 
@@ -2751,7 +2952,7 @@ def odoo_table_rows(table_key: str,
2751
 
2752
  if _materialised_table(table_key):
2753
  return _materialised_window(table_key, session, offset, limit, filters, filterConj,
2754
- sorts, search, related)
2755
 
2756
  # ⛔⛔ ONE COMPILER, AND THE AGGREGATES DOOR CALLS THE SAME ONE. The permission wall, the
2757
  # hidden-field closure, the user predicate and the search all live in `_compiled_read` above,
@@ -2765,6 +2966,10 @@ def odoo_table_rows(table_key: str,
2765
  cols, limits, frm = read["cols"], read["limits"], read["frm"]
2766
  base_where, wall_params = read["base_where"], read["wall_params"]
2767
  where, params, sort_spec = read["where"], read["params"], read["sort_spec"]
 
 
 
 
2768
 
2769
  # ── the order, made TOTAL ─────────────────────────────────────────────────────────────────
2770
  # ⛔ `tiebreak_sql` is not optional here: without a total order, LIMIT/OFFSET may return one
@@ -2803,7 +3008,7 @@ def odoo_table_rows(table_key: str,
2803
  # ⭐ D-155 — the freshness stamp rides the SAME builder, so both read-through doors answer the
2804
  # `refreshed` column identically instead of one of them leaving it blank.
2805
  rows_src = _pool_from_window(spec, win,
2806
- stamp=mirror_stamp(spec, cur, table_key,
2807
  session.runtime))
2808
  overlays = {str(r["pid"]): {k: v for k, v in r.items() if k != "pid"} for r in rows_src}
2809
 
@@ -3167,7 +3372,7 @@ def odoo_table_aggregates(table_key: str, body: dict = Body(default=None),
3167
  return body_out
3168
 
3169
 
3170
- def mirror_stamp(spec, cur=None, table_key="", rt=None):
3171
  """⭐ D-155 — WHEN THIS READ-THROUGH GRID'S DATA WAS LAST RECONCILED AGAINST ODOO, as a date.
3172
 
3173
  ⛔ THE COLUMN EXISTED AND THE BINDING DID NOT, which is the whole of D-155. Every Odoo table
@@ -3212,9 +3417,12 @@ def mirror_stamp(spec, cur=None, table_key="", rt=None):
3212
  # the materialised carve-out above, made structural. ⚠ Fail-QUIET to `""`: when we cannot
3213
  # tell whether this grid stores rows, the safe answer is the behaviour that shipped (blank),
3214
  # never a stamp that might overwrite a per-row one.
 
 
 
3215
  if table_key:
3216
  try:
3217
- if _ut().materialises(str(table_key), st=rt):
3218
  return ""
3219
  except Exception: # noqa: BLE001
3220
  return ""
@@ -3331,7 +3539,11 @@ def whole_pool(table_key, cur=None, rt=None):
3331
  f"{table_key}: {win['total']:,} rows is more than one {datastore.WINDOW_MAX:,}-row "
3332
  f"window, and this database no longer stores rows in the tenant document; it can "
3333
  f"only be read a page at a time (`/odoo-tables/{table_key}/rows`)")
3334
- return _pool_from_window(spec, win, stamp=mirror_stamp(spec, cur, table_key, rt))
 
 
 
 
3335
 
3336
 
3337
  def _fe():
 
22
  import hashlib
23
  import hmac
24
  import json
25
+ import math
26
  import time
27
  from contextlib import contextmanager
28
 
 
251
  else:
252
  n = -1 # unknown, and never reported as zero
253
  mirror_refreshed = mirror_stamp(
254
+ spec or {}, cur=cur, table_key=key, rt=session.runtime,
255
+ defn=(table if isinstance(table, dict) and table else None))
256
  except Exception: # noqa: BLE001
257
  n = -1
258
  connection_id = str(((table.get("connector") or {}).get("connectionId")
 
2303
  return tree, sets
2304
 
2305
 
2306
+ def _ranks_as_cohorts(tree, conj, spec, cols, base_where, wall_params, cur, cohort_sets,
2307
+ had_cohort, today, limits=None):
2308
+ """Resolve every ACTIVE rank leaf (Top N, quartile, above average ...) into a synthetic
2309
+ `__cohort__` leaf over the ids it selects. `(tree, cohort_sets)`.
2310
+
2311
+ A rank is a property of the SET, so `filter_sql` refuses it at row grain. The set is answered
2312
+ here the way the client answers it: the residue (every non-rank condition) under the wall is
2313
+ the domain, and `filter_eval.resolve_rank_sets` (the Python port of the client's set pass,
2314
+ ties by ascending pid) picks the members. Only the id and the ranked columns are read, uncapped.
2315
+ """
2316
+ fe = _fe()
2317
+ leaves = fe._rank_leaves(tree or [], cols)
2318
+ if not leaves:
2319
+ return tree, cohort_sets
2320
+ if had_cohort:
2321
+ raise err(400, "filter_unsupported",
2322
+ "a condition on cohort membership cannot be evaluated on this database's live "
2323
+ "connection, because a cohort is resolved from this tenant's own records rather "
2324
+ "than from the connection. Filter on a saved view instead, or open this "
2325
+ "database's stored copy")
2326
+ residue = fe._strip_rank_leaves(tree)
2327
+ try:
2328
+ pred = _fs().compile_filter_tree(residue, conj=conj, columns=cols, id_sql=spec["id"],
2329
+ today=today, cohort_sets=cohort_sets)
2330
+ except ValueError as exc:
2331
+ raise err(400, "filter_unsupported", str(exc))
2332
+ if pred is not None and pred.uses_aggregate:
2333
+ raise err(400, "filter_unsupported",
2334
+ "This condition cannot be evaluated for individual rows.")
2335
+ where = base_where
2336
+ params = list(wall_params)
2337
+ if pred is not None:
2338
+ where = f"({where}) AND {pred.sql}" if where else pred.sql
2339
+ params.extend(pred.params)
2340
+ frm_body = spec["from_sql"] if spec.get("from_sql") else spec["table"]
2341
+ answers = {}
2342
+ python_leaves = []
2343
+ for n in leaves:
2344
+ got = _rank_ids_sql(n, cols, spec["id"], frm_body, where, params, cur)
2345
+ if got is None:
2346
+ python_leaves.append(n)
2347
+ else:
2348
+ answers[id(n)] = got
2349
+ if python_leaves:
2350
+ # A GROUP-scoped rank (rare on this door) keeps the reference resolver: read the id and
2351
+ # the ranked columns once, uncapped, and let `resolve_rank_sets` answer it.
2352
+ ranked = sorted({str(n.get("colId")) for n in python_leaves if n.get("colId") in cols})
2353
+ select = ", ".join([spec["id"]] + [cols[c]["sql"] for c in ranked])
2354
+ sql = f"SELECT {select} FROM {frm_body}" + (f" WHERE {where}" if where else "")
2355
+ rows = []
2356
+ for r in cur.execute(sql, params).fetchall():
2357
+ if not r or r[0] is None:
2358
+ continue
2359
+ row = {"pid": int(r[0])}
2360
+ for i, c in enumerate(ranked, start=1):
2361
+ row[c] = r[i]
2362
+ rows.append(row)
2363
+ resolved = fe.resolve_rank_sets({"nodes": python_leaves, "conj": "and"}, rows, cols)
2364
+ for n in python_leaves:
2365
+ answers[id(n)] = sorted(resolved.sets.get(fe._rank_key(n)) or ())
2366
+ sets = dict(cohort_sets or {})
2367
+ counter = [0]
2368
+ wanted = {id(n) for n in leaves}
2369
+
2370
+ def rewrite(nodes):
2371
+ out = []
2372
+ for n in (nodes or []):
2373
+ if isinstance(n, dict) and isinstance(n.get("children"), list):
2374
+ out.append(dict(n, children=rewrite(n["children"])))
2375
+ elif isinstance(n, dict) and id(n) in wanted:
2376
+ counter[0] += 1
2377
+ key = "__rank_%d__" % counter[0]
2378
+ got = answers.get(id(n))
2379
+ sets[key] = got if got is not None else []
2380
+ if (limits is not None and isinstance(got, list)
2381
+ and len(got) >= _PIN_REPORT_AT):
2382
+ limits.append({
2383
+ "subject": str(n.get("colId") or ""), "effect": "slow",
2384
+ "cause": f"this ranking condition selects {len(got):,} rows, and "
2385
+ f"each page of this database names every one of them in the "
2386
+ f"query that narrows it",
2387
+ "recommendation": "rank a smaller slice (a lower Top N or percentage), "
2388
+ "or add a condition beside it"})
2389
+ out.append({"colId": "__cohort__", "op": "anyOf", "value": key})
2390
+ else:
2391
+ out.append(n)
2392
+ return out
2393
+
2394
+ return rewrite(tree), sets
2395
+
2396
+
2397
+ def _rank_ids_sql(leaf, cols, id_sql, frm_body, where, params, cur):
2398
+ """One GLOBAL rank leaf as SQL: a `SqlMembership` selecting its ids, or None for the resolver.
2399
+
2400
+ Measured 2026-09-23: `resolve_rank_sets` over 256,542 order lines took 3.6 s in Python, and a
2401
+ paged grid pays it on every page; as a SQL window the same answer is tens of milliseconds,
2402
+ and as a subquery it never becomes a six-figure IN list. Semantics are the resolver's, line
2403
+ for line (parity-tested over all eight ops with ties and blanks): blank or non-finite values
2404
+ are ABSENT, ties break by ascending id in both directions, a bound outside the builder's
2405
+ whole-number range is unanswerable (empty), and a quartile or decile of fewer rows than
2406
+ buckets is empty. The domain's count and mean are read once here and inlined as literals.
2407
+ """
2408
+ fe = _fe()
2409
+ Sql = _fs().SqlMembership
2410
+ empty = Sql("SELECT NULL WHERE FALSE", [])
2411
+ scope, _field = fe._rank_scope(leaf, None)
2412
+ if scope != "global":
2413
+ return None
2414
+ col = cols.get(leaf.get("colId")) or {}
2415
+ if col.get("type") not in fe.NUMERIC_TYPES:
2416
+ return empty
2417
+ v = f"TRY_CAST({col['sql']} AS DOUBLE)"
2418
+ dom = (f"SELECT {id_sql} AS pid, {v} AS v FROM {frm_body} WHERE "
2419
+ + (f"({where}) AND " if where else "") + f"{v} IS NOT NULL AND isfinite({v})")
2420
+ params = list(params)
2421
+ op = leaf.get("op")
2422
+ if op in ("topN", "bottomN"):
2423
+ bound = fe._rank_bound(leaf.get("value"), 1, 10000)
2424
+ if bound is None:
2425
+ return empty
2426
+ direction = "DESC" if op == "topN" else "ASC"
2427
+ return Sql(f"SELECT pid FROM ({dom}) d ORDER BY v {direction}, pid ASC LIMIT {bound}",
2428
+ params)
2429
+ count, total = cur.execute(f"SELECT count(*), sum(v) FROM ({dom}) d", params).fetchone()
2430
+ count = int(count or 0)
2431
+ if not count:
2432
+ return empty
2433
+ if op in ("inTopPct", "inBottomPct"):
2434
+ pct = fe._rank_bound(leaf.get("value"), 1, 100)
2435
+ if pct is None:
2436
+ return empty
2437
+ take = min(count, max(1, math.ceil(count * pct / 100)))
2438
+ direction = "DESC" if op == "inTopPct" else "ASC"
2439
+ return Sql(f"SELECT pid FROM ({dom}) d ORDER BY v {direction}, pid ASC LIMIT {take}",
2440
+ params)
2441
+ if op in ("aboveAvg", "belowAvg"):
2442
+ mean = float(total) / count
2443
+ cmp = ">" if op == "aboveAvg" else "<"
2444
+ return Sql(f"SELECT pid FROM ({dom}) d WHERE v {cmp} {mean!r}", params)
2445
+ if op in ("inQuartile", "inDecile"):
2446
+ buckets = 4 if op == "inQuartile" else 10
2447
+ wanted = fe._rank_bound(leaf.get("value"), 1, buckets)
2448
+ if wanted is None or count < buckets:
2449
+ return empty
2450
+ return Sql(f"SELECT pid FROM (SELECT pid, row_number() OVER (ORDER BY v ASC, pid ASC) - 1"
2451
+ f" AS idx FROM ({dom}) d) r WHERE least({buckets}, (idx * {buckets}) // {count}"
2452
+ f" + 1) = {int(wanted)}", params)
2453
+ return None
2454
+
2455
  def _may_see_view(session, vid, store):
2456
  """May this caller open that saved view? The same predicate the view rail asks.
2457
 
 
2692
  # the reader is held to, exactly as `viewSets` resolves inside the rows the client holds) and
2693
  # before `_leaf_cols` below, so the leaf never reaches the sentence that explains a column with
2694
  # no mirror expression. One place learns it; `/rows` and `/aggregates` share this compiler.
2695
+ _had_cohort = bool(_active_cohort_leaves(tree))
2696
  tree, cohort_sets = _views_as_cohorts(tree, table_key, session, spec, cols,
2697
  base_where, wall_params, cur, limits)
2698
+ tree, cohort_sets = _ranks_as_cohorts(
2699
+ tree, (filterConj if filterConj in ("and", "or") else "and"), spec, cols, base_where,
2700
+ wall_params, cur, cohort_sets, _had_cohort, _today(), limits)
2701
 
2702
  # ── the predicate, pushed down ────────────────────────────────────────────────────────────
2703
  # ⛔ `_PSEUDO_COLS` is subtracted BEFORE the missing-column test. `__cohort__` and `__view__`
 
2822
  "cols": bindings, "where": None}
2823
  cols = _filter_columns(spec, fields)
2824
  limits = list(payload.get("limits") or [])
2825
+ _had_cohort = bool(_active_cohort_leaves(query["filters"]))
2826
  tree, cohorts = _views_as_cohorts(query["filters"], table_key, session, spec, cols,
2827
  None, [], cur, limits)
2828
+ tree, cohorts = _ranks_as_cohorts(tree, query["filterConj"], spec, cols, None, [], cur,
2829
+ cohorts, _had_cohort,
2830
+ payload.get("today") or _today(), limits)
2831
  missing = _leaf_cols(tree) - _PSEUDO_COLS - set(cols)
2832
  if missing:
2833
  raise err(400, "filter_unsupported", "A filter names a column unavailable to this account.")
 
2848
  "frm": {"table": "pinned_rows"}, "limits": limits, "payload": payload}
2849
 
2850
 
2851
+ def _group_pin(cols, group_by, group_key):
2852
+ """`(sql, params)` narrowing a window to ONE group of `/aggregates`' grouping, or `(None, [])`.
2853
+
2854
+ HOTFIX 2026-09-23 (owner: "whatever is GROUPED we can add pagination per group"). A group's
2855
+ records page through this door, so the narrowing is the SAME expression `_aggregate_over`
2856
+ groups by (`filter_sql.group_sql`), never a client-built `eq` leaf: `_value_sql` lowercases
2857
+ text and rounds numbers, which would make a group's pages disagree with its count.
2858
+ `group_key` is the JSON of the key `/aggregates` put on the wire (`null` = the blank bucket).
2859
+ """
2860
+ # A plain-Python caller that omits the argument hands us FastAPI's `Query` sentinel, not
2861
+ # None (the `related` scar in `routes_connected_tables`), so anything but a string is "none".
2862
+ gcol = group_by.strip() if isinstance(group_by, str) else ""
2863
+ if not gcol:
2864
+ return None, []
2865
+ group_key = group_key if isinstance(group_key, str) else None
2866
+ gspec = cols.get(gcol)
2867
+ if gspec is None:
2868
+ raise err(400, "bad_group", "this column cannot be grouped on this database's live "
2869
+ "connection, or it is not visible to your account")
2870
+ try:
2871
+ key = json.loads(group_key) if group_key not in (None, "") else None
2872
+ except ValueError:
2873
+ raise err(400, "bad_group", "groupKey must be the JSON of a group key")
2874
+ gexpr = _fs().group_sql(gspec)
2875
+ if key is None:
2876
+ return f"({gexpr}) IS NULL", []
2877
+ if gspec["type"] in _fs().NUMERIC_TYPES:
2878
+ try:
2879
+ return f"({gexpr}) = ?", [float(key)]
2880
+ except (TypeError, ValueError):
2881
+ raise err(400, "bad_group", "groupKey must be a number for a number column")
2882
+ return f"({gexpr}) = ?", [str(key)]
2883
+
2884
+
2885
+ def _materialised_window(table_key, session, offset, limit, filters, filterConj, sorts, search, related,
2886
+ groupBy=None, groupKey=None):
2887
  from harness import datastore
2888
 
2889
  query = _selection_query({"filters": _json_arg(filters, "filters"), "filterConj": filterConj,
 
2891
  with _materialised_read(table_key, session, query, related) as read:
2892
  spec = read["spec"]
2893
  order = _fs().compile_order_by(query["sorts"], read["cols"], tiebreak_sql=spec["id"])
2894
+ where, params = read["where"], list(read["params"])
2895
+ gsql, gparams = _group_pin(read["cols"], groupBy, groupKey)
2896
+ if gsql:
2897
+ where = f"({where}) AND {gsql}" if where else gsql
2898
+ params.extend(gparams)
2899
+ win = datastore.window(select=f'{spec["id"]} AS pid', where=where,
2900
+ params=tuple(params), order_by=order or spec["id"],
2901
  offset=offset, limit=limit or None, cur=read["cur"], **read["frm"])
2902
  payload = read["payload"]
2903
  by_id = {int(row["pid"]): row for row in payload["rows"]}
 
2920
  sorts: str = Query(default=None),
2921
  search: str = Query(default=None),
2922
  related: str = Query(default=None),
2923
+ groupBy: str = Query(default=None),
2924
+ groupKey: str = Query(default=None),
2925
  session: Session = Depends(require_session)):
2926
  """ONE WINDOW over a connected grid, read straight from the mirror (contract C2).
2927
 
 
2952
 
2953
  if _materialised_table(table_key):
2954
  return _materialised_window(table_key, session, offset, limit, filters, filterConj,
2955
+ sorts, search, related, groupBy, groupKey)
2956
 
2957
  # ⛔⛔ ONE COMPILER, AND THE AGGREGATES DOOR CALLS THE SAME ONE. The permission wall, the
2958
  # hidden-field closure, the user predicate and the search all live in `_compiled_read` above,
 
2966
  cols, limits, frm = read["cols"], read["limits"], read["frm"]
2967
  base_where, wall_params = read["base_where"], read["wall_params"]
2968
  where, params, sort_spec = read["where"], read["params"], read["sort_spec"]
2969
+ _gsql, _gparams = _group_pin(cols, groupBy, groupKey)
2970
+ if _gsql:
2971
+ where = f"({where}) AND {_gsql}" if where else _gsql
2972
+ params = list(params) + list(_gparams)
2973
 
2974
  # ── the order, made TOTAL ─────────────────────────────────────────────────────────────────
2975
  # ⛔ `tiebreak_sql` is not optional here: without a total order, LIMIT/OFFSET may return one
 
3008
  # ⭐ D-155 — the freshness stamp rides the SAME builder, so both read-through doors answer the
3009
  # `refreshed` column identically instead of one of them leaving it blank.
3010
  rows_src = _pool_from_window(spec, win,
3011
+ stamp=mirror_stamp(spec, cur, table_key, defn=defn, rt=
3012
  session.runtime))
3013
  overlays = {str(r["pid"]): {k: v for k, v in r.items() if k != "pid"} for r in rows_src}
3014
 
 
3372
  return body_out
3373
 
3374
 
3375
+ def mirror_stamp(spec, cur=None, table_key="", rt=None, defn=None):
3376
  """⭐ D-155 — WHEN THIS READ-THROUGH GRID'S DATA WAS LAST RECONCILED AGAINST ODOO, as a date.
3377
 
3378
  ⛔ THE COLUMN EXISTED AND THE BINDING DID NOT, which is the whole of D-155. Every Odoo table
 
3417
  # the materialised carve-out above, made structural. ⚠ Fail-QUIET to `""`: when we cannot
3418
  # tell whether this grid stores rows, the safe answer is the behaviour that shipped (blank),
3419
  # never a stamp that might overwrite a per-row one.
3420
+ # HOTFIX 2026-09-23: `defn` is LENT by a caller already holding the definition. Without it
3421
+ # `materialises` falls through to a whole-document `user_tables` read, measured on staging
3422
+ # at ~3 s of every 50-row page of order lines (the `timing` phase `pool_and_stamp`).
3423
  if table_key:
3424
  try:
3425
+ if _ut().materialises(str(table_key), st=rt, defn=defn):
3426
  return ""
3427
  except Exception: # noqa: BLE001
3428
  return ""
 
3539
  f"{table_key}: {win['total']:,} rows is more than one {datastore.WINDOW_MAX:,}-row "
3540
  f"window, and this database no longer stores rows in the tenant document; it can "
3541
  f"only be read a page at a time (`/odoo-tables/{table_key}/rows`)")
3542
+ # HOTFIX 2026-09-23: this door serves only a table whose rows have LEFT the tenant document
3543
+ # (its docstring), so that fact is lent rather than re-derived: without `defn`,
3544
+ # `materialises` re-reads the whole `user_tables` document, ~3 s on the pg store.
3545
+ return _pool_from_window(spec, win, stamp=mirror_stamp(spec, cur, table_key, rt,
3546
+ defn={"readThrough": True}))
3547
 
3548
 
3549
  def _fe():
platform/harness/filter_sql.py CHANGED
@@ -157,6 +157,9 @@ _DATE_CMP = dict(_NUM_CMP)
157
  #: rather than WHERE; columns_used = colIds actually referenced in the emitted SQL (an
158
  #: always-true `1=1` branch references nothing, and must not force HAVING routing).
159
  Compiled = namedtuple('Compiled', 'sql params uses_aggregate columns_used')
 
 
 
160
 
161
 
162
  # --------------------------------------------------------------------------- value coercion
@@ -612,6 +615,10 @@ def _compile_cohort(rule, state):
612
 
613
  parts, params = [], []
614
  for ids in members:
 
 
 
 
615
  ids = [int(x) for x in ids]
616
  if not ids:
617
  parts.append('1=0')
 
157
  #: rather than WHERE; columns_used = colIds actually referenced in the emitted SQL (an
158
  #: always-true `1=1` branch references nothing, and must not force HAVING routing).
159
  Compiled = namedtuple('Compiled', 'sql params uses_aggregate columns_used')
160
+ #: HOTFIX 2026-09-23: a cohort set given as a SELECT of ids rather than a list. A server-side
161
+ #: rank answer (Top N, above average ...) over 256k rows is a subquery, never a 128k-id IN list.
162
+ SqlMembership = namedtuple('SqlMembership', 'sql params')
163
 
164
 
165
  # --------------------------------------------------------------------------- value coercion
 
615
 
616
  parts, params = [], []
617
  for ids in members:
618
+ if isinstance(ids, SqlMembership):
619
+ parts.append(f"COALESCE({id_sql} IN ({ids.sql}), FALSE)")
620
+ params.extend(ids.params)
621
+ continue
622
  ids = [int(x) for x in ids]
623
  if not ids:
624
  parts.append('1=0')
web/public/AIOS_DEPLOY_RECEIPT CHANGED
@@ -1 +1 @@
1
- bfcfb2eaaa52b19b592c33709f2420bf1e2e3d586045e5426581ad3050bd607a
 
1
+ b46d3eebd3f9a69647bdca398ddf00ca46448a0ac9f3a19e164fae625444f09c
web/src/customer-grid/CustomerGrid.tsx CHANGED
@@ -34,13 +34,14 @@ import { acceptsQueryPreview, routeQueryViewMutation } from "./queryPreview";
34
  // ⭐ WAVE 30 · W30-T42 (contract C2) — the WINDOWED grid's arithmetic, pure and node-run in
35
  // `verify_grid_ux.py`, because every one of these decisions is taken inside a callback where
36
  // only its own source text could otherwise be checked.
37
- import { WINDOW_ROWS, fetchAggregates, personalGridLayout } from "./apiBridge";
 
38
  // ⭐⭐ W50-T03 / CONTRACT C1 — the windowed aggregate's envelope. Lane F serves the route
39
  // (W50-T31); this side is written to C1's shape and degrades to the loaded window until it
40
  // lands, which is the done-when's own observable rather than a workaround.
41
  import type { AggregateResult } from "./apiBridge";
42
  import {
43
- EMPTY_WINDOW_PREDICATE, limitSummary, lockedRecordsNote, nextWindowOffset,
44
  windowedCapabilityNote, windowedFoldNote, windowPredicateKey,
45
  } from "./counts";
46
  // ⭐ W35-T29/T30 (C5) — the record star's client, and its own stylesheet imported HERE, by the
@@ -3631,6 +3632,18 @@ function CustomerGridSurface({
3631
  }),
3632
  [config.filters, config.filterConj, config.sorts, search]
3633
  );
 
 
 
 
 
 
 
 
 
 
 
 
3634
  const sentPredicate = useRef<string | null>(null);
3635
  useEffect(() => {
3636
  if (!serverWindowed) {
@@ -3649,6 +3662,7 @@ function CustomerGridSurface({
3649
  return;
3650
  }
3651
  sentPredicate.current = windowPredicate;
 
3652
  requestWindow(windowRequest(0));
3653
  }, [serverWindowed, windowPredicate, windowRequest, requestWindow]);
3654
 
@@ -3673,18 +3687,12 @@ function CustomerGridSurface({
3673
  const [canvasX, setCanvasX] = useState(0);
3674
  const onVisibleRegionChanged = useCallback(
3675
  (range: Rectangle, tx: number) => {
 
 
 
3676
  setCanvasX(Number.isFinite(tx) ? tx : 0);
3677
- if (!serverWindowed) return;
3678
- const offset = nextWindowOffset({
3679
- lastVisibleRow: range.y + range.height,
3680
- loaded: payload?.counts?.shown ?? 0,
3681
- matched: payload?.counts?.matched ?? 0,
3682
- limit: WINDOW_ROWS,
3683
- });
3684
- if (offset !== null) requestWindow(windowRequest(offset));
3685
  },
3686
- [serverWindowed, payload?.counts?.shown, payload?.counts?.matched, requestWindow,
3687
- windowRequest]
3688
  );
3689
 
3690
  // CG-8 — measure conditions, answered by the host as `{ruleId: pid[]}`. Converted to Sets
@@ -4077,7 +4085,9 @@ function CustomerGridSurface({
4077
  );
4078
  const summaryRequestKey = JSON.stringify(summaryRequest);
4079
  useEffect(() => {
4080
- if (!serverWindowed || !summaryRequestKey || summaryRequestKey === "[]") {
 
 
4081
  setServerAggs(null);
4082
  return;
4083
  }
@@ -4098,7 +4108,7 @@ function CustomerGridSurface({
4098
  is the server folding the whole predicate. Absent `groupBy` this is the table-wide
4099
  answer W50-T03 already asks for, byte for byte. */
4100
  ...(config.groupBy ? { groupBy: config.groupBy } : {}),
4101
- aggs: JSON.parse(summaryRequestKey) as { colId: string; agg: string; p?: number }[],
4102
  }).then((result) => {
4103
  if (live) setServerAggs(result);
4104
  });
@@ -4223,14 +4233,89 @@ function CustomerGridSurface({
4223
  * is not available on this table. Summary mode is the ONE state whose intended shape is
4224
  * header-only, so it is the one state that may take this source.
4225
  */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4226
  const serverGroupRows = useMemo(() => {
4227
- if (!serverWindowed || !config.groupBy || !groupSummaryOn) return null;
4228
  const groups = serverAggs?.groups;
4229
  if (!groups || !groups.length) return null;
4230
- return serverGroupHeaders(
4231
  groups, fields, summaryMap, serverAggs.aggregates, serverAggs.totalRows
4232
  );
4233
- }, [serverWindowed, config.groupBy, serverAggs, fields, summaryMap]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4234
  /** R6's SECOND SENTENCE, on the client side of the wire: the limits D's route DECLARED on this
4235
  * response. Received and painted nothing = the limit is silent again, one layer further out. */
4236
  // ⭐ W32-T03: `counts` rides along so the clamped-window clause can say "Showing 5,000 of
@@ -5177,7 +5262,7 @@ function CustomerGridSurface({
5177
  // Do not paint loaded rows as though they were the whole update. Invalidate every cached
5178
  // window and request a fresh one, then state exactly what the server says it wrote.
5179
  dropTableRowsCache(scope);
5180
- requestWindow(windowRequest(0));
5181
  signal(ROWS_STALE_EVENT);
5182
  setServerFilteredSelection(null);
5183
  clearSelection();
@@ -6117,6 +6202,17 @@ function CustomerGridSurface({
6117
  toggleFold(row.groupKey);
6118
  return;
6119
  }
 
 
 
 
 
 
 
 
 
 
 
6120
  // W40-T30 — the virtual "Go" cell's tap door stood here, matched by POSITION on the index
6121
  // one past the persisted columns. Owner instruction 27 removed it; the transit link is a
6122
  // pre-set URL field now, so it opens through the ordinary url-cell branch below, which is
@@ -9420,8 +9516,10 @@ function CustomerGridSurface({
9420
  const onExpandAllGroups = useCallback(() => {
9421
  const keys = new Set<string>();
9422
  for (const vr of visibleRows) if (vr.kind === "group-header") keys.add(vr.groupKey);
 
 
9423
  setFold(keys);
9424
- }, [visibleRows, setFold]);
9425
  /**
9426
  * Item 7 (C-TS) — the pid set the time series asks about: exactly the rows the current
9427
  * filter kept, so the panel and the toolbar count can never disagree about "who".
@@ -10554,7 +10652,7 @@ function CustomerGridSurface({
10554
  sortsLocked={activeSortsLocked}
10555
  onCopyToChange={() => duplicateView(activeViewId)}
10556
  // the toolbar must not advertise a grouping the pipeline is not applying
10557
- groupBy={serverWindowed ? null : config.groupBy}
10558
  onGroupBy={(groupBy) => updateConfig({ ...config, groupBy })}
10559
  onCollapseAllGroups={onCollapseAllGroups}
10560
  onExpandAllGroups={onExpandAllGroups}
@@ -10854,15 +10952,14 @@ function CustomerGridSurface({
10854
  `cg-app-launch-state`: route-app.css:28-31 hides the Data toolbar's controls on
10855
  `.cg-main:has(.cg-app-launch-state)`, so borrowing that class would flash the whole toolbar
10856
  away on every rail click. Only the bar classes are reused; they carry size and the pulse. */}
 
 
 
 
10857
  {!applicationLaunching && viewSwitchPending && (
10858
- <div className="cg-view-pending" role="status" aria-label="Loading view"
10859
- style={{ display: "grid", alignContent: "start", gap: 12, padding: 24 }}>
10860
- <span className="cg-app-launch-line is-wide" />
10861
- <span className="cg-app-launch-line" />
10862
- <span className="cg-app-launch-grid" />
10863
- </div>
10864
  )}
10865
- {displayMode === "grid" && !applicationLaunching && !viewSwitchPending && (
10866
  <>
10867
  <DataEditor
10868
  ref={gridRef}
@@ -11671,6 +11768,19 @@ function CustomerGridSurface({
11671
  />
11672
  )}
11673
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
11674
  {/* ⭐ W30-T42 — the WINDOWED grid's honest footnotes, in the strip that already exists
11675
  for exactly this job. Reuses `.cg-more` / `.cg-more-note` rather than adding a
11676
  class: `index.css` is another lane's fence this wave, and this needs no new pixel.
 
34
  // ⭐ WAVE 30 · W30-T42 (contract C2) — the WINDOWED grid's arithmetic, pure and node-run in
35
  // `verify_grid_ux.py`, because every one of these decisions is taken inside a callback where
36
  // only its own source text could otherwise be checked.
37
+ import { WINDOW_ROWS, fetchAggregates, fetchTableWindow, personalGridLayout } from "./apiBridge";
38
+ import { GridPager } from "./GridPager";
39
  // ⭐⭐ W50-T03 / CONTRACT C1 — the windowed aggregate's envelope. Lane F serves the route
40
  // (W50-T31); this side is written to C1's shape and degrades to the loaded window until it
41
  // lands, which is the done-when's own observable rather than a workaround.
42
  import type { AggregateResult } from "./apiBridge";
43
  import {
44
+ EMPTY_WINDOW_PREDICATE, limitSummary, lockedRecordsNote,
45
  windowedCapabilityNote, windowedFoldNote, windowPredicateKey,
46
  } from "./counts";
47
  // ⭐ W35-T29/T30 (C5) — the record star's client, and its own stylesheet imported HERE, by the
 
3632
  }),
3633
  [config.filters, config.filterConj, config.sorts, search]
3634
  );
3635
+ /* ⭐⭐ HOTFIX 2026-09-23 — THE PAGE. The owner revoked the virtualise-only ruling: *"I want
3636
+ fucking either pagination or next page and only load 50 at a time"*. A read-through grid now
3637
+ holds ONE page of `WINDOW_ROWS` rows at `pageOffset`, moved by the pager under the canvas.
3638
+ A predicate change returns to the first page. */
3639
+ const [pageOffset, setPageOffset] = useState(0);
3640
+ const pageOffsetRef = useRef(0);
3641
+ pageOffsetRef.current = pageOffset;
3642
+ const goToPage = useCallback((offset: number) => {
3643
+ const next = Math.max(0, Math.floor(offset));
3644
+ setPageOffset(next);
3645
+ requestWindow(windowRequest(next));
3646
+ }, [requestWindow, windowRequest]);
3647
  const sentPredicate = useRef<string | null>(null);
3648
  useEffect(() => {
3649
  if (!serverWindowed) {
 
3662
  return;
3663
  }
3664
  sentPredicate.current = windowPredicate;
3665
+ setPageOffset(0);
3666
  requestWindow(windowRequest(0));
3667
  }, [serverWindowed, windowPredicate, windowRequest, requestWindow]);
3668
 
 
3687
  const [canvasX, setCanvasX] = useState(0);
3688
  const onVisibleRegionChanged = useCallback(
3689
  (range: Rectangle, tx: number) => {
3690
+ // HOTFIX 2026-09-23: a read-through grid PAGES (the pager under the canvas) instead of
3691
+ // appending on scroll, so the visible region only drives the summary bar's track now.
3692
+ void range;
3693
  setCanvasX(Number.isFinite(tx) ? tx : 0);
 
 
 
 
 
 
 
 
3694
  },
3695
+ []
 
3696
  );
3697
 
3698
  // CG-8 — measure conditions, answered by the host as `{ruleId: pid[]}`. Converted to Sets
 
4085
  );
4086
  const summaryRequestKey = JSON.stringify(summaryRequest);
4087
  useEffect(() => {
4088
+ // HOTFIX 2026-09-23: a grouped windowed table needs its groups even when no column carries
4089
+ // a summary, because the groups ARE the canvas now (per-group paging).
4090
+ if (!serverWindowed || ((!summaryRequestKey || summaryRequestKey === "[]") && !config.groupBy)) {
4091
  setServerAggs(null);
4092
  return;
4093
  }
 
4108
  is the server folding the whole predicate. Absent `groupBy` this is the table-wide
4109
  answer W50-T03 already asks for, byte for byte. */
4110
  ...(config.groupBy ? { groupBy: config.groupBy } : {}),
4111
+ aggs: JSON.parse(summaryRequestKey || "[]") as { colId: string; agg: string; p?: number }[],
4112
  }).then((result) => {
4113
  if (live) setServerAggs(result);
4114
  });
 
4233
  * is not available on this table. Summary mode is the ONE state whose intended shape is
4234
  * header-only, so it is the one state that may take this source.
4235
  */
4236
+ /* ⭐⭐ HOTFIX 2026-09-23: GROUPED PAGING ON A READ-THROUGH TABLE. Owner: *"whatever is GROUPED
4237
+ we can add pagination per group as well. So we only show the total for each group when its
4238
+ metric or formula or numeric but to show the record we need to add pagination."* The groups,
4239
+ their counts and their totals come from `/aggregates` over the WHOLE predicate; an OPEN group
4240
+ pages its own records 50 at a time through `/rows?groupBy&groupKey`, whose narrowing is the
4241
+ server's grouping expression, so a group's pages always add up to its count. */
4242
+ const groupKeyRaw = useMemo(() => {
4243
+ const m = new Map<string, string | number | null>();
4244
+ for (const g of serverAggs?.groups ?? []) {
4245
+ const raw = g.key as unknown as string | number | null;
4246
+ m.set(raw == null ? "" : String(raw), raw);
4247
+ }
4248
+ return m;
4249
+ }, [serverAggs]);
4250
+ const [groupPages, setGroupPages] = useState<
4251
+ ReadonlyMap<string, { offset: number; rows: Row[]; pending: boolean }>
4252
+ >(() => new Map());
4253
+ const groupPageSeq = useRef(0);
4254
+ useEffect(() => {
4255
+ groupPageSeq.current += 1;
4256
+ setGroupPages(new Map());
4257
+ }, [serverWindowed, windowPredicate, config.groupBy, relatedPin]);
4258
+ const loadGroupPage = useCallback((key: string, offset: number) => {
4259
+ const by = config.groupBy;
4260
+ if (!by || !groupKeyRaw.has(key)) return;
4261
+ const seq = groupPageSeq.current;
4262
+ setGroupPages((prev) => {
4263
+ const next = new Map(prev);
4264
+ next.set(key, { offset, rows: prev.get(key)?.rows ?? [], pending: true });
4265
+ return next;
4266
+ });
4267
+ void fetchTableWindow(scope, {
4268
+ ...windowRequest(offset),
4269
+ related: relatedPin,
4270
+ group: { by, key: groupKeyRaw.get(key) ?? null },
4271
+ }).then((page) => {
4272
+ if (seq !== groupPageSeq.current) return;
4273
+ setGroupPages((prev) => {
4274
+ const cur = prev.get(key);
4275
+ if (cur && cur.offset !== offset) return prev;
4276
+ const next = new Map(prev);
4277
+ next.set(key, { offset, rows: page?.rows ?? cur?.rows ?? [], pending: false });
4278
+ return next;
4279
+ });
4280
+ });
4281
+ }, [config.groupBy, groupKeyRaw, scope, windowRequest, relatedPin]);
4282
+ useEffect(() => {
4283
+ if (!serverWindowed || !config.groupBy || groupSummaryOn) return;
4284
+ for (const key of expanded) {
4285
+ if (groupKeyRaw.has(key) && !groupPages.has(key)) loadGroupPage(key, 0);
4286
+ }
4287
+ }, [serverWindowed, config.groupBy, groupSummaryOn, expanded, groupKeyRaw, groupPages,
4288
+ loadGroupPage]);
4289
  const serverGroupRows = useMemo(() => {
4290
+ if (!serverWindowed || !config.groupBy) return null;
4291
  const groups = serverAggs?.groups;
4292
  if (!groups || !groups.length) return null;
4293
+ const heads = serverGroupHeaders(
4294
  groups, fields, summaryMap, serverAggs.aggregates, serverAggs.totalRows
4295
  );
4296
+ if (groupSummaryOn) return heads;
4297
+ const out: VisibleRow[] = [];
4298
+ for (const h of heads) {
4299
+ if (h.kind !== "group-header") continue;
4300
+ const raw = h.groupKey as unknown as string | number | null;
4301
+ const key = raw == null ? "" : String(raw);
4302
+ const open = expanded.has(key);
4303
+ out.push({ ...h, groupKey: key, collapsed: !open });
4304
+ if (!open) continue;
4305
+ const page = groupPages.get(key);
4306
+ for (const record of page?.rows ?? []) out.push({ kind: "data", record });
4307
+ out.push({
4308
+ kind: "group-footer",
4309
+ groupKey: key,
4310
+ aggs: h.aggs,
4311
+ ...(h.count > WINDOW_ROWS
4312
+ ? { page: { offset: page?.offset ?? 0, total: h.count, size: WINDOW_ROWS } }
4313
+ : {}),
4314
+ });
4315
+ }
4316
+ return out;
4317
+ }, [serverWindowed, config.groupBy, serverAggs, fields, summaryMap, groupSummaryOn, expanded,
4318
+ groupPages]);
4319
  /** R6's SECOND SENTENCE, on the client side of the wire: the limits D's route DECLARED on this
4320
  * response. Received and painted nothing = the limit is silent again, one layer further out. */
4321
  // ⭐ W32-T03: `counts` rides along so the clamped-window clause can say "Showing 5,000 of
 
5262
  // Do not paint loaded rows as though they were the whole update. Invalidate every cached
5263
  // window and request a fresh one, then state exactly what the server says it wrote.
5264
  dropTableRowsCache(scope);
5265
+ requestWindow(windowRequest(pageOffsetRef.current));
5266
  signal(ROWS_STALE_EVENT);
5267
  setServerFilteredSelection(null);
5268
  clearSelection();
 
6202
  toggleFold(row.groupKey);
6203
  return;
6204
  }
6205
+ // HOTFIX 2026-09-23: a paged group's footer. The left half of its first cell is
6206
+ // Previous, the right half Next (`groupFooterCell` paints both marks there).
6207
+ if (row.kind === "group-footer" && row.page) {
6208
+ event.preventDefault();
6209
+ if (cell[0] !== 0) return;
6210
+ const { offset, total, size } = row.page;
6211
+ const back = event.localEventX < event.bounds.width / 2;
6212
+ const next = back ? offset - size : offset + size;
6213
+ if (next >= 0 && next < total) loadGroupPage(row.groupKey, next);
6214
+ return;
6215
+ }
6216
  // W40-T30 — the virtual "Go" cell's tap door stood here, matched by POSITION on the index
6217
  // one past the persisted columns. Owner instruction 27 removed it; the transit link is a
6218
  // pre-set URL field now, so it opens through the ordinary url-cell branch below, which is
 
9516
  const onExpandAllGroups = useCallback(() => {
9517
  const keys = new Set<string>();
9518
  for (const vr of visibleRows) if (vr.kind === "group-header") keys.add(vr.groupKey);
9519
+ // HOTFIX 2026-09-23: a read-through table's groups come from the server, not the page.
9520
+ if (serverWindowed) for (const k of groupKeyRaw.keys()) keys.add(k);
9521
  setFold(keys);
9522
+ }, [visibleRows, setFold, serverWindowed, groupKeyRaw]);
9523
  /**
9524
  * Item 7 (C-TS) — the pid set the time series asks about: exactly the rows the current
9525
  * filter kept, so the panel and the toolbar count can never disagree about "who".
 
10652
  sortsLocked={activeSortsLocked}
10653
  onCopyToChange={() => duplicateView(activeViewId)}
10654
  // the toolbar must not advertise a grouping the pipeline is not applying
10655
+ groupBy={config.groupBy}
10656
  onGroupBy={(groupBy) => updateConfig({ ...config, groupBy })}
10657
  onCollapseAllGroups={onCollapseAllGroups}
10658
  onExpandAllGroups={onExpandAllGroups}
 
10952
  `cg-app-launch-state`: route-app.css:28-31 hides the Data toolbar's controls on
10953
  `.cg-main:has(.cg-app-launch-state)`, so borrowing that class would flash the whole toolbar
10954
  away on every rail click. Only the bar classes are reused; they carry size and the pulse. */}
10955
+ {/* ⭐⭐ HOTFIX 2026-09-23 — PENDING NO LONGER UNMOUNTS THE GRID. S64-T01 swapped the canvas
10956
+ for a skeleton on every view switch, even when the page came back from cache, and
10957
+ the owner felt that as "we used to click from one view to another without ANY load".
10958
+ The rows in hand stay painted; a thin bar says a newer page is on its way. */}
10959
  {!applicationLaunching && viewSwitchPending && (
10960
+ <div className="cg-view-pending" role="status" aria-label="Loading view" />
 
 
 
 
 
10961
  )}
10962
+ {displayMode === "grid" && !applicationLaunching && (
10963
  <>
10964
  <DataEditor
10965
  ref={gridRef}
 
11768
  />
11769
  )}
11770
  </div>
11771
+ {/* ⭐⭐ HOTFIX 2026-09-23 — THE PAGER. One page of a read-through table at a time, and
11772
+ every page reachable: `matched` is the server's own count, so this is a view onto the
11773
+ whole population rather than a cap on it (standing rule 1). Grouped, each open group
11774
+ pages on its own footer instead. */}
11775
+ {serverWindowed && !config.groupBy && displayMode === "grid" && (
11776
+ <GridPager
11777
+ offset={pageOffset}
11778
+ size={WINDOW_ROWS}
11779
+ total={payload?.counts?.matched ?? 0}
11780
+ pending={windowPending}
11781
+ onPage={goToPage}
11782
+ />
11783
+ )}
11784
  {/* ⭐ W30-T42 — the WINDOWED grid's honest footnotes, in the strip that already exists
11785
  for exactly this job. Reuses `.cg-more` / `.cg-more-note` rather than adding a
11786
  class: `index.css` is another lane's fence this wave, and this needs no new pixel.
web/src/customer-grid/GridPager.tsx ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * ⭐⭐ HOTFIX 2026-09-23 — the read-through grid's pager.
3
+ *
4
+ * Owner, verbatim: *"I want fucking either pagination or next page and only load 50 at a time to
5
+ * be fucking back."* This revokes SDLC 62 R3 (virtualise only). A read-through table holds ONE
6
+ * page of `size` rows; Previous and Next move it. `total` is the server's count of everything the
7
+ * predicate matches, so every row stays reachable and the count is never `rows.length`.
8
+ */
9
+ export function pageLabel(offset: number, size: number, total: number): string {
10
+ if (total <= 0) return "No records";
11
+ const from = Math.min(total, offset + 1);
12
+ const to = Math.min(total, offset + size);
13
+ return `${from.toLocaleString()} to ${to.toLocaleString()} of ${total.toLocaleString()}`;
14
+ }
15
+
16
+ export function GridPager({
17
+ offset,
18
+ size,
19
+ total,
20
+ pending,
21
+ onPage,
22
+ }: {
23
+ offset: number;
24
+ size: number;
25
+ total: number;
26
+ pending: boolean;
27
+ onPage: (offset: number) => void;
28
+ }) {
29
+ const pages = Math.max(1, Math.ceil(total / size));
30
+ const page = Math.min(pages, Math.floor(offset / size) + 1);
31
+ const hasPrev = offset > 0;
32
+ const hasNext = offset + size < total;
33
+ return (
34
+ <nav className="cg-pager" aria-label="Pages" aria-busy={pending || undefined}>
35
+ <button
36
+ type="button"
37
+ className="cg-btn"
38
+ disabled={!hasPrev}
39
+ onClick={() => onPage(Math.max(0, offset - size))}
40
+ >
41
+ Previous
42
+ </button>
43
+ <span className="cg-pager-label">
44
+ {pageLabel(offset, size, total)}
45
+ <span className="cg-pager-page">Page {page.toLocaleString()} of {pages.toLocaleString()}</span>
46
+ </span>
47
+ <button
48
+ type="button"
49
+ className="cg-btn"
50
+ disabled={!hasNext}
51
+ onClick={() => onPage(offset + size)}
52
+ >
53
+ Next
54
+ </button>
55
+ </nav>
56
+ );
57
+ }
web/src/customer-grid/Toolbar.tsx CHANGED
@@ -864,7 +864,7 @@ export default function Toolbar({
864
  recordCount,
865
  scopeCounts,
866
  pool,
867
- serverWindowed = false,
868
  cohortAction,
869
  filterSeed = null,
870
  modeControl,
@@ -1193,16 +1193,10 @@ export default function Toolbar({
1193
  {() => (
1194
  <div className="cg-pop-body">
1195
  <div className="cg-pop-title">Group by</div>
1196
- {serverWindowed ? (
1197
- // CG-3. Grouping runs over the rows in hand; on a windowed table those are ONE
1198
- // PAGE, so every group header would report a count and subtotals for the page
1199
- // while presenting them as the group's. Say why, rather than silently omitting
1200
- // the control — a missing button reads as a bug.
1201
- <div className="cg-pop-note">
1202
- Not available on this table. It loads one page at a time, so a group would
1203
- count only the rows currently fetched.
1204
- </div>
1205
- ) : (
1206
  <>
1207
  {/* ⭐⭐ W50-T02 (owner instruction 2, ruling R16) — "the user can click Collapse
1208
  all and the opposite (Expand all)". Inside the NON-windowed branch on
 
864
  recordCount,
865
  scopeCounts,
866
  pool,
867
+ serverWindowed: _serverWindowed = false,
868
  cohortAction,
869
  filterSeed = null,
870
  modeControl,
 
1193
  {() => (
1194
  <div className="cg-pop-body">
1195
  <div className="cg-pop-title">Group by</div>
1196
+ {/* HOTFIX 2026-09-23: grouping is back on a read-through table. The groups, counts
1197
+ and totals come from the server over the whole match set, and each open group
1198
+ pages its own records (owner revoked the virtualise-only ruling). */}
1199
+ {(
 
 
 
 
 
 
1200
  <>
1201
  {/* ⭐⭐ W50-T02 (owner instruction 2, ruling R16) — "the user can click Collapse
1202
  all and the opposite (Expand all)". Inside the NON-windowed branch on
web/src/customer-grid/apiBridge.ts CHANGED
@@ -565,7 +565,9 @@ export async function fetchAssignedCustomerRows(viewId: string): Promise<Custome
565
  /** One window's worth of rows. 200 is what D measured the route at (79 ms warm on 32,700
566
  * orders, against 474 ms for the whole read); the server clamps anything over
567
  * `datastore.WINDOW_MAX` (5,000) and REPORTS the clamp rather than trimming quietly. */
568
- export const WINDOW_ROWS = 200;
 
 
569
 
570
  export interface RowWindowRequest {
571
  offset: number;
@@ -586,6 +588,10 @@ export interface RowWindowRequest {
586
  * to see in the network panel.
587
  */
588
  related?: RelatedPin | null;
 
 
 
 
589
  }
590
 
591
  /**
@@ -629,6 +635,10 @@ export function windowRowsPath(tableKey: string, req: RowWindowRequest): string
629
  payload; assuming both were bodies is the half-wired contract that paints the right rows
630
  under a summary computed over the whole table. */
631
  if (req.related) q.set("related", JSON.stringify(req.related));
 
 
 
 
632
  return `odoo-tables/${encodeURIComponent(tableKey)}/rows?${q.toString()}`;
633
  }
634
 
 
565
  /** One window's worth of rows. 200 is what D measured the route at (79 ms warm on 32,700
566
  * orders, against 474 ms for the whole read); the server clamps anything over
567
  * `datastore.WINDOW_MAX` (5,000) and REPORTS the clamp rather than trimming quietly. */
568
+ // HOTFIX 2026-09-23 (owner): "pagination or next page and only load 50 at a time". The grid
569
+ // pages a read-through table 50 rows at a time with Prev / Next; `total` stays the server's.
570
+ export const WINDOW_ROWS = 50;
571
 
572
  export interface RowWindowRequest {
573
  offset: number;
 
588
  * to see in the network panel.
589
  */
590
  related?: RelatedPin | null;
591
+ /** HOTFIX 2026-09-23 — page ONE group of `/aggregates`' grouping. `key` is the group key
592
+ * exactly as `/aggregates` put it on the wire (`null` = the blank bucket). Part of the path,
593
+ * therefore part of the cache key. */
594
+ group?: { by: string; key: string | number | null } | null;
595
  }
596
 
597
  /**
 
635
  payload; assuming both were bodies is the half-wired contract that paints the right rows
636
  under a summary computed over the whole table. */
637
  if (req.related) q.set("related", JSON.stringify(req.related));
638
+ if (req.group && req.group.by) {
639
+ q.set("groupBy", req.group.by);
640
+ q.set("groupKey", JSON.stringify(req.group.key ?? null));
641
+ }
642
  return `odoo-tables/${encodeURIComponent(tableKey)}/rows?${q.toString()}`;
643
  }
644
 
web/src/customer-grid/counts.ts CHANGED
@@ -294,7 +294,6 @@ function firstSentence(cause: string | undefined): string {
294
  * there without a line here.
295
  */
296
  export const WINDOWED_TOOLS_OFF = [
297
- "grouping and its subtotals",
298
  "the kanban, calendar, list, map and catalog views",
299
  "export",
300
  "add to cohort, and remove from cohort",
 
294
  * there without a line here.
295
  */
296
  export const WINDOWED_TOOLS_OFF = [
 
297
  "the kanban, calendar, list, map and catalog views",
298
  "export",
299
  "add to cohort, and remove from cohort",
web/src/customer-grid/types.ts CHANGED
@@ -2855,7 +2855,14 @@ export type VisibleRow =
2855
  collapsed: boolean;
2856
  aggs: Record<string, string>;
2857
  }
2858
- | { kind: "group-footer"; groupKey: string; aggs: Record<string, string> };
 
 
 
 
 
 
 
2859
 
2860
  /** Multi-level sort: ordered = precedence (each key breaks ties within the prior). */
2861
  export interface SortRule {
 
2855
  collapsed: boolean;
2856
  aggs: Record<string, string>;
2857
  }
2858
+ | {
2859
+ kind: "group-footer";
2860
+ groupKey: string;
2861
+ aggs: Record<string, string>;
2862
+ /** HOTFIX 2026-09-23: per-group paging, the page this footer's group is showing. Absent
2863
+ * when the group fits on one page. */
2864
+ page?: { offset: number; total: number; size: number };
2865
+ };
2866
 
2867
  /** Multi-level sort: ordered = precedence (each key breaks ties within the prior). */
2868
  export interface SortRule {
web/src/customer-grid/useCustomerData.ts CHANGED
@@ -746,38 +746,24 @@ export function useCustomerData(
746
  const requestWindow = useCallback((req: RowWindowRequest) => {
747
  if (suppliedPayload || !readThroughRef.current || STREAMLIT_COMPONENT || EMBEDDED_HTML) return;
748
  const offset = Math.max(0, Math.floor(req.offset || 0));
749
- // ⛔ ONE REQUEST PER PAGE IN FLIGHT. glide fires its visible-region callback on every frame
750
- // of a scroll; without this the same offset is asked for on each one. Offset 0 is exempt on
751
- // purpose — that is a PREDICATE change, and the newest predicate must always be able to
752
- // overtake an older one rather than be suppressed by it.
753
- if (offset > 0 && inflightOffset.current === offset) return;
754
- /* ⛔⛔ S64-T01 / C4 — PENDING IS FOR THE PREDICATE CHANGE ONLY, AND THE `offset === 0` GUARD
755
- IS THE WHOLE REASON THIS DOES NOT BREAK THE SCROLL. The two callers mean opposite things
756
- about the rows already on screen. Offset 0 REPLACES them: it is a view switch (the rows
757
- belong to the view the reader just left) or `CustomerGrid.tsx`'s bulk-write refresh, whose
758
- own comment says *"Do not paint loaded rows as though they were the whole update"*. Offset
759
- > 0 APPENDS to a window that is still the right view.
760
- ⛔ Without the guard every scroll page entered pending, and `viewSwitchPending` unmounts the
761
- `DataEditor` — so paging a read-through grid would blank it and return the reader to the top
762
- of the table, on every page. `counts.ts::nextWindowOffset` returns `loaded`, always >= 1, so
763
- that fires on EVERY append rather than in some corner. Pinned by `verify_api.py`'s C4
764
- section and its negative control. */
765
- if (offset === 0) setWindowPending(true);
766
  const seq = ++windowSeq.current;
767
- if (offset > 0) inflightOffset.current = offset;
768
- /* ⭐⭐ W51-T06 / C6 — AND THE SCROLL CARRIES THE PIN, WHICH IS THE HALF A CLOSURE LOSES.
769
- ⛔ `related` IS IN THE DEPENDENCY LIST BELOW FOR THIS ONE LINE. Left out, this callback
770
- would keep the pin it was built with: the first page correct and every appended page the
771
- WHOLE table, under a `total` that still described the pinned set. Nothing errors, the
772
- count agrees with itself, and the rows are two different populations stacked. */
773
  void fetchTableWindow(scope, { ...req, related, offset }).then((next) => {
774
- if (offset > 0 && inflightOffset.current === offset) inflightOffset.current = null;
775
  if (seq !== windowSeq.current) return;
776
  setWindowPending(false);
777
  if (!next) return;
778
- setData((prev) => mergeWindow(prev, next, offset));
779
  }).catch(() => {
780
- if (offset > 0 && inflightOffset.current === offset) inflightOffset.current = null;
781
  if (seq === windowSeq.current) setWindowPending(false);
782
  });
783
  }, [scope, related, suppliedPayload]);
 
746
  const requestWindow = useCallback((req: RowWindowRequest) => {
747
  if (suppliedPayload || !readThroughRef.current || STREAMLIT_COMPONENT || EMBEDDED_HTML) return;
748
  const offset = Math.max(0, Math.floor(req.offset || 0));
749
+ /* ⭐⭐ HOTFIX 2026-09-23 (owner: "pagination or next page and only load 50 at a time") — EVERY
750
+ request is a PAGE that REPLACES the rows in hand, so every one enters pending and the
751
+ newest one always wins (`windowSeq`). There is no scroll append any more, so the
752
+ one-request-per-offset dedupe that existed for scroll spam is gone: it could suppress a
753
+ page the reader asked for again while an older request for it was still in flight.
754
+ ⛔ Pending no longer unmounts the grid (`CustomerGrid.tsx::viewSwitchPending`): the rows
755
+ on screen stay until the next page lands, which is what made view switches feel instant. */
756
+ setWindowPending(true);
 
 
 
 
 
 
 
 
 
757
  const seq = ++windowSeq.current;
758
+ /* ⭐⭐ W51-T06 / C6 — THE PAGE CARRIES THE PIN. `related` IS IN THE DEPENDENCY LIST BELOW FOR
759
+ THIS ONE LINE: left out, every page after the first would be the WHOLE table under a
760
+ `total` that still described the pinned set. */
 
 
 
761
  void fetchTableWindow(scope, { ...req, related, offset }).then((next) => {
 
762
  if (seq !== windowSeq.current) return;
763
  setWindowPending(false);
764
  if (!next) return;
765
+ setData((prev) => mergeWindow(prev, next, 0));
766
  }).catch(() => {
 
767
  if (seq === windowSeq.current) setWindowPending(false);
768
  });
769
  }, [scope, related, suppliedPayload]);
web/src/customer-grid/useGetCellContent.ts CHANGED
@@ -199,6 +199,20 @@ function loadingCell(width: number | undefined, row: number, pulse: number): Gri
199
  */
200
  function groupFooterCell(vr: GroupFooterRow, col: number, field: Field | undefined): GridCell {
201
  const agg = field ? vr.aggs[field.key] : undefined;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  if (agg === undefined && col === 0 && vr.groupKey === TOTAL_GROUP_KEY)
203
  return {
204
  ...summaryCell(TOTAL_ROW_LABEL, SUMMARY_BG, SUMMARY_TEXT, SUMMARY_FONT),
 
199
  */
200
  function groupFooterCell(vr: GroupFooterRow, col: number, field: Field | undefined): GridCell {
201
  const agg = field ? vr.aggs[field.key] : undefined;
202
+ // HOTFIX 2026-09-23: a paged group's first footer cell is its pager. The click handler in
203
+ // `CustomerGrid.onCellClicked` reads the left half as Previous and the right half as Next.
204
+ if (col === 0 && vr.page) {
205
+ const { offset, total, size } = vr.page;
206
+ const from = Math.min(total, offset + 1).toLocaleString();
207
+ const to = Math.min(total, offset + size).toLocaleString();
208
+ const prev = offset > 0 ? "‹ Prev" : "";
209
+ const next = offset + size < total ? "Next ›" : "";
210
+ return {
211
+ ...summaryCell(`${prev} ${from} to ${to} of ${total.toLocaleString()} ${next}`.trim(),
212
+ SUMMARY_BG, SUMMARY_TEXT, SUMMARY_FONT),
213
+ contentAlign: "center",
214
+ };
215
+ }
216
  if (agg === undefined && col === 0 && vr.groupKey === TOTAL_GROUP_KEY)
217
  return {
218
  ...summaryCell(TOTAL_ROW_LABEL, SUMMARY_BG, SUMMARY_TEXT, SUMMARY_FONT),
web/src/index.css CHANGED
@@ -422,6 +422,43 @@ body {
422
  overflow: hidden;
423
  }
424
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
425
  .cg-loading {
426
  width: 100%;
427
  height: 100%;
 
422
  overflow: hidden;
423
  }
424
 
425
+ /* HOTFIX 2026-09-23: the read-through grid pages 50 rows at a time (owner). */
426
+ .cg-pager {
427
+ display: flex;
428
+ align-items: center;
429
+ justify-content: flex-end;
430
+ gap: 12px;
431
+ padding: 6px 12px;
432
+ border-top: 1px solid var(--cg-line, #E3E8EF);
433
+ font-size: 12px;
434
+ color: var(--cg-muted, #5B6B7F);
435
+ flex: 0 0 auto;
436
+ }
437
+ .cg-pager-label { display: inline-flex; gap: 10px; font-variant-numeric: tabular-nums; }
438
+ .cg-pager-page { color: var(--cg-faint, #8A97A8); }
439
+ .cg-pager[aria-busy="true"] .cg-pager-label { opacity: 0.6; }
440
+ /* The view-switch pending bar: the rows stay painted underneath it. */
441
+ .cg-view-pending {
442
+ position: absolute;
443
+ top: 0;
444
+ left: 0;
445
+ right: 0;
446
+ height: 2px;
447
+ z-index: 3;
448
+ background: linear-gradient(90deg, transparent, #1F4E78, transparent);
449
+ background-size: 50% 100%;
450
+ background-repeat: no-repeat;
451
+ animation: cg-view-pending-slide 0.9s linear infinite;
452
+ pointer-events: none;
453
+ }
454
+ @keyframes cg-view-pending-slide {
455
+ from { background-position: -50% 0; }
456
+ to { background-position: 150% 0; }
457
+ }
458
+ @media (prefers-reduced-motion: reduce) {
459
+ .cg-view-pending { animation: none; background: #1F4E78; opacity: 0.4; }
460
+ }
461
+
462
  .cg-loading {
463
  width: 100%;
464
  height: 100%;