fsanyoto commited on
Commit
480544b
·
verified ·
1 Parent(s): f38d1d4

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,4 +1,4 @@
1
  {
2
- "current": "0854ce6",
3
  "releases": []
4
  }
 
1
  {
2
+ "current": "3edf0f1",
3
  "releases": []
4
  }
VERSION CHANGED
@@ -1 +1 @@
1
- 0854ce6
 
1
+ 3edf0f1
api/routes_sheet.py CHANGED
@@ -35,6 +35,7 @@ while its surface is a 404.
35
  (standing rule 2), and each names both the cause and the subject.
36
  """
37
 
 
38
  import hashlib
39
  import json
40
  import os
@@ -353,7 +354,17 @@ def _registry_assembly(session: Session, table_key: str):
353
 
354
 
355
  def _related_declarations(session, database):
356
- """The same permission-scoped catalogue for reads, rewrites and the picker."""
 
 
 
 
 
 
 
 
 
 
357
  from core import perm_scope, relations, user_tables
358
  from routes_grid import _source_fields
359
 
@@ -381,6 +392,8 @@ def _related_declarations(session, database):
381
  if relations.edge_identity(entry) not in seen:
382
  seen.add(relations.edge_identity(entry))
383
  entries.append(entry)
 
 
384
  return fields, defs, entries
385
 
386
 
@@ -1114,12 +1127,37 @@ def _has_cell_inputs(binding):
1114
  return any(sheet_mod.filter_cell_nodes(nodes))
1115
 
1116
 
1117
- def _refresh_context(book, binding, memo=None):
1118
- """Authored inputs and relative dates invalidate refresh, but never an open's snapshot."""
 
 
 
 
 
 
 
 
1119
  from core.sheet_binding import fingerprint
1120
  from datetime import date
1121
  payload = {}
1122
- if _has_cell_inputs(binding):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1123
  if memo is None:
1124
  memo = {}
1125
  if "inputs" not in memo:
@@ -1230,8 +1268,11 @@ def _reresolved_for_reader(session: Session, book, *, endings_only=False):
1230
  # and MCP read agree on stored cells, figures and formats` measured exactly that pair: D1 and
1231
  # F1 fresh 30.0 / 60.0 from MCP against stale-and-blank from the UI. A non-browser consumer has
1232
  # no client engine to cover for it, so the blank is what it would have shown.
 
 
 
1233
  stale_formula = any(
1234
- cell.get("kind") == "formula" and (cell.get("state") != "fresh" or "value" not in cell)
1235
  for tab in (fresh.get("sheets") or []) for cell in (tab.get("cells") or {}).values())
1236
  if changed_values or stale_formula:
1237
  from modules import sheet as sheet_mod
@@ -1847,10 +1888,17 @@ def _recomputed_tab_cells(session: Session, workbook_id: str, tab_ref: str, *, c
1847
  A formula sitting on a tab nobody has open still shows its last answer until that tab is
1848
  opened or the workbook is refreshed, exactly as a stale database-bound cell does.
1849
  """
 
 
 
 
 
1850
  from core import sheets
1851
  from modules import sheet as sheet_mod
1852
  import formula_runtime as fr
 
1853
 
 
1854
  try:
1855
  book = sheets.get_workbook(_store(session), workbook_id)
1856
  found = sheets.find_tab(book, tab_ref)
@@ -1864,17 +1912,43 @@ def _recomputed_tab_cells(session: Session, workbook_id: str, tab_ref: str, *, c
1864
  (found.get("cells") or {}).get(str(addr).strip().upper()) for addr in changes}
1865
  _recompute_formulas(book, fr, sheet_mod,
1866
  cache_key=(session.tenant, session.uname, workbook_id), changes=edits)
1867
- # Date and filter-cell edits also change database totals. Recompute all readers, then formulas.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1868
  ending_cells = set()
1869
  refreshed_entries = []
1870
  context_memo = {}
1871
- for source in book.get("sheets") or []:
 
 
1872
  for addr, cell in (source.get("cells") or {}).items():
1873
  binding = cell.get("binding") or {}
1874
- if cell.get("kind") != "bound" or not _has_cell_inputs(binding):
 
 
 
1875
  continue
1876
  try:
1877
- result = _resolve_cell_binding(session, binding, book, source.get("id"))
 
1878
  cell.update(value=result["value"], display="" if result["value"] is None else str(result["value"]), state="fresh")
1879
  cell["refreshed_at"] = _now_iso()
1880
  if result.get("limits"):
@@ -1882,6 +1956,8 @@ def _recomputed_tab_cells(session: Session, workbook_id: str, tab_ref: str, *, c
1882
  else:
1883
  cell.pop("limits", None)
1884
  cell.pop("refusal", None)
 
 
1885
  except HTTPException as exc:
1886
  info = ((exc.detail or {}).get("error") or {})
1887
  cell.update(_binding_refusal(
@@ -1891,7 +1967,8 @@ def _recomputed_tab_cells(session: Session, workbook_id: str, tab_ref: str, *, c
1891
  ending_cells.add((source.get("id"), addr))
1892
  refreshed_entries.append((str(source.get("id")) + "!" + addr,
1893
  _binding_scope_key(session, str(binding.get("database") or ""), binding),
1894
- {"tokens": {}, "context": _refresh_context(book, binding, context_memo),
 
1895
  "cell": {k: cell[k] for k in ("value", "display", "state", "refreshed_at", "limits", "refusal")
1896
  if k in cell}}))
1897
  if ending_cells:
@@ -1900,6 +1977,11 @@ def _recomputed_tab_cells(session: Session, workbook_id: str, tab_ref: str, *, c
1900
  {c.get("binding", {}).get("database") for t in book.get("sheets", [])
1901
  for c in t.get("cells", {}).values() if c.get("kind") == "bound"})
1902
  _recompute_formulas(book, fr, sheet_mod)
 
 
 
 
 
1903
  found = sheets.find_tab(book, tab_ref)
1904
  out = {}
1905
  for addr, cell in (found.get("cells") or {}).items():
@@ -2073,12 +2155,25 @@ def unshare_sheet(workbook_id: str, who: str, session: Session = Depends(require
2073
 
2074
 
2075
  @router.post("/sheets/{workbook_id}/refresh")
2076
- def refresh_sheet(workbook_id: str, session: Session = Depends(require_session)):
 
2077
  """C2/R4: Refresh resolves only databases whose token or binding inputs changed.
2078
 
2079
  Viewers refresh their own server cache. Only editors save the workbook document.
2080
  One token is read per distinct database on the unchanged path, regardless of cell count.
 
 
 
 
2081
  """
 
 
 
 
 
 
 
 
2082
  from copy import deepcopy
2083
  from core import sheets, sheet_binding
2084
  from modules import sheet as sheet_mod
@@ -2121,15 +2216,25 @@ def refresh_sheet(workbook_id: str, session: Session = Depends(require_session))
2121
  tabs = book.get("sheets") or []
2122
  names = _tab_scope_names(tabs)
2123
  if input_graph is None:
2124
- documents = {fr.a1_key(addr, name): cell for tab, name in zip(tabs, names)
2125
- for addr, cell in (tab.get("cells") or {}).items()}
2126
- engine = fr.SheetCalculation({key: fr._document_spec(cell, key.rpartition("!")[0])
2127
- for key, cell in documents.items()}, sheets=names,
2128
- named_ranges=book.get("namedRanges"), date_system=book.get("dateSystem", "1900"))
2129
- input_graph = documents, engine
 
 
 
 
 
2130
  documents, engine = input_graph
2131
  home = _resolve_home_tab(book, tabs, names, tab_ref)
2132
- pending, visited, deps = [_asked_key(ref, home, fr) for ref in refs], set(), set()
 
 
 
 
 
2133
  while pending:
2134
  key = pending.pop()
2135
  if key in visited:
@@ -2193,11 +2298,16 @@ def refresh_sheet(workbook_id: str, session: Session = Depends(require_session))
2193
  hit = cache.get("refreshCells", {}).get(str(tab_ref) + "!" + addr, {}).get(scope_key)
2194
  sources = {db: token(db) for db in dependencies(db, binding, tab_ref)}
2195
  if (hit and all(sources.values()) and hit.get("tokens") == sources
2196
- and hit.get("context") == _refresh_context(book, binding, context_memo)
 
2197
  and hit["cell"].get("state") == "fresh"):
2198
  return hit["cell"]
2199
  return None
2200
 
 
 
 
 
2201
  for tab in book.get("sheets") or []:
2202
  for addr, cell in (tab.get("cells") or {}).items():
2203
  if cell.get("kind") != "bound" or _is_view_binding(cell):
@@ -2205,8 +2315,11 @@ def refresh_sheet(workbook_id: str, session: Session = Depends(require_session))
2205
  binding = cell.get("binding") or {}
2206
  db = str(binding.get("database") or "")
2207
  cell_key = str(tab.get("id")) + "!" + addr
 
 
2208
  scope_key = _binding_scope_key(session, db, binding)
2209
- context = _refresh_context(book, binding, context_memo)
 
2210
  hit = cache.get("refreshCells", {}).get(cell_key, {}).get(scope_key)
2211
  source_tokens = {}
2212
  try:
@@ -2226,12 +2339,16 @@ def refresh_sheet(workbook_id: str, session: Session = Depends(require_session))
2226
  status.setdefault(db, "skipped")
2227
  continue
2228
  status[db] = "resolved"
 
2229
  previous = getattr(session, "_sheet_refresh_input", None)
2230
  session._sheet_refresh_input = cached_input
2231
  try:
2232
  out = _resolve_cell_binding(session, binding, book, tab.get("id"), view_memo=view_memo)
2233
  finally:
2234
  session._sheet_refresh_input = previous
 
 
 
2235
  limits = list(out.get("limits") or [])
2236
  if not all(source_tokens.values()):
2237
  limits.append({"code": "change_token_unavailable",
@@ -2276,9 +2393,15 @@ def refresh_sheet(workbook_id: str, session: Session = Depends(require_session))
2276
  tab_ref, addr = cell_key.split("!", 1)
2277
  _snapshot_cell(sheets.find_tab(book, tab_ref)["cells"][addr], entry["cell"])
2278
 
 
2279
  started = perf_counter()
2280
  _recompute_formulas(book, fr, sheet_mod)
2281
  recalc_ms = round((perf_counter() - started) * 1000.0, 1)
 
 
 
 
 
2282
  if editable:
2283
  try:
2284
  saved = sheets.put_workbook(store, workbook_id,
@@ -2293,6 +2416,13 @@ def refresh_sheet(workbook_id: str, session: Session = Depends(require_session))
2293
  saved["refreshedFor"] = str(session.uname or "")
2294
  if entries:
2295
  sheet_binding.save_refresh_cache(store, workbook_id, entries, status)
 
 
 
 
 
 
 
2296
  return {"workbook": _response_workbook(saved), "recalc_ms": recalc_ms,
2297
  "binding_refresh": {"databases": status, "token_reads": token_reads}}
2298
 
@@ -2438,6 +2568,10 @@ _METRIC_COLUMN_CREATE_LOCK = threading.RLock()
2438
  def _forget_sheet_database(session, database):
2439
  """A field write invalidates both request-local schema and materialised-column memos."""
2440
  getattr(session, "_sheet_assemblies", {}).pop(database, None)
 
 
 
 
2441
  mirrors = getattr(session, "_sheet_mirrors", {})
2442
  for slot in list(mirrors):
2443
  if slot[0] == database:
@@ -2564,6 +2698,286 @@ def _ending_window(session, binding, *, book=None, tab=None, today=None, seen=()
2564
  return sheet_mod.period_window(period, today, cell_date=date)
2565
 
2566
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2567
  def _read_binding_cell(session, ref, *, book=None, tab=None, today=None, seen=(),
2568
  code="ending_cell_unreadable", as_date=False):
2569
  """Shared cell read for Ending and Filter, including scoped bound and formula inputs.
@@ -2578,40 +2992,50 @@ def _read_binding_cell(session, ref, *, book=None, tab=None, today=None, seen=()
2578
  def refuse(reason):
2579
  raise sheet_mod.SheetRefusal(code, ref or "(blank)", reason)
2580
 
 
 
 
2581
  if not re.fullmatch(r"(?:(?:'([^']|'')+'|[^'!]+)!)?\$?[A-Za-z]{1,3}\$?[1-9][0-9]{0,6}", ref):
2582
  refuse("its reference is invalid.")
2583
  if book is None:
2584
  refuse("the source workbook is unavailable.")
2585
  tabs = book.get("sheets") or []
2586
- names = _tab_scope_names(tabs)
 
 
 
 
 
2587
  home = _resolve_home_tab(book, tabs, names, tab)
2588
  key = _asked_key(ref, home, fr)
2589
  if key in seen:
2590
  refuse("the reference is circular.")
2591
- cells = {fr.a1_key(addr, name): cell for source, name in zip(tabs, names)
2592
- for addr, cell in (source.get("cells") or {}).items()}
 
2593
  cell = cells.get(key)
2594
  if not isinstance(cell, dict) or cell.get("kind") == "empty":
2595
  refuse("the cell or its sheet is missing or blank.")
2596
  if cell.get("kind") == "bound":
2597
  try:
2598
- lookup = getattr(session, "_sheet_refresh_input", None)
2599
- cached = lookup(key) if lookup is not None else None
2600
- value = (cached["value"] if cached is not None else _resolve_binding(
2601
- session, cell.get("binding"), today=today, book=book,
2602
- tab=key.rpartition("!")[0], ending_seen=(*seen, key))["value"])
2603
  except HTTPException as exc:
2604
  reason = ((exc.detail or {}).get("error") or {}).get("message", "its source is refused.")
2605
  refuse(reason)
2606
  elif cell.get("kind") == "formula":
2607
  # The existing formula graph discovers actual inputs, including dynamic references.
2608
  # A database input starts refused, so a cached value can never bypass this reader's wall.
2609
- bound = {k: c for k, c in cells.items() if c.get("kind") == "bound"}
2610
- specs = {k: ({"refused": "ending_input_pending"} if k in bound
2611
- else fr._document_spec(c, k.rpartition("!")[0])) for k, c in cells.items()}
2612
- engine = fr.SheetCalculation(specs, sheets=names, today=today,
2613
- named_ranges=book.get("namedRanges"), date_system=book.get("dateSystem", "1900"))
2614
- attempted, failures = set(), {}
 
 
 
 
2615
  while True:
2616
  dependencies, pending = set(), [key]
2617
  while pending:
@@ -2627,11 +3051,8 @@ def _read_binding_cell(session, ref, *, book=None, tab=None, today=None, seen=()
2627
  for dependency in needed:
2628
  attempted.add(dependency)
2629
  try:
2630
- lookup = getattr(session, "_sheet_refresh_input", None)
2631
- result = lookup(dependency) if lookup is not None else None
2632
- if result is None:
2633
- result = _resolve_binding(session, bound[dependency].get("binding"), today=today,
2634
- book=book, tab=dependency.rpartition("!")[0], ending_seen=(*seen, key, dependency))
2635
  changes[dependency] = {"value": result["value"]}
2636
  except HTTPException as exc:
2637
  info = ((exc.detail or {}).get("error") or {})
@@ -3060,6 +3481,11 @@ def preview_cell(workbook_id: str, addr: str, body: dict = Body(default=None),
3060
  binding editor show a number before anyone commits the cell. R10 may create a missing Metric
3061
  field through the database's ordinary field writer; reusing a column needs no field write.
3062
  """
 
 
 
 
 
3063
  raw = dict(body or {})
3064
  binding = raw.get("binding") or {}
3065
  book = None
@@ -3167,6 +3593,11 @@ def compute_cell(workbook_id: str, addr: str, body: dict = Body(default=None),
3167
  ⚠ `rev` BUMPS, BECAUSE THIS PERSISTS. It goes back in the answer and the client adopts it, or
3168
  its next PATCH would carry a revision the server has already moved past.
3169
  """
 
 
 
 
 
3170
  from core import sheets
3171
 
3172
  try:
@@ -3392,6 +3823,11 @@ def drill_cell(workbook_id: str, addr: str, tab: str | None = None,
3392
  no comparison text, and the count beside those ids is the LIVE count, because `LinkGridModal`
3393
  prints the length of what it is handed and runs no query of its own.
3394
  """
 
 
 
 
 
3395
  from core import sheets
3396
  from modules import sheet as sheet_mod
3397
  import core.perm_scope as perm_scope
@@ -3606,6 +4042,11 @@ def resolve_bindings(workbook_id: str, body: dict = Body(default=None),
3606
  database work, and a batch's cost is dominated by the number of distinct (database, period)
3607
  pairs in it rather than by the number of cells.
3608
  """
 
 
 
 
 
3609
  from core import sheets
3610
  import formula_runtime as fr
3611
 
 
35
  (standing rule 2), and each names both the cause and the subject.
36
  """
37
 
38
+ import contextlib
39
  import hashlib
40
  import json
41
  import os
 
354
 
355
 
356
  def _related_declarations(session, database):
357
+ """The same permission-scoped catalogue for reads, rewrites and the picker.
358
+
359
+ HOTFIX 2026-09-29: answered once per request inside `_sheet_request_scope`. Every
360
+ `related:` leaf used to re-read `user_tables.all_defs()` and re-scope every definition, once
361
+ per BINDING, so a Refresh of Daily Sales (~470 cells filtered on the customer's pricelist) read
362
+ the whole catalogue ~470 times (SDLC 67 S67-T21 finding).
363
+ """
364
+ memo = getattr(session, "_sheet_read_memo", None)
365
+ slot = ("related", database)
366
+ if isinstance(memo, dict) and slot in memo:
367
+ return memo[slot]
368
  from core import perm_scope, relations, user_tables
369
  from routes_grid import _source_fields
370
 
 
392
  if relations.edge_identity(entry) not in seen:
393
  seen.add(relations.edge_identity(entry))
394
  entries.append(entry)
395
+ if isinstance(memo, dict):
396
+ memo[slot] = (fields, defs, entries)
397
  return fields, defs, entries
398
 
399
 
 
1127
  return any(sheet_mod.filter_cell_nodes(nodes))
1128
 
1129
 
1130
+ def _refresh_context(book, binding, memo=None, *, tab=None, session=None):
1131
+ """Authored inputs and relative dates invalidate refresh, but never an open's snapshot.
1132
+
1133
+ HOTFIX 2026-09-29 (owner: "ONLY when we update ANY cells, its related cells also have to
1134
+ update"): with its `tab` and a request scope, a binding's inputs are the cells it actually
1135
+ READS, transitively (`_input_closure`), not the whole workbook. The whole-workbook fingerprint
1136
+ meant one edit anywhere invalidated every one of Daily Sales' ~470 bindings, so every Refresh
1137
+ after any edit re-resolved all of them. The tab list rides the fingerprint, so a rename or a
1138
+ reorder still invalidates everything. Without a scope the old whole-workbook reading stands.
1139
+ """
1140
  from core.sheet_binding import fingerprint
1141
  from datetime import date
1142
  payload = {}
1143
+ graph = None
1144
+ if session is not None and tab is not None and _has_cell_inputs(binding):
1145
+ import formula_runtime as fr
1146
+ graph = _read_graph(session, book, fr, None)
1147
+ if graph is not None:
1148
+ import formula_runtime as fr
1149
+ tabs = book.get("sheets") or []
1150
+ home = _resolve_home_tab(book, tabs, graph["names"], tab)
1151
+ engine = _read_engine(graph, book, fr, None)[0]
1152
+ closure = _input_closure(graph, engine, fr, _qualified_refs(binding, home, fr, graph))
1153
+ authored = {}
1154
+ for key in sorted(closure):
1155
+ cell = graph["cells"].get(key)
1156
+ authored[key] = None if not isinstance(cell, dict) else {
1157
+ k: cell.get(k) for k in ("kind", "text", "formula", "binding", "value")
1158
+ if k != "value" or cell.get("kind") in ("literal", "empty")}
1159
+ payload["inputs"] = fingerprint([[[t.get("id"), t.get("name")] for t in tabs], authored])
1160
+ elif _has_cell_inputs(binding):
1161
  if memo is None:
1162
  memo = {}
1163
  if "inputs" not in memo:
 
1268
  # and MCP read agree on stored cells, figures and formats` measured exactly that pair: D1 and
1269
  # F1 fresh 30.0 / 60.0 from MCP against stale-and-blank from the UI. A non-browser consumer has
1270
  # no client engine to cover for it, so the blank is what it would have shown.
1271
+ # HOTFIX 2026-09-29: a `refused` formula is a COMPUTED answer (an error is a result), so it no
1272
+ # longer forces a whole-workbook recompute on every tab read. Only a formula with no answer at
1273
+ # all (`stale`, or no value stored) does. One `#DIV/0!` anywhere used to cost every read ~1 s.
1274
  stale_formula = any(
1275
+ cell.get("kind") == "formula" and (cell.get("state") == "stale" or "value" not in cell)
1276
  for tab in (fresh.get("sheets") or []) for cell in (tab.get("cells") or {}).values())
1277
  if changed_values or stale_formula:
1278
  from modules import sheet as sheet_mod
 
1888
  A formula sitting on a tab nobody has open still shows its last answer until that tab is
1889
  opened or the workbook is refreshed, exactly as a stale database-bound cell does.
1890
  """
1891
+ with _sheet_request_scope(session):
1892
+ return _recomputed_tab_cells_scoped(session, workbook_id, tab_ref, changes=changes)
1893
+
1894
+
1895
+ def _recomputed_tab_cells_scoped(session: Session, workbook_id: str, tab_ref: str, *, changes=None):
1896
  from core import sheets
1897
  from modules import sheet as sheet_mod
1898
  import formula_runtime as fr
1899
+ from time import perf_counter
1900
 
1901
+ started = perf_counter()
1902
  try:
1903
  book = sheets.get_workbook(_store(session), workbook_id)
1904
  found = sheets.find_tab(book, tab_ref)
 
1912
  (found.get("cells") or {}).get(str(addr).strip().upper()) for addr in changes}
1913
  _recompute_formulas(book, fr, sheet_mod,
1914
  cache_key=(session.tenant, session.uname, workbook_id), changes=edits)
1915
+ # HOTFIX 2026-09-29 (owner: "we should only update or refresh cells that are affected by an
1916
+ # operation"): a commit re-resolves ONLY the database cells whose inputs read what it changed.
1917
+ # This loop used to resolve EVERY bound cell with a cell input on EVERY commit, whatever was
1918
+ # edited: ~470 SQL resolves (each rebuilding the whole formula graph) per keystroke on Daily
1919
+ # Sales. `_dependent_bound_keys` walks the formula graph forward from the edited cells.
1920
+ graph = _read_graph(session, book, fr, None)
1921
+ targets, mode = None, "all"
1922
+ if edits is not None and graph is not None:
1923
+ try:
1924
+ targets = _dependent_bound_keys(book, graph, fr, set(edits))
1925
+ # A bound cell written by this commit resolves too, as it always did.
1926
+ targets |= {key for key in edits if key in graph["bound"]}
1927
+ mode = "dependents"
1928
+ except Exception as exc: # noqa: BLE001
1929
+ # Unprovable dependents fall back to the old whole-workbook pass: slow, never wrong.
1930
+ try:
1931
+ import harness.telemetry as _tel
1932
+ _tel.error("api:sheet-dependents", exc)
1933
+ except Exception: # noqa: BLE001
1934
+ pass
1935
+ targets, mode = None, "all"
1936
  ending_cells = set()
1937
  refreshed_entries = []
1938
  context_memo = {}
1939
+ view_memo = {}
1940
+ names = _tab_scope_names(book.get("sheets") or [])
1941
+ for source, name in zip(book.get("sheets") or [], names):
1942
  for addr, cell in (source.get("cells") or {}).items():
1943
  binding = cell.get("binding") or {}
1944
+ if cell.get("kind") != "bound" or _is_view_binding(cell) or not _has_cell_inputs(binding):
1945
+ continue
1946
+ key = fr.a1_key(addr, name)
1947
+ if targets is not None and key not in targets:
1948
  continue
1949
  try:
1950
+ result = _resolve_cell_binding(session, binding, book, source.get("id"),
1951
+ view_memo=view_memo)
1952
  cell.update(value=result["value"], display="" if result["value"] is None else str(result["value"]), state="fresh")
1953
  cell["refreshed_at"] = _now_iso()
1954
  if result.get("limits"):
 
1956
  else:
1957
  cell.pop("limits", None)
1958
  cell.pop("refusal", None)
1959
+ if graph is not None:
1960
+ graph["bound_values"][key] = result
1961
  except HTTPException as exc:
1962
  info = ((exc.detail or {}).get("error") or {})
1963
  cell.update(_binding_refusal(
 
1967
  ending_cells.add((source.get("id"), addr))
1968
  refreshed_entries.append((str(source.get("id")) + "!" + addr,
1969
  _binding_scope_key(session, str(binding.get("database") or ""), binding),
1970
+ {"tokens": {}, "context": _refresh_context(book, binding, context_memo,
1971
+ tab=source.get("id"), session=session),
1972
  "cell": {k: cell[k] for k in ("value", "display", "state", "refreshed_at", "limits", "refusal")
1973
  if k in cell}}))
1974
  if ending_cells:
 
1977
  {c.get("binding", {}).get("database") for t in book.get("sheets", [])
1978
  for c in t.get("cells", {}).values() if c.get("kind") == "bound"})
1979
  _recompute_formulas(book, fr, sheet_mod)
1980
+ stats = _read_stats(session) or {}
1981
+ print(f"[sheet] commit wb={workbook_id} tab={tab_ref} edited={len(edits or {})} mode={mode} "
1982
+ f"bound_resolved={len(ending_cells)} engines={stats.get('engines', 0)} "
1983
+ f"input_hits={stats.get('input_hits', 0)} "
1984
+ f"ms={round((perf_counter() - started) * 1000.0)}", flush=True)
1985
  found = sheets.find_tab(book, tab_ref)
1986
  out = {}
1987
  for addr, cell in (found.get("cells") or {}).items():
 
2155
 
2156
 
2157
  @router.post("/sheets/{workbook_id}/refresh")
2158
+ def refresh_sheet(workbook_id: str, body: dict = Body(default=None),
2159
+ session: Session = Depends(require_session)):
2160
  """C2/R4: Refresh resolves only databases whose token or binding inputs changed.
2161
 
2162
  Viewers refresh their own server cache. Only editors save the workbook document.
2163
  One token is read per distinct database on the unchanged path, regardless of cell count.
2164
+
2165
+ HOTFIX 2026-09-29: an optional body `{"cells": ["<tab id>!<ADDR>", ...]}` refreshes ONLY
2166
+ those bound cells (the open-time repair of the few cells this reader has no answer for, and
2167
+ the cells a row or column edit left stale). Every other cell keeps its stored answer.
2168
  """
2169
+ wanted = (body or {}).get("cells") if isinstance(body, dict) else None
2170
+ only = ({str(item) for item in wanted if isinstance(item, str) and "!" in item}
2171
+ if isinstance(wanted, list) else None)
2172
+ with _sheet_request_scope(session):
2173
+ return _refresh_sheet_scoped(workbook_id, session, only=only)
2174
+
2175
+
2176
+ def _refresh_sheet_scoped(workbook_id: str, session: Session, *, only=None):
2177
  from copy import deepcopy
2178
  from core import sheets, sheet_binding
2179
  from modules import sheet as sheet_mod
 
2216
  tabs = book.get("sheets") or []
2217
  names = _tab_scope_names(tabs)
2218
  if input_graph is None:
2219
+ shared = _read_graph(session, book, fr, None)
2220
+ if shared is not None:
2221
+ # The request's one engine (bound cells pending): its edges are the same edges.
2222
+ input_graph = shared["cells"], _read_engine(shared, book, fr, None)[0]
2223
+ else:
2224
+ documents = {fr.a1_key(addr, name): cell for tab, name in zip(tabs, names)
2225
+ for addr, cell in (tab.get("cells") or {}).items()}
2226
+ engine = fr.SheetCalculation({key: fr._document_spec(cell, key.rpartition("!")[0])
2227
+ for key, cell in documents.items()}, sheets=names,
2228
+ named_ranges=book.get("namedRanges"), date_system=book.get("dateSystem", "1900"))
2229
+ input_graph = documents, engine
2230
  documents, engine = input_graph
2231
  home = _resolve_home_tab(book, tabs, names, tab_ref)
2232
+ shared = _read_graph(session, book, fr, None)
2233
+ pending = ([key for ref in refs for key in
2234
+ (_formula_slot_keys(shared, fr, ref, home) if ref.startswith("=")
2235
+ else [_asked_key(ref, home, fr)])] if shared is not None
2236
+ else [_asked_key(ref, home, fr) for ref in refs if not ref.startswith("=")])
2237
+ visited, deps = set(), set()
2238
  while pending:
2239
  key = pending.pop()
2240
  if key in visited:
 
2298
  hit = cache.get("refreshCells", {}).get(str(tab_ref) + "!" + addr, {}).get(scope_key)
2299
  sources = {db: token(db) for db in dependencies(db, binding, tab_ref)}
2300
  if (hit and all(sources.values()) and hit.get("tokens") == sources
2301
+ and hit.get("context") == _refresh_context(book, binding, context_memo,
2302
+ tab=tab_ref, session=session)
2303
  and hit["cell"].get("state") == "fresh"):
2304
  return hit["cell"]
2305
  return None
2306
 
2307
+ started = perf_counter()
2308
+ resolved_count = 0
2309
+ scope_names = {id(tab): name for tab, name in
2310
+ zip(book.get("sheets") or [], _tab_scope_names(book.get("sheets") or []))}
2311
  for tab in book.get("sheets") or []:
2312
  for addr, cell in (tab.get("cells") or {}).items():
2313
  if cell.get("kind") != "bound" or _is_view_binding(cell):
 
2315
  binding = cell.get("binding") or {}
2316
  db = str(binding.get("database") or "")
2317
  cell_key = str(tab.get("id")) + "!" + addr
2318
+ if only is not None and cell_key not in only:
2319
+ continue
2320
  scope_key = _binding_scope_key(session, db, binding)
2321
+ context = _refresh_context(book, binding, context_memo, tab=tab.get("id"),
2322
+ session=session)
2323
  hit = cache.get("refreshCells", {}).get(cell_key, {}).get(scope_key)
2324
  source_tokens = {}
2325
  try:
 
2339
  status.setdefault(db, "skipped")
2340
  continue
2341
  status[db] = "resolved"
2342
+ resolved_count += 1
2343
  previous = getattr(session, "_sheet_refresh_input", None)
2344
  session._sheet_refresh_input = cached_input
2345
  try:
2346
  out = _resolve_cell_binding(session, binding, book, tab.get("id"), view_memo=view_memo)
2347
  finally:
2348
  session._sheet_refresh_input = previous
2349
+ shared = _read_graph(session, book, fr, None)
2350
+ if shared is not None:
2351
+ shared["bound_values"][fr.a1_key(addr, scope_names.get(id(tab), ""))] = out
2352
  limits = list(out.get("limits") or [])
2353
  if not all(source_tokens.values()):
2354
  limits.append({"code": "change_token_unavailable",
 
2393
  tab_ref, addr = cell_key.split("!", 1)
2394
  _snapshot_cell(sheets.find_tab(book, tab_ref)["cells"][addr], entry["cell"])
2395
 
2396
+ resolve_ms = round((perf_counter() - started) * 1000.0)
2397
  started = perf_counter()
2398
  _recompute_formulas(book, fr, sheet_mod)
2399
  recalc_ms = round((perf_counter() - started) * 1000.0, 1)
2400
+ stats = _read_stats(session) or {}
2401
+ print(f"[sheet] refresh wb={workbook_id} cells={'all' if only is None else len(only)} "
2402
+ f"bound_resolved={resolved_count} engines={stats.get('engines', 0)} "
2403
+ f"input_hits={stats.get('input_hits', 0)} resolve_ms={resolve_ms} "
2404
+ f"recalc_ms={recalc_ms}", flush=True)
2405
  if editable:
2406
  try:
2407
  saved = sheets.put_workbook(store, workbook_id,
 
2416
  saved["refreshedFor"] = str(session.uname or "")
2417
  if entries:
2418
  sheet_binding.save_refresh_cache(store, workbook_id, entries, status)
2419
+ if only is not None:
2420
+ # ⛔ C5: a targeted answer carries ONLY the cells it resolved for this caller. The rest of
2421
+ # the document holds the owner's stored answers, which a scoped reader must never adopt.
2422
+ return {"workbook": {key: saved.get(key) for key in ("id", "name", "rev", "refreshed_at")},
2423
+ "cells": {cell_key: entry["cell"] for cell_key, _, entry in entries},
2424
+ "recalc_ms": recalc_ms,
2425
+ "binding_refresh": {"databases": status, "token_reads": token_reads}}
2426
  return {"workbook": _response_workbook(saved), "recalc_ms": recalc_ms,
2427
  "binding_refresh": {"databases": status, "token_reads": token_reads}}
2428
 
 
2568
  def _forget_sheet_database(session, database):
2569
  """A field write invalidates both request-local schema and materialised-column memos."""
2570
  getattr(session, "_sheet_assemblies", {}).pop(database, None)
2571
+ memo = getattr(session, "_sheet_read_memo", None)
2572
+ if isinstance(memo, dict):
2573
+ for slot in [slot for slot in memo if isinstance(slot, tuple) and slot[0] == "related"]:
2574
+ memo.pop(slot, None)
2575
  mirrors = getattr(session, "_sheet_mirrors", {})
2576
  for slot in list(mirrors):
2577
  if slot[0] == database:
 
2698
  return sheet_mod.period_window(period, today, cell_date=date)
2699
 
2700
 
2701
+ @contextlib.contextmanager
2702
+ def _sheet_request_scope(session):
2703
+ """HOTFIX 2026-09-29: one memo for one Sheet request, dropped when the request ends.
2704
+
2705
+ ⭐ The Session is built fresh per request (`deps.require_session`), but gates reuse one
2706
+ SimpleNamespace across calls, so the memo is OPT-IN, installed here and removed on exit.
2707
+ Inside it the workbook's authored cells cannot change: every door that opens a scope reads one
2708
+ document and resolves against it, so a cell read or a bound input answered once is the answer
2709
+ for the rest of the request. ⛔ Never open a scope around code that edits cells between two
2710
+ reads of the same document object (the Daily Sales repair projects in rounds and does not).
2711
+ """
2712
+ previous = getattr(session, "_sheet_read_memo", None)
2713
+ memo = {"stats": {"engines": 0, "resolves": 0, "input_hits": 0}}
2714
+ try:
2715
+ session._sheet_read_memo = memo
2716
+ except Exception: # noqa: BLE001
2717
+ yield None
2718
+ return
2719
+ try:
2720
+ yield memo
2721
+ finally:
2722
+ session._sheet_read_memo = previous
2723
+
2724
+
2725
+ def _read_stats(session):
2726
+ memo = getattr(session, "_sheet_read_memo", None)
2727
+ return memo.get("stats") if isinstance(memo, dict) else None
2728
+
2729
+
2730
+ def _read_graph(session, book, fr, today):
2731
+ """This request's cell map and formula graph for `book`, or None outside a request scope."""
2732
+ memo = getattr(session, "_sheet_read_memo", None)
2733
+ if not isinstance(memo, dict) or not isinstance(book, dict):
2734
+ return None
2735
+ slot = ("graph", id(book), str(today or ""))
2736
+ graph = memo.get(slot)
2737
+ if graph is None or graph["book"] is not book:
2738
+ graph = memo[slot] = _new_read_graph(book, fr, memo.get("stats"))
2739
+ return graph
2740
+
2741
+
2742
+ def _new_read_graph(book, fr, stats=None):
2743
+ tabs = book.get("sheets") or []
2744
+ names = _tab_scope_names(tabs)
2745
+ cells = {fr.a1_key(addr, name): cell for source, name in zip(tabs, names)
2746
+ for addr, cell in (source.get("cells") or {}).items() if isinstance(cell, dict)}
2747
+ return {"book": book, "names": names, "cells": cells,
2748
+ "bound": {k: c for k, c in cells.items() if c.get("kind") == "bound"},
2749
+ "engine": None, "attempted": set(), "failures": {}, "bound_values": {},
2750
+ "formulas": {}, "stats": stats}
2751
+
2752
+
2753
+ #: Where a filter formula is evaluated: a private one-formula engine, never a workbook address.
2754
+ _FORMULA_SLOT_ADDR = "XFD1048576"
2755
+
2756
+
2757
+ def _formula_slot(graph, fr, formula, home):
2758
+ """A filter formula, compiled once per request: (slot key, cells it reads, ranges it reads).
2759
+
2760
+ HOTFIX 2026-09-29 (owner: "make formula native inside the Cell database Filter so it can point
2761
+ to an existing date but we can use something like a date function refer to a cell"). A filter
2762
+ value slot holds a cell reference (`F7`) OR a formula (`=DATE($E$24,1,1)`), so a monthly total
2763
+ needs no helper cell holding its first and last day. `cells` is None when it does not compile.
2764
+ """
2765
+ cache = graph.setdefault("formulas", {})
2766
+ slot = (str(home).upper(), formula)
2767
+ if slot not in cache:
2768
+ vkey = fr.a1_key(_FORMULA_SLOT_ADDR, home)
2769
+ book = graph["book"]
2770
+ try:
2771
+ probe = fr.SheetCalculation({vkey: {"formula": formula, "sheet": home}},
2772
+ sheets=graph["names"], named_ranges=book.get("namedRanges"),
2773
+ date_system=book.get("dateSystem", "1900"))
2774
+ compiled = probe.compiled.get(vkey)
2775
+ except Exception: # noqa: BLE001
2776
+ compiled = None
2777
+ cache[slot] = (vkey, set(compiled["cells"]) if compiled else None,
2778
+ list(compiled["ranges"]) if compiled else [])
2779
+ return cache[slot]
2780
+
2781
+
2782
+ def _formula_slot_keys(graph, fr, formula, home):
2783
+ """Every workbook cell a filter formula reads (range members included), or [] if unreadable."""
2784
+ _vkey, reads, ranges = _formula_slot(graph, fr, formula, home)
2785
+ keys = set(reads or ())
2786
+ if ranges:
2787
+ engine = _read_engine(graph, graph["book"], fr, None)[0]
2788
+ for bounds in ranges:
2789
+ keys.update(engine.positions.within(bounds))
2790
+ return sorted(keys)
2791
+
2792
+
2793
+ def _read_binding_formula(session, formula, *, book, tab, today, seen, code, as_date):
2794
+ """A filter / ending value computed by a formula over this workbook's cells, never stored."""
2795
+ from modules import sheet as sheet_mod
2796
+ import formula_runtime as fr
2797
+
2798
+ def refuse(reason):
2799
+ exc = sheet_mod.SheetRefusal(code, formula, reason)
2800
+ exc.message = exc.message.replace("from cell =", "from formula =", 1)
2801
+ exc.args = (exc.message,)
2802
+ raise exc
2803
+
2804
+ graph = _read_graph(session, book, fr, today) or _new_read_graph(book, fr)
2805
+ home = _resolve_home_tab(book, book.get("sheets") or [], graph["names"], tab)
2806
+ vkey, reads, _ranges = _formula_slot(graph, fr, formula, home)
2807
+ if reads is None:
2808
+ refuse("the formula could not be read.")
2809
+ specs = {vkey: {"formula": formula, "sheet": home}}
2810
+ reasons = {}
2811
+ for key in _formula_slot_keys(graph, fr, formula, home):
2812
+ if key == vkey:
2813
+ continue
2814
+ if key in seen:
2815
+ refuse("the reference is circular.")
2816
+ cell = graph["cells"].get(key)
2817
+ if not isinstance(cell, dict) or cell.get("kind") == "empty":
2818
+ if key in reads:
2819
+ # A cell the formula names directly must hold something: a deleted input refuses
2820
+ # by name, as a cell reference does, never a year-zero date. The browser twin is
2821
+ # `sheetState.readFormulaSlot`. A blank range member stays blank.
2822
+ refuse(f"cell {key.rpartition('!')[2]} is blank.")
2823
+ continue
2824
+ try:
2825
+ specs[key] = {"value": _read_binding_cell(session, key, book=book, tab=tab, today=today,
2826
+ seen=seen, code=code),
2827
+ **({"style": cell["style"]} if isinstance(cell.get("style"), dict) else {})}
2828
+ except sheet_mod.SheetRefusal as exc:
2829
+ specs[key] = {"refused": exc.code}
2830
+ reasons[key] = exc.message
2831
+ probe = fr.SheetCalculation(specs, sheets=graph["names"], today=today,
2832
+ named_ranges=book.get("namedRanges"),
2833
+ date_system=book.get("dateSystem", "1900"))
2834
+ if probe.errors.get(vkey):
2835
+ error_code = probe.errors[vkey]
2836
+ refuse(next(iter(reasons.values()), None) or fr._sheet_error_message(error_code))
2837
+ value = probe.values.get(vkey)
2838
+ if value is None or isinstance(value, str) and not value.strip():
2839
+ refuse("its result is blank.")
2840
+ if (as_date and isinstance(value, (int, float)) and not isinstance(value, bool)
2841
+ and sheet_mod.date_formatted_cell({"style": {"format": probe.formats.get(vkey)}})):
2842
+ from harness import windows as W
2843
+ day = W.ending_cell_date(value, book.get("dateSystem", "1900"))
2844
+ if not day:
2845
+ refuse("its value is not a real date.")
2846
+ return day
2847
+ return value
2848
+
2849
+
2850
+ def _read_engine(graph, book, fr, today):
2851
+ """ONE formula engine per request, database inputs pending until a read needs them."""
2852
+ if graph["engine"] is None:
2853
+ specs = {k: ({"refused": "ending_input_pending"} if k in graph["bound"]
2854
+ else fr._document_spec(c, k.rpartition("!")[0]))
2855
+ for k, c in graph["cells"].items()}
2856
+ graph["engine"] = fr.SheetCalculation(
2857
+ specs, sheets=graph["names"], today=today,
2858
+ named_ranges=book.get("namedRanges"), date_system=book.get("dateSystem", "1900"))
2859
+ stats = graph.get("stats")
2860
+ if stats is not None:
2861
+ stats["engines"] += 1
2862
+ return graph["engine"], graph["attempted"], graph["failures"]
2863
+
2864
+
2865
+ def _bound_input(session, key, cell, *, book, today, seen, graph):
2866
+ """A bound cell read as an INPUT (a filter value, an ending date, a formula's operand).
2867
+
2868
+ Refresh's certified cache first, then this request's memo, then one real resolve. A refusal
2869
+ is memoized as the refusal: the same binding over the same document and the same database
2870
+ cannot answer differently twice in one request.
2871
+ """
2872
+ lookup = getattr(session, "_sheet_refresh_input", None)
2873
+ cached = lookup(key) if lookup is not None else None
2874
+ if cached is not None:
2875
+ return cached
2876
+ memo = graph["bound_values"] if graph is not None else None
2877
+ if memo is not None and key in memo:
2878
+ stats = _read_stats(session)
2879
+ if stats is not None:
2880
+ stats["input_hits"] += 1
2881
+ hit = memo[key]
2882
+ if isinstance(hit, HTTPException):
2883
+ raise hit
2884
+ return hit
2885
+ try:
2886
+ result = _resolve_binding(session, cell.get("binding"), today=today, book=book,
2887
+ tab=key.rpartition("!")[0], ending_seen=seen)
2888
+ except HTTPException as exc:
2889
+ if memo is not None:
2890
+ memo[key] = exc
2891
+ raise
2892
+ if memo is not None:
2893
+ memo[key] = result
2894
+ return result
2895
+
2896
+
2897
+ def _binding_input_refs(binding):
2898
+ """Every cell reference a binding reads: filter values at any depth and a period's ref."""
2899
+ from modules import sheet as sheet_mod
2900
+ if not isinstance(binding, dict):
2901
+ return []
2902
+ nodes = []
2903
+ for part in (binding.get("scope"), binding.get("related")):
2904
+ if isinstance(part, dict):
2905
+ found, _ = _fe_parts(part.get("filter"))
2906
+ nodes.extend(found)
2907
+ refs = [str((node.get(slot) or {}).get("ref") or "")
2908
+ for node in sheet_mod.filter_cell_nodes(nodes)
2909
+ for slot in ("valueRef", "value2Ref") if isinstance(node.get(slot), dict)]
2910
+ period = binding.get("period")
2911
+ if isinstance(period, dict) and period.get("ref"):
2912
+ refs.append(str(period["ref"]))
2913
+ return [ref for ref in refs if ref.strip()]
2914
+
2915
+
2916
+ def _qualified_refs(binding, home, fr, graph=None):
2917
+ out = []
2918
+ for ref in _binding_input_refs(binding):
2919
+ if ref.startswith("="):
2920
+ if graph is not None:
2921
+ out.extend(_formula_slot_keys(graph, fr, ref, home))
2922
+ continue
2923
+ try:
2924
+ out.append(_asked_key(ref, home, fr))
2925
+ except Exception: # noqa: BLE001
2926
+ continue
2927
+ return out
2928
+
2929
+
2930
+ def _dependent_bound_keys(book, graph, fr, edited):
2931
+ """HOTFIX 2026-09-29 (owner: "ONLY when we update ANY cells, its related cells also have to
2932
+ update, this includes the cell database"): the bound cells an edit can change, and no other.
2933
+
2934
+ Walks FORWARD from the edited keys over the formula graph's own reverse edges (the same three
2935
+ `SheetCalculation.update` walks: static reads, dynamic reads, range consumers) plus one more
2936
+ edge the formula graph cannot see: a bound cell's filter value / period reference. So editing
2937
+ `F6` reaches `F7 = G6-1`, and every binding filtering on `F7`, and every formula over those.
2938
+ ⛔ STRUCTURE, NEVER A VALUE DIFF: the stored values are last computed, not current, so an
2939
+ edit reverted to its old value would look unchanged and leave a binding on the edited answer.
2940
+ """
2941
+ from collections import deque
2942
+ engine = _read_engine(graph, book, fr, None)[0]
2943
+ readers = {}
2944
+ for key, cell in graph["bound"].items():
2945
+ if _is_view_binding(cell):
2946
+ continue
2947
+ for ref in _qualified_refs(cell.get("binding"), key.rpartition("!")[0], fr, graph):
2948
+ readers.setdefault(ref, set()).add(key)
2949
+ seen, queue = set(edited), deque(edited)
2950
+ while queue:
2951
+ key = queue.popleft()
2952
+ owners = (set(engine.read_by.get(key, ())) | set(engine.consumed_by.get(key, ()))
2953
+ | set(engine.ranges.at(key, engine.stats)) | readers.get(key, set()))
2954
+ for owner in owners:
2955
+ if owner not in seen:
2956
+ seen.add(owner)
2957
+ queue.append(owner)
2958
+ return {key for key in seen if key in graph["bound"] and key not in edited}
2959
+
2960
+
2961
+ def _input_closure(graph, engine, fr, roots):
2962
+ """Every cell a set of references reads, transitively, through formulas and bound inputs."""
2963
+ seen, pending = set(), list(roots)
2964
+ while pending:
2965
+ key = pending.pop()
2966
+ if key in seen:
2967
+ continue
2968
+ seen.add(key)
2969
+ cell = graph["cells"].get(key)
2970
+ if isinstance(cell, dict) and cell.get("kind") == "bound":
2971
+ pending.extend(_qualified_refs(cell.get("binding"), key.rpartition("!")[0], fr, graph))
2972
+ continue
2973
+ pending.extend(engine.reads.get(key, ()))
2974
+ pending.extend(engine.consumed.get(key, ()))
2975
+ compiled = engine.compiled.get(key)
2976
+ for bounds in (compiled or {}).get("ranges") or ():
2977
+ pending.extend(engine.positions.within(bounds))
2978
+ return seen
2979
+
2980
+
2981
  def _read_binding_cell(session, ref, *, book=None, tab=None, today=None, seen=(),
2982
  code="ending_cell_unreadable", as_date=False):
2983
  """Shared cell read for Ending and Filter, including scoped bound and formula inputs.
 
2992
  def refuse(reason):
2993
  raise sheet_mod.SheetRefusal(code, ref or "(blank)", reason)
2994
 
2995
+ if str(ref or "").strip().startswith("=") and book is not None:
2996
+ return _read_binding_formula(session, str(ref).strip(), book=book, tab=tab, today=today,
2997
+ seen=seen, code=code, as_date=as_date)
2998
  if not re.fullmatch(r"(?:(?:'([^']|'')+'|[^'!]+)!)?\$?[A-Za-z]{1,3}\$?[1-9][0-9]{0,6}", ref):
2999
  refuse("its reference is invalid.")
3000
  if book is None:
3001
  refuse("the source workbook is unavailable.")
3002
  tabs = book.get("sheets") or []
3003
+ # HOTFIX 2026-09-29 (owner: "MAKE IT FAST"): one request reads ONE graph. Before this, every
3004
+ # filter reference of every bound cell rebuilt the whole workbook's cell map and, for a formula
3005
+ # reference, a whole-workbook SheetCalculation (about 0.6 s each): Daily Sales has ~470 bound
3006
+ # cells reading `$E$10` and `F7`, so one commit or one Refresh paid ~900 engine builds.
3007
+ graph = _read_graph(session, book, fr, today)
3008
+ names = graph["names"] if graph is not None else _tab_scope_names(tabs)
3009
  home = _resolve_home_tab(book, tabs, names, tab)
3010
  key = _asked_key(ref, home, fr)
3011
  if key in seen:
3012
  refuse("the reference is circular.")
3013
+ cells = graph["cells"] if graph is not None else {
3014
+ fr.a1_key(addr, name): cell for source, name in zip(tabs, names)
3015
+ for addr, cell in (source.get("cells") or {}).items()}
3016
  cell = cells.get(key)
3017
  if not isinstance(cell, dict) or cell.get("kind") == "empty":
3018
  refuse("the cell or its sheet is missing or blank.")
3019
  if cell.get("kind") == "bound":
3020
  try:
3021
+ value = _bound_input(session, key, cell, book=book, today=today,
3022
+ seen=(*seen, key), graph=graph)["value"]
 
 
 
3023
  except HTTPException as exc:
3024
  reason = ((exc.detail or {}).get("error") or {}).get("message", "its source is refused.")
3025
  refuse(reason)
3026
  elif cell.get("kind") == "formula":
3027
  # The existing formula graph discovers actual inputs, including dynamic references.
3028
  # A database input starts refused, so a cached value can never bypass this reader's wall.
3029
+ bound = graph["bound"] if graph is not None else {
3030
+ k: c for k, c in cells.items() if c.get("kind") == "bound"}
3031
+ if graph is not None:
3032
+ engine, attempted, failures = _read_engine(graph, book, fr, today)
3033
+ else:
3034
+ specs = {k: ({"refused": "ending_input_pending"} if k in bound
3035
+ else fr._document_spec(c, k.rpartition("!")[0])) for k, c in cells.items()}
3036
+ engine = fr.SheetCalculation(specs, sheets=names, today=today,
3037
+ named_ranges=book.get("namedRanges"), date_system=book.get("dateSystem", "1900"))
3038
+ attempted, failures = set(), {}
3039
  while True:
3040
  dependencies, pending = set(), [key]
3041
  while pending:
 
3051
  for dependency in needed:
3052
  attempted.add(dependency)
3053
  try:
3054
+ result = _bound_input(session, dependency, bound[dependency], book=book,
3055
+ today=today, seen=(*seen, key, dependency), graph=graph)
 
 
 
3056
  changes[dependency] = {"value": result["value"]}
3057
  except HTTPException as exc:
3058
  info = ((exc.detail or {}).get("error") or {})
 
3481
  binding editor show a number before anyone commits the cell. R10 may create a missing Metric
3482
  field through the database's ordinary field writer; reusing a column needs no field write.
3483
  """
3484
+ with _sheet_request_scope(session):
3485
+ return _preview_cell_scoped(workbook_id, addr, body, session)
3486
+
3487
+
3488
+ def _preview_cell_scoped(workbook_id: str, addr: str, body, session: Session):
3489
  raw = dict(body or {})
3490
  binding = raw.get("binding") or {}
3491
  book = None
 
3593
  ⚠ `rev` BUMPS, BECAUSE THIS PERSISTS. It goes back in the answer and the client adopts it, or
3594
  its next PATCH would carry a revision the server has already moved past.
3595
  """
3596
+ with _sheet_request_scope(session):
3597
+ return _compute_cell_scoped(workbook_id, addr, body, session)
3598
+
3599
+
3600
+ def _compute_cell_scoped(workbook_id: str, addr: str, body, session: Session):
3601
  from core import sheets
3602
 
3603
  try:
 
3823
  no comparison text, and the count beside those ids is the LIVE count, because `LinkGridModal`
3824
  prints the length of what it is handed and runs no query of its own.
3825
  """
3826
+ with _sheet_request_scope(session):
3827
+ return _drill_cell_scoped(workbook_id, addr, tab, session)
3828
+
3829
+
3830
+ def _drill_cell_scoped(workbook_id: str, addr: str, tab, session: Session):
3831
  from core import sheets
3832
  from modules import sheet as sheet_mod
3833
  import core.perm_scope as perm_scope
 
4042
  database work, and a batch's cost is dominated by the number of distinct (database, period)
4043
  pairs in it rather than by the number of cells.
4044
  """
4045
+ with _sheet_request_scope(session):
4046
+ return _resolve_bindings_scoped(workbook_id, body, session)
4047
+
4048
+
4049
+ def _resolve_bindings_scoped(workbook_id: str, body, session: Session):
4050
  from core import sheets
4051
  import formula_runtime as fr
4052
 
platform/core/sheet_structure.py CHANGED
@@ -185,6 +185,11 @@ def _reanchor_binding(value, shift: dict, own_sheet: str) -> bool:
185
  if key in BINDING_REF_KEYS and isinstance(child, str) and parse_ref(child):
186
  value[key] = shift_for_structure(child, shift, own_sheet, bare=True)
187
  changed = value[key] != child or changed
 
 
 
 
 
188
  elif isinstance(child, (dict, list)):
189
  changed = _reanchor_binding(child, shift, own_sheet) or changed
190
  return changed
 
185
  if key in BINDING_REF_KEYS and isinstance(child, str) and parse_ref(child):
186
  value[key] = shift_for_structure(child, shift, own_sheet, bare=True)
187
  changed = value[key] != child or changed
188
+ elif key in BINDING_REF_KEYS and isinstance(child, str) and child.strip().startswith("="):
189
+ # HOTFIX 2026-09-29: a filter value slot may hold a FORMULA (`=DATE($E$24,1,1)`);
190
+ # its references follow a row or column edit exactly as a formula cell's do.
191
+ value[key] = shift_for_structure(child, shift, own_sheet)
192
+ changed = value[key] != child or changed
193
  elif isinstance(child, (dict, list)):
194
  changed = _reanchor_binding(child, shift, own_sheet) or changed
195
  return changed
web/public/AIOS_DEPLOY_RECEIPT CHANGED
@@ -1 +1 @@
1
- e5d3a8fb1dd0e6d32f148f0c9b0165b6ad27f497e106879681061f24ecd84c48
 
1
+ 7a903ae33939dd78c71c29baa2bf75363c7215239fc62423a8d2fb8f165daf4e
web/src/customer-grid/apiBridge.ts CHANGED
@@ -1317,6 +1317,16 @@ export async function probeRelatedRead(
1317
  * let one dropped packet replace a working table with an error card. The flag
1318
  * is passed explicitly at the one call site that owns the first paint.
1319
  */
 
 
 
 
 
 
 
 
 
 
1320
  export async function fetchWorkspace(
1321
  scope: SurfaceScope = "customer",
1322
  opts: { announceFailure?: boolean; allowCached?: boolean } = {},
 
1317
  * let one dropped packet replace a working table with an error card. The flag
1318
  * is passed explicitly at the one call site that owns the first paint.
1319
  */
1320
+ /**
1321
+ * HOTFIX 2026-09-29 (owner: "clicking edit for cell database ... is still very slow"). The memo's
1322
+ * answer for `scope` when it is inside its freshness window, WITHOUT a request, else null. A
1323
+ * panel paints from it at once and still asks the server; the server's answer replaces it.
1324
+ */
1325
+ export function peekWorkspace(scope: SurfaceScope): GridWorkspace | null {
1326
+ const hit = wsCache.get(scope);
1327
+ return hit && Date.now() - hit.at < CUSTOMERS_FRESH_MS ? workspaceWithoutMetricCells(hit.ws) : null;
1328
+ }
1329
+
1330
  export async function fetchWorkspace(
1331
  scope: SurfaceScope = "customer",
1332
  opts: { announceFailure?: boolean; allowCached?: boolean } = {},
web/src/filter-kit/FilterBuilderPanel.tsx CHANGED
@@ -700,23 +700,25 @@ const ISO_DAY = /^(\d{4})-(\d{2})-(\d{2})/;
700
  export function readFilterCell(read: FilterCellReader, ref: string, type: FieldType,
701
  asDate: boolean): { ok: boolean; text: string } {
702
  const at = ref.trim();
703
- if (!at) return { ok: false, text: "Type a cell, like F7." };
704
  const got = read(at);
705
- if (!got) return { ok: false, text: `${at} is not a cell. Type a cell, like F7.` };
706
  if (got.problem) return { ok: false, text: got.problem };
707
  const value = String(got.value ?? "").trim();
708
- if (!value) return { ok: false, text: `Cell ${at} is blank.` };
 
 
709
  if (asDate || isDateFamily(type)) {
710
  const m = ISO_DAY.exec(value);
711
  const day = m ? new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]))) : null;
712
  if (!m || !day || day.getUTCDate() !== Number(m[3]))
713
- return { ok: false, text: `Cell ${at} holds ${value}, which is not a date.` };
714
- return { ok: true, text: `Cell ${at} reads ${day.toLocaleDateString(undefined,
715
  { timeZone: "UTC", year: "numeric", month: "short", day: "numeric" })}` };
716
  }
717
  if (isNumericType(type) && !Number.isFinite(Number(value.replace(/,/g, ""))))
718
- return { ok: false, text: `Cell ${at} holds ${value}, which is not a number.` };
719
- return { ok: true, text: `Cell ${at} reads ${value}` };
720
  }
721
 
722
  /** One cell input and, under it, what the cell reads now or why it cannot be used. */
@@ -732,7 +734,7 @@ function CellRefInput({ slot, label, read, type, asDate, onRef }: {
732
  type="text"
733
  className="cg-input"
734
  aria-label={label}
735
- placeholder="F7"
736
  value={ref}
737
  aria-invalid={ref.trim() !== "" && !check.ok}
738
  onChange={(e) => onRef(e.target.value)}
 
700
  export function readFilterCell(read: FilterCellReader, ref: string, type: FieldType,
701
  asDate: boolean): { ok: boolean; text: string } {
702
  const at = ref.trim();
703
+ if (!at) return { ok: false, text: "Type a cell like F7, or a formula like =DATE(2026,1,1)." };
704
  const got = read(at);
705
+ if (!got) return { ok: false, text: `${at} is not a cell. Type a cell like F7, or a formula like =DATE(2026,1,1).` };
706
  if (got.problem) return { ok: false, text: got.problem };
707
  const value = String(got.value ?? "").trim();
708
+ // HOTFIX 2026-09-29: a slot may hold a formula; the sentence names which kind it read.
709
+ const subject = at.startsWith("=") ? "The formula" : `Cell ${at}`;
710
+ if (!value) return { ok: false, text: `${subject} is blank.` };
711
  if (asDate || isDateFamily(type)) {
712
  const m = ISO_DAY.exec(value);
713
  const day = m ? new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]))) : null;
714
  if (!m || !day || day.getUTCDate() !== Number(m[3]))
715
+ return { ok: false, text: `${subject} holds ${value}, which is not a date.` };
716
+ return { ok: true, text: `${subject} reads ${day.toLocaleDateString(undefined,
717
  { timeZone: "UTC", year: "numeric", month: "short", day: "numeric" })}` };
718
  }
719
  if (isNumericType(type) && !Number.isFinite(Number(value.replace(/,/g, ""))))
720
+ return { ok: false, text: `${subject} holds ${value}, which is not a number.` };
721
+ return { ok: true, text: `${subject} reads ${value}` };
722
  }
723
 
724
  /** One cell input and, under it, what the cell reads now or why it cannot be used. */
 
734
  type="text"
735
  className="cg-input"
736
  aria-label={label}
737
+ placeholder="F7 or =DATE(2026,1,1)"
738
  value={ref}
739
  aria-invalid={ref.trim() !== "" && !check.ok}
740
  onChange={(e) => onRef(e.target.value)}
web/src/sheet/BindingEditor.tsx CHANGED
@@ -38,7 +38,7 @@
38
 
39
  import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
40
  import { API_V1, CREDENTIALS } from "../apiContract";
41
- import { fetchTopicRows, fetchWorkspace } from "../customer-grid/apiBridge";
42
  import type { SurfaceScope } from "../customer-grid/apiBridge";
43
  import { dayText } from "../customer-grid/display";
44
  import { FieldSelectButton } from "../customer-grid/FieldSelect";
@@ -60,6 +60,7 @@ import type { RelatedFilterField } from "../filter-kit/FilterBuilderPanel";
60
  import { WindowPicker } from "../filter-kit/WindowPicker";
61
  import { useEscapeClose } from "../ui/useEscapeClose";
62
  import { previewCell, readWorkbook } from "./sheetApi";
 
63
  import DrillModal from "./DrillModal";
64
  import { formatRef, parseRef } from "./a1";
65
  import { bindingAggregate, bindingDisplay, bindingFilterClauses, bindingOnDrag, bindingPeriod, bindingRelated,
@@ -716,10 +717,18 @@ export interface BindingEditorProps {
716
  onCancel: () => void;
717
  /** What a referenced cell reads now, so a filter value taken from a cell is shown, not blank. */
718
  readCell?: ReadBindingCell;
 
 
 
 
 
 
 
 
719
  }
720
 
721
  export default function BindingEditor({
722
- workbookId, addr, databases, initial, onSave, onCancel, readCell,
723
  }: BindingEditorProps) {
724
  const [activeSection, setActiveSection] = useState<typeof BINDING_SECTIONS[number]["key"]>("data");
725
  const [shape, setShape] = useState<"value" | "view">(initial?.mode === "view" ? "view" : "value");
@@ -1005,6 +1014,18 @@ export default function BindingEditor({
1005
  setOptionsResolved(true);
1006
  return () => { live = false; };
1007
  }
 
 
 
 
 
 
 
 
 
 
 
 
1008
  (async () => {
1009
  // ONE door, and it is the one that knows what exists now.
1010
  const fresh = await fetchWorkspace(scope);
@@ -1240,6 +1261,12 @@ export default function BindingEditor({
1240
  const showMetricPeriod = chosenIsMetric || filterUsesMetric;
1241
  useEffect(() => {
1242
  if (!showMetricPeriod || !periodOn || periodMode !== "window" || ending !== "cell") return;
 
 
 
 
 
 
1243
  let cancelled = false;
1244
  void readWorkbook(workbookId).then((got) => {
1245
  if (cancelled) return;
@@ -1248,7 +1275,7 @@ export default function BindingEditor({
1248
  setEndingSheet((held) => held || got.value.sheets[0]?.name || "");
1249
  });
1250
  return () => { cancelled = true; };
1251
- }, [workbookId, showMetricPeriod, periodOn, periodMode, ending]);
1252
  const canStepPeriod = chosenIsMetric || shape === "view";
1253
  const periodClauseLabel = shape === "view" ? "Metric period"
1254
  : `Metric period of ${measures.find((m) => m.key === metricKey)?.label || metricKey || "Metric"}`;
@@ -1369,12 +1396,17 @@ export default function BindingEditor({
1369
  try {
1370
  const filterRefs = bindingRefSlots(binding).filter((slot) => slot.kind === "filter");
1371
  if (filterRefs.length) {
1372
- const got = await readWorkbook(workbookId);
1373
- if (!got.ok) throw new Error(got.message);
1374
  const scope = binding.scope as { filter: FilterTree };
1375
  let previewTree = scope.filter;
 
 
 
 
 
1376
  for (const slot of filterRefs) {
1377
- const operand = resolveFilterCell(got.value, slot.text);
 
 
1378
  previewTree = updateFilterValueLeaf(previewTree, slot.indices!, (node) => ({ ...node,
1379
  value: operand, ...((MULTI_VALUE_OPS as ReadonlySet<string>).has(node.op) ? { values: [operand] } : {}),
1380
  }));
@@ -1389,9 +1421,12 @@ export default function BindingEditor({
1389
  throw new Error(`Ending cannot be more than ${MAX_N} before today.`);
1390
  }
1391
  if (ending === "cell") {
1392
- const got = await readWorkbook(workbookId);
1393
- if (!got.ok) throw new Error(got.message);
1394
- value = resolveEndingCell(got.value, endingRef);
 
 
 
1395
  }
1396
  const today = new Date();
1397
  const day = `${today.getFullYear()}-${pad2(today.getMonth() + 1)}-${pad2(today.getDate())}`;
@@ -1414,7 +1449,7 @@ export default function BindingEditor({
1414
  setPreview("");
1415
  const prepared = await prepareBinding();
1416
  if (!prepared) return;
1417
- const got = await previewCell(workbookId, addr, prepared);
1418
  if (!got.ok) {
1419
  setNotice(got.message);
1420
  return;
 
38
 
39
  import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
40
  import { API_V1, CREDENTIALS } from "../apiContract";
41
+ import { fetchTopicRows, fetchWorkspace, peekWorkspace } from "../customer-grid/apiBridge";
42
  import type { SurfaceScope } from "../customer-grid/apiBridge";
43
  import { dayText } from "../customer-grid/display";
44
  import { FieldSelectButton } from "../customer-grid/FieldSelect";
 
60
  import { WindowPicker } from "../filter-kit/WindowPicker";
61
  import { useEscapeClose } from "../ui/useEscapeClose";
62
  import { previewCell, readWorkbook } from "./sheetApi";
63
+ import type { Workbook } from "./types";
64
  import DrillModal from "./DrillModal";
65
  import { formatRef, parseRef } from "./a1";
66
  import { bindingAggregate, bindingDisplay, bindingFilterClauses, bindingOnDrag, bindingPeriod, bindingRelated,
 
717
  onCancel: () => void;
718
  /** What a referenced cell reads now, so a filter value taken from a cell is shown, not blank. */
719
  readCell?: ReadBindingCell;
720
+ /**
721
+ * HOTFIX 2026-09-29 (owner: "clicking edit for cell database ... is still very slow"). The
722
+ * workbook the page is already painting. Preview and Save read their cell values from it
723
+ * instead of downloading the whole workbook again (twice per Preview, before this).
724
+ */
725
+ workbook?: Workbook;
726
+ /** The tab the edited cell is on, so a bare reference like `F8` is read on THAT tab. */
727
+ homeTab?: { id: string; name: string };
728
  }
729
 
730
  export default function BindingEditor({
731
+ workbookId, addr, databases, initial, onSave, onCancel, readCell, workbook, homeTab,
732
  }: BindingEditorProps) {
733
  const [activeSection, setActiveSection] = useState<typeof BINDING_SECTIONS[number]["key"]>("data");
734
  const [shape, setShape] = useState<"value" | "view">(initial?.mode === "view" ? "view" : "value");
 
1014
  setOptionsResolved(true);
1015
  return () => { live = false; };
1016
  }
1017
+ // HOTFIX 2026-09-29: a scope this page read moments ago paints NOW from the memo, so a second
1018
+ // Edit does not sit on a skeleton for a multi-second assembly. The server read below still
1019
+ // runs and replaces these lists (and drops a view that no longer exists) when it answers.
1020
+ const memo = peekWorkspace(scope);
1021
+ if (memo) {
1022
+ setFields((memo.fields ?? []) as Field[]);
1023
+ setMeasures(memo.measures ?? []);
1024
+ setViews(viewList(memo.views));
1025
+ setUserOptions(memo.userOptions ?? []);
1026
+ setViewsLoaded(true);
1027
+ setOptionsResolved(true);
1028
+ }
1029
  (async () => {
1030
  // ONE door, and it is the one that knows what exists now.
1031
  const fresh = await fetchWorkspace(scope);
 
1261
  const showMetricPeriod = chosenIsMetric || filterUsesMetric;
1262
  useEffect(() => {
1263
  if (!showMetricPeriod || !periodOn || periodMode !== "window" || ending !== "cell") return;
1264
+ if (workbook) {
1265
+ // HOTFIX 2026-09-29: the tab names are already painted; no whole-workbook download for them.
1266
+ setEndingSheets(workbook.sheets.map(({ id, name }) => ({ id, name })));
1267
+ setEndingSheet((held) => held || homeTab?.name || workbook.sheets[0]?.name || "");
1268
+ return;
1269
+ }
1270
  let cancelled = false;
1271
  void readWorkbook(workbookId).then((got) => {
1272
  if (cancelled) return;
 
1275
  setEndingSheet((held) => held || got.value.sheets[0]?.name || "");
1276
  });
1277
  return () => { cancelled = true; };
1278
+ }, [workbookId, showMetricPeriod, periodOn, periodMode, ending, workbook, homeTab?.name]);
1279
  const canStepPeriod = chosenIsMetric || shape === "view";
1280
  const periodClauseLabel = shape === "view" ? "Metric period"
1281
  : `Metric period of ${measures.find((m) => m.key === metricKey)?.label || metricKey || "Metric"}`;
 
1396
  try {
1397
  const filterRefs = bindingRefSlots(binding).filter((slot) => slot.kind === "filter");
1398
  if (filterRefs.length) {
 
 
1399
  const scope = binding.scope as { filter: FilterTree };
1400
  let previewTree = scope.filter;
1401
+ const source = workbook ?? await (async () => {
1402
+ const got = await readWorkbook(workbookId);
1403
+ if (!got.ok) throw new Error(got.message);
1404
+ return got.value;
1405
+ })();
1406
  for (const slot of filterRefs) {
1407
+ const read = readCell && (workbook || slot.text.startsWith("=")) ? readCell(slot.text) : null;
1408
+ if (read?.problem) throw new Error(read.problem);
1409
+ const operand = read ? read.value : resolveFilterCell(source, slot.text, homeTab?.name);
1410
  previewTree = updateFilterValueLeaf(previewTree, slot.indices!, (node) => ({ ...node,
1411
  value: operand, ...((MULTI_VALUE_OPS as ReadonlySet<string>).has(node.op) ? { values: [operand] } : {}),
1412
  }));
 
1421
  throw new Error(`Ending cannot be more than ${MAX_N} before today.`);
1422
  }
1423
  if (ending === "cell") {
1424
+ const source = workbook ?? await (async () => {
1425
+ const got = await readWorkbook(workbookId);
1426
+ if (!got.ok) throw new Error(got.message);
1427
+ return got.value;
1428
+ })();
1429
+ value = resolveEndingCell(source, endingRef, homeTab?.name);
1430
  }
1431
  const today = new Date();
1432
  const day = `${today.getFullYear()}-${pad2(today.getMonth() + 1)}-${pad2(today.getDate())}`;
 
1449
  setPreview("");
1450
  const prepared = await prepareBinding();
1451
  if (!prepared) return;
1452
+ const got = await previewCell(workbookId, addr, prepared, homeTab?.id);
1453
  if (!got.ok) {
1454
  setNotice(got.message);
1455
  return;
web/src/sheet/SheetPage.tsx CHANGED
@@ -66,7 +66,7 @@ import SheetRail from "./SheetRail";
66
  import type { RailStrata } from "./SheetRail";
67
  import {
68
  computeCell, createdFolderIds, createWorkbook, deleteWorkbook, patchTabCells, readIndex, readTab, readTabMeta,
69
- placementOnlyDelta, readWorkbook, refreshWorkbook, writeIndex, writePlacements, writeWorkbook,
70
  } from "./sheetApi";
71
  import type { SheetIndex } from "./sheetApi";
72
  // ⛔⛔ W51-T10 / R6 — THE ONE CONFIRM DIALOG (contract C8). The sheet-delete prompt below used to
@@ -90,7 +90,7 @@ import {
90
  drillAffordance, emptyHistory, growSheet, moveTab, pushHistory, redoHistory, removeTab,
91
  removeTabRefusal, renameTab, renameTabRefusal, setColumnWidth, setFreeze, setTabView,
92
  reanchorWorkbookForMove, setTabVisibility, splitAddress, structureRefusal, tabCellCount, undoHistory,
93
- withCells, withRowGroupsTab,
94
  } from "./sheetState";
95
  import type { MovedBlock, SheetHistory, StructureOp } from "./sheetState";
96
  import { bindingDisplay, emptyIndex, ROOT_FOLDER_ID, sheetExtent, withBindingDisplay } from "./types";
@@ -1036,72 +1036,80 @@ export default function SheetPage() {
1036
  if (!painted || painted.id !== wid
1037
  || !tabLoadedRef.current.has(tabKeyOf(wid, loadedTab))) return;
1038
  const loaded = painted.sheets.find((tab) => tab.id === loadedTab);
1039
- if (!loaded || !Object.values(loaded.cells).some((cell) => cell.kind === "bound"
1040
- && cell.state === "refused" && cell.refusal?.code === "sheet_refresh_required")) return;
 
 
 
 
 
 
 
1041
  const pass = { id: wid, restore: () => restoreMarkedCells() };
1042
  openRefreshRef.current = pass;
1043
 
1044
  const marked = new Map<string, { before: Cell; pending: Cell }>();
1045
- const sheets = painted.sheets.map((tab) => {
1046
- if (tab.id !== loadedTab || !tabLoadedRef.current.has(tabKeyOf(wid, tab.id))) return tab;
1047
- let changed = false;
1048
- const cells = { ...tab.cells };
1049
- for (const [addr, cell] of Object.entries(tab.cells)) {
1050
- if (cell.kind !== "bound" || cell.state === "stale") continue;
1051
- const pending: Cell = { ...cell, state: "stale" };
1052
- marked.set(addr, { before: cell, pending });
1053
- cells[addr] = pending;
1054
- changed = true;
1055
- }
1056
- return changed ? { ...tab, cells } : tab;
1057
- });
1058
- if (marked.size > 0) applyLocal({ ...painted, sheets });
1059
 
1060
  const restoreMarkedCells = () => {
1061
- if (marked.size === 0) return;
1062
  const live = bookRef.current;
1063
  if (!live || live.id !== wid) return;
1064
  let restored = false;
1065
  const restoredSheets = live.sheets.map((tab) => {
1066
  if (tab.id !== loadedTab) return tab;
1067
- const cells = { ...tab.cells };
1068
  for (const [addr, held] of marked.entries()) {
1069
- if (cells[addr] !== held.pending) continue;
1070
- cells[addr] = held.before;
1071
  restored = true;
1072
  }
1073
- return restored ? { ...tab, cells } : tab;
1074
  });
1075
  if (restored) applyLocal({ ...live, sheets: restoredSheets });
1076
  };
1077
 
1078
- const refreshSeq = editSeqRef.current;
1079
  refreshExportBarrierRef.current = (async () => {
1080
- const got = await refreshWorkbook(wid, refreshRequestsRef.current);
1081
  const live = bookRef.current;
1082
- if (live?.id === wid) {
1083
- const rev = got.ok ? got.value.workbook.rev : got.rev_current;
1084
- if (typeof rev === "number" && rev >= live.rev) applyLocal({ ...live, rev });
1085
- }
1086
- if (openRefreshRef.current !== pass || !live || live.id !== wid
1087
- || editSeqRef.current !== refreshSeq || dirtyRef.current.size > 0
1088
- || structureDirtyRef.current || !got.ok || got.value.workbook.rev < live.rev) {
1089
  restoreMarkedCells();
1090
  if (openRefreshRef.current === pass) openRefreshRef.current = null;
1091
  return;
1092
  }
1093
- // A refresh replaces the same tree and dirty addresses as the button's refresh does.
1094
- historyRef.current = emptyHistory();
1095
- editSeqRef.current += 1;
1096
- dirtyRef.current = new Map();
1097
- markAllLoaded(got.value.workbook);
1098
- applyLocal(got.value.workbook);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1099
  if (openRefreshRef.current === pass) openRefreshRef.current = null;
1100
  })().catch(() => {
1101
  restoreMarkedCells();
1102
  if (openRefreshRef.current === pass) openRefreshRef.current = null;
1103
  });
1104
- }, [applyLocal, markAllLoaded]);
1105
 
1106
  /** The tab bar's own door: switch, then fetch the cells if this is the first visit. */
1107
  const openTab = useCallback((id: string) => {
@@ -1337,6 +1345,32 @@ export default function SheetPage() {
1337
  if (live?.id === current.id && sent.value.rev) {
1338
  applyLocal({ ...live, rev: sent.value.rev });
1339
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1340
  const refused = sent.value.refused ?? [];
1341
  const conflicts = sent.value.conflicts ?? [];
1342
  if (conflicts.length > 0) {
@@ -1505,8 +1539,13 @@ export default function SheetPage() {
1505
  if (outcome !== "route_absent") return;
1506
  }
1507
  await sendWholeWorkbook();
 
 
 
 
 
1508
  });
1509
- }, [sendDirtyCells, sendWholeWorkbook]);
1510
 
1511
  useEffect(() => { drainRef.current = drainSave; }, [drainSave]);
1512
 
@@ -3394,9 +3433,16 @@ export default function SheetPage() {
3394
  initial={(tab?.cells?.[editAt]?.binding as Record<string, unknown>) ?? null}
3395
  onSave={onSaveBinding}
3396
  onCancel={() => setEditAt("")}
 
 
3397
  readCell={(text) => {
3398
  // The same reader the drag and resolve paths use, so the panel shows what a refresh
3399
  // would read. A bare reference is about the tab the edited cell is on.
 
 
 
 
 
3400
  const ref = parseRef(text);
3401
  if (!ref) return null;
3402
  let value = "", problem = "";
 
66
  import type { RailStrata } from "./SheetRail";
67
  import {
68
  computeCell, createdFolderIds, createWorkbook, deleteWorkbook, patchTabCells, readIndex, readTab, readTabMeta,
69
+ placementOnlyDelta, readWorkbook, refreshCells, refreshWorkbook, writeIndex, writePlacements, writeWorkbook,
70
  } from "./sheetApi";
71
  import type { SheetIndex } from "./sheetApi";
72
  // ⛔⛔ W51-T10 / R6 — THE ONE CONFIRM DIALOG (contract C8). The sheet-delete prompt below used to
 
90
  drillAffordance, emptyHistory, growSheet, moveTab, pushHistory, redoHistory, removeTab,
91
  removeTabRefusal, renameTab, renameTabRefusal, setColumnWidth, setFreeze, setTabView,
92
  reanchorWorkbookForMove, setTabVisibility, splitAddress, structureRefusal, tabCellCount, undoHistory,
93
+ withCells, withRowGroupsTab, readFormulaSlot,
94
  } from "./sheetState";
95
  import type { MovedBlock, SheetHistory, StructureOp } from "./sheetState";
96
  import { bindingDisplay, emptyIndex, ROOT_FOLDER_ID, sheetExtent, withBindingDisplay } from "./types";
 
1036
  if (!painted || painted.id !== wid
1037
  || !tabLoadedRef.current.has(tabKeyOf(wid, loadedTab))) return;
1038
  const loaded = painted.sheets.find((tab) => tab.id === loadedTab);
1039
+ // ⭐⭐ HOTFIX 2026-09-29 (owner: "the whole sheet cell database is pulsing because its still
1040
+ // loading ... we should only update or refresh cells that are affected"). ONE cell without an
1041
+ // answer used to mark EVERY bound cell on the tab pending and re-resolve the WHOLE workbook
1042
+ // (~470 cells, minutes on Daily Sales). Now only the cells that need it are marked, sent to
1043
+ // `POST /refresh {cells}`, and merged back one by one; every other cell keeps its answer.
1044
+ const needs = loaded ? Object.entries(loaded.cells).filter(([, cell]) => cell.kind === "bound"
1045
+ && (cell.state === "stale"
1046
+ || (cell.state === "refused" && cell.refusal?.code === "sheet_refresh_required"))) : [];
1047
+ if (needs.length === 0) return;
1048
  const pass = { id: wid, restore: () => restoreMarkedCells() };
1049
  openRefreshRef.current = pass;
1050
 
1051
  const marked = new Map<string, { before: Cell; pending: Cell }>();
1052
+ const cells = { ...loaded!.cells };
1053
+ for (const [addr, cell] of needs) {
1054
+ const pending: Cell = cell.state === "stale" ? cell : { ...cell, state: "stale" };
1055
+ marked.set(addr, { before: cell, pending });
1056
+ cells[addr] = pending;
1057
+ }
1058
+ applyLocal({ ...painted, sheets: painted.sheets.map((tab) =>
1059
+ tab.id === loadedTab ? { ...tab, cells } : tab) });
 
 
 
 
 
 
1060
 
1061
  const restoreMarkedCells = () => {
 
1062
  const live = bookRef.current;
1063
  if (!live || live.id !== wid) return;
1064
  let restored = false;
1065
  const restoredSheets = live.sheets.map((tab) => {
1066
  if (tab.id !== loadedTab) return tab;
1067
+ const next = { ...tab.cells };
1068
  for (const [addr, held] of marked.entries()) {
1069
+ if (next[addr] !== held.pending || held.pending === held.before) continue;
1070
+ next[addr] = held.before;
1071
  restored = true;
1072
  }
1073
+ return restored ? { ...tab, cells: next } : tab;
1074
  });
1075
  if (restored) applyLocal({ ...live, sheets: restoredSheets });
1076
  };
1077
 
 
1078
  refreshExportBarrierRef.current = (async () => {
1079
+ const got = await refreshCells(wid, [...marked.keys()].map((addr) => `${loadedTab}!${addr}`));
1080
  const live = bookRef.current;
1081
+ if (!got.ok || !live || live.id !== wid) {
 
 
 
 
 
 
1082
  restoreMarkedCells();
1083
  if (openRefreshRef.current === pass) openRefreshRef.current = null;
1084
  return;
1085
  }
1086
+ // Merged CELL BY CELL: a cell the reader edited meanwhile is no longer the pending object
1087
+ // this pass painted, so its answer is dropped and their edit stands. No history is cleared.
1088
+ let changed = false;
1089
+ const sheets = live.sheets.map((tab) => {
1090
+ if (tab.id !== loadedTab) return tab;
1091
+ const next = { ...tab.cells };
1092
+ for (const [addr, held] of marked.entries()) {
1093
+ const row = got.value.cells[`${loadedTab}!${addr}`];
1094
+ if (next[addr] !== held.pending) continue;
1095
+ if (!row) { if (held.pending !== held.before) { next[addr] = held.before; changed = true; } continue; }
1096
+ const merged: Cell = { ...held.before, value: row.value, display: row.display,
1097
+ state: row.state as Cell["state"] };
1098
+ if (row.refusal) merged.refusal = row.refusal; else delete merged.refusal;
1099
+ if (row.refreshed_at) merged.refreshed_at = row.refreshed_at;
1100
+ next[addr] = merged;
1101
+ changed = true;
1102
+ }
1103
+ return changed ? { ...tab, cells: next } : tab;
1104
+ });
1105
+ const rev = typeof got.value.rev === "number" ? got.value.rev : live.rev;
1106
+ if (changed || rev > live.rev) applyLocal({ ...live, sheets, rev: Math.max(rev, live.rev) });
1107
  if (openRefreshRef.current === pass) openRefreshRef.current = null;
1108
  })().catch(() => {
1109
  restoreMarkedCells();
1110
  if (openRefreshRef.current === pass) openRefreshRef.current = null;
1111
  });
1112
+ }, [applyLocal]);
1113
 
1114
  /** The tab bar's own door: switch, then fetch the cells if this is the first visit. */
1115
  const openTab = useCallback((id: string) => {
 
1345
  if (live?.id === current.id && sent.value.rev) {
1346
  applyLocal({ ...live, rev: sent.value.rev });
1347
  }
1348
+ // ⭐⭐ HOTFIX 2026-09-29 (owner: "ONLY when we update ANY cells, its related cells also
1349
+ // have to update, this includes the cell database"). The server re-resolves exactly the
1350
+ // database cells this commit feeds and returns them in `computed`; this client used to
1351
+ // parse that and throw it away, so a bound cell kept its old number until a reload. A
1352
+ // cell the reader has edited again since is left alone: their newer edit wins.
1353
+ const answered = bookRef.current;
1354
+ if (answered?.id === current.id) {
1355
+ let touched = false;
1356
+ const again = dirtyRef.current.get(tabKey);
1357
+ const sheets = answered.sheets.map((t) => {
1358
+ if (t.id !== tabKey) return t;
1359
+ const next = { ...t.cells };
1360
+ for (const [addr, row] of Object.entries(sent.value.computed ?? {})) {
1361
+ const cell = next[addr];
1362
+ if (!cell || cell.kind !== "bound" || again?.has(addr)) continue;
1363
+ if (cell.value === row.value && cell.state === row.state && !cell.refusal === !row.refusal) continue;
1364
+ const merged: Cell = { ...cell, value: row.value, display: row.display,
1365
+ state: row.state as Cell["state"] };
1366
+ if (row.refusal) merged.refusal = row.refusal; else delete merged.refusal;
1367
+ next[addr] = merged;
1368
+ touched = true;
1369
+ }
1370
+ return touched ? { ...t, cells: next } : t;
1371
+ });
1372
+ if (touched) applyLocal({ ...answered, sheets });
1373
+ }
1374
  const refused = sent.value.refused ?? [];
1375
  const conflicts = sent.value.conflicts ?? [];
1376
  if (conflicts.length > 0) {
 
1539
  if (outcome !== "route_absent") return;
1540
  }
1541
  await sendWholeWorkbook();
1542
+ // HOTFIX 2026-09-29: a row or column edit leaves the bound cells whose references moved
1543
+ // `stale`, and nothing resolved them, so they shimmered until a manual Refresh. Resolve
1544
+ // exactly those cells now that the new structure is saved.
1545
+ const after = bookRef.current;
1546
+ if (structural && after && tabIdRef.current) refreshOpenedWorkbook(after.id, tabIdRef.current);
1547
  });
1548
+ }, [sendDirtyCells, sendWholeWorkbook, refreshOpenedWorkbook]);
1549
 
1550
  useEffect(() => { drainRef.current = drainSave; }, [drainSave]);
1551
 
 
3433
  initial={(tab?.cells?.[editAt]?.binding as Record<string, unknown>) ?? null}
3434
  onSave={onSaveBinding}
3435
  onCancel={() => setEditAt("")}
3436
+ workbook={book}
3437
+ homeTab={tab ? { id: tab.id, name: tab.name } : undefined}
3438
  readCell={(text) => {
3439
  // The same reader the drag and resolve paths use, so the panel shows what a refresh
3440
  // would read. A bare reference is about the tab the edited cell is on.
3441
+ // HOTFIX 2026-09-29: a slot may hold a FORMULA (`=DATE($E$24,1,1)`), read on this tab.
3442
+ if (text.trim().startsWith("=")) {
3443
+ const got = readFormulaSlot(book, text.trim(), tab);
3444
+ return { value: got.value, problem: got.problem ?? "", formula: text.trim() };
3445
+ }
3446
  const ref = parseRef(text);
3447
  if (!ref) return null;
3448
  let value = "", problem = "";
web/src/sheet/sheetApi.ts CHANGED
@@ -379,13 +379,43 @@ export const previewCell = (
379
  id: string,
380
  addr: string,
381
  binding: Record<string, unknown>,
 
382
  ): Promise<Result<{ value: unknown; display: string }>> =>
383
  call(
384
  `/sheets/${encodeURIComponent(id)}/cells/${encodeURIComponent(addr)}/preview`,
385
- sends("POST", { binding: normalizeCellBinding(binding) }),
 
 
386
  (body) => body as { value: unknown; display: string },
387
  );
388
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
389
  /**
390
  * W54-T32 (instruction 9): what `POST /sheets/{id}/cells/{addr}/compute` answers.
391
  *
 
379
  id: string,
380
  addr: string,
381
  binding: Record<string, unknown>,
382
+ tab?: string,
383
  ): Promise<Result<{ value: unknown; display: string }>> =>
384
  call(
385
  `/sheets/${encodeURIComponent(id)}/cells/${encodeURIComponent(addr)}/preview`,
386
+ // Hotfix 2026-09-29: the edited cell's tab rides along, so a bare `F8` in a filter is read on
387
+ // THAT tab. Without it the server read the first tab's F8 for a cell on any other tab.
388
+ sends("POST", { binding: normalizeCellBinding(binding), ...(tab ? { tab } : {}) }),
389
  (body) => body as { value: unknown; display: string },
390
  );
391
 
392
+ /** One refreshed bound cell, keyed `<tab id>!<ADDR>`, as `POST /refresh {cells}` answers it. */
393
+ export interface RefreshedCell extends CellComputed {
394
+ refreshed_at?: string;
395
+ limits?: unknown[];
396
+ }
397
+
398
+ /**
399
+ * Hotfix 2026-09-29 (owner: "we should only update or refresh cells that are affected"). Refresh
400
+ * ONLY the named bound cells, `<tab id>!<ADDR>` each. Every other cell keeps its answer, and the
401
+ * reply carries only these cells plus the revision the workbook is now at.
402
+ */
403
+ export const refreshCells = (
404
+ id: string, cells: readonly string[],
405
+ ): Promise<Result<{ rev: number | null; cells: Record<string, RefreshedCell> }>> =>
406
+ call(`/sheets/${encodeURIComponent(id)}/refresh`, sends("POST", { cells }), (body) => {
407
+ const raw = (body as { workbook?: { rev?: unknown }; cells?: unknown } | null) ?? {};
408
+ const rev = typeof raw.workbook?.rev === "number" ? raw.workbook.rev : null;
409
+ const out: Record<string, RefreshedCell> = {};
410
+ for (const [key, row] of Object.entries(asComputed(raw.cells))) {
411
+ const extra = ((raw.cells as Record<string, Record<string, unknown>>)[key]) ?? {};
412
+ out[key] = { ...row,
413
+ ...(typeof extra.refreshed_at === "string" ? { refreshed_at: extra.refreshed_at } : {}),
414
+ ...(Array.isArray(extra.limits) ? { limits: extra.limits } : {}) };
415
+ }
416
+ return { rev, cells: out };
417
+ });
418
+
419
  /**
420
  * W54-T32 (instruction 9): what `POST /sheets/{id}/cells/{addr}/compute` answers.
421
  *
web/src/sheet/sheetState.ts CHANGED
@@ -41,8 +41,8 @@ import type { SavedViewShadow } from "./bindingRefs";
41
  // `get(addr) => CellValue` callback and knows nothing about a `Cell`. `cellToValue`, below, is the
42
  // one door that turns this file's `Cell` into that shape, so the evaluator itself never has to.
43
  import {
44
- CYCLE_REFUSAL, ERROR_REF, evaluateFormula, formulaReferenceKey,
45
- WorkbookCalculation as FormulaCalculation, workbookFormulaGetter,
46
  } from "./formulaEval";
47
  import type { CellValue, QualifiedFormula, SpillChildMarker, FormulaErrorCode } from "./formulaEval";
48
  import { copyCell, replaceCellStyle } from "./cellStyleOps";
@@ -465,10 +465,68 @@ const qualifiedKeyParts = (key: string): { sheet: string; addr: string } => {
465
  : { sheet: key.slice(0, bang).toUpperCase(), addr: key.slice(bang + 1).toUpperCase() };
466
  };
467
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
468
  /** One mounted workbook owns this cache; no tenant values enter a process-global cache. */
469
  export class WorkbookCalculationSession {
470
  readonly engine = new FormulaCalculation();
471
  sheets: readonly SheetTab[] = [];
 
 
 
 
 
 
 
 
 
 
472
  metadata = "";
473
  revision = -1;
474
  sourceRevision = -1;
@@ -501,12 +559,12 @@ const calculateWorkbook = (
501
  book?.namedRanges, book?.dateSystem]);
502
  const reset = session.revision < 0 || session.metadata !== metadata
503
  || (book != null && (book.rev < session.sourceRevision || book.rev > session.sourceRevision + 1));
504
- const previous = new Map(session.sheets.map((sheet) => [sheet.id, sheet]));
505
  const changes: Record<string, QualifiedFormula | null> = {};
506
  const changed: string[] = [];
507
  const spillChildren: Record<string, SpillChildMarker> = {};
508
  const cellStyles: Record<string, Record<string, unknown>> = {};
509
- if (reset) { session.cells.clear(); session.formulas.clear(); }
510
  for (const sheet of baseSheets) {
511
  const old = previous.get(sheet.id);
512
  if (!reset && old?.cells === sheet.cells) continue;
@@ -560,8 +618,14 @@ const calculateWorkbook = (
560
  if (!all && !graph.dirty.has(key)) continue;
561
  const result = graph.values.get(key);
562
  if (!result) continue;
563
- const next = cellFromFormulaResult(session.cells.get(key) ?? {}, spec.formula, result);
564
  const spill = graph.spills.get(key);
 
 
 
 
 
 
565
  if (spill) next.spill = { ...spill }; else delete next.spill;
566
  write(key, next);
567
  }
@@ -590,8 +654,13 @@ const calculateWorkbook = (
590
  return patch ? { ...sheet, cells: { ...(sheet.cells ?? {}), ...patch } } : sheet;
591
  });
592
  session.sheets = resultSheets;
 
593
  for (const sheet of resultSheets) for (const [addr, cell] of Object.entries(patches.get(sheet.id) ?? {})) {
594
  const key = formulaReferenceKey(sheet.name, addr);
 
 
 
 
595
  session.cells.set(key, cell);
596
  if (cell.kind === "formula" && cell.formula) session.formulas.set(key, {
597
  formula: cell.formula, sheet: sheet.name, style: cell.style as Record<string, unknown> | undefined,
 
41
  // `get(addr) => CellValue` callback and knows nothing about a `Cell`. `cellToValue`, below, is the
42
  // one door that turns this file's `Cell` into that shape, so the evaluator itself never has to.
43
  import {
44
+ compileSheetFormula, CYCLE_REFUSAL, ERROR_REF, evaluateCompiledSheetFormula, evaluateFormula,
45
+ formulaReferenceKey, WorkbookCalculation as FormulaCalculation, workbookFormulaGetter,
46
  } from "./formulaEval";
47
  import type { CellValue, QualifiedFormula, SpillChildMarker, FormulaErrorCode } from "./formulaEval";
48
  import { copyCell, replaceCellStyle } from "./cellStyleOps";
 
465
  : { sheet: key.slice(0, bang).toUpperCase(), addr: key.slice(bang + 1).toUpperCase() };
466
  };
467
 
468
+ /**
469
+ * HOTFIX 2026-09-29 (owner: "make formula native inside the Cell database Filter so it can point
470
+ * to an existing date but we can use something like a date function refer to a cell"). What a
471
+ * FORMULA held in a filter value slot (`=DATE($E$24,1,1)`) reads now, over the painted workbook:
472
+ * `{value}` as the filter compares it (ISO text for a date), or `{problem}` saying why not. The
473
+ * server twin is `routes_sheet._read_binding_formula`; both use their workbook engine, so a date
474
+ * function answers the same ISO day on each side.
475
+ */
476
+ export const readFormulaSlot = (
477
+ book: Workbook, src: string, home?: SheetTab | null,
478
+ ): { value: string; problem?: string } => {
479
+ const fail = (reason: string) => ({ value: "", problem:
480
+ `Filter value from formula ${src} cannot be read because ${reason} `
481
+ + "Choose a readable cell containing one nonblank value, or type the filter value." });
482
+ const current = home ?? book.sheets[0];
483
+ const byName = new Map(book.sheets.map((sheet) => [sheet.name.trim().toUpperCase(), sheet]));
484
+ const get = workbookFormulaGetter((rawKey) => {
485
+ const parsed = qualifiedKeyParts(rawKey);
486
+ const target = parsed.sheet ? byName.get(parsed.sheet) : current;
487
+ if (!target) return UNKNOWN_SHEET_VALUE;
488
+ return cellToValue(target.cells?.[parsed.addr.replace(/\$/g, "")]);
489
+ });
490
+ let got: CellValue;
491
+ try {
492
+ const compiled = compileSheetFormula(src, current?.name ?? "", current?.name ?? "");
493
+ // A cell the formula names directly must hold something: a deleted input refuses by name
494
+ // (as a cell reference does) instead of computing a year-zero date. Range members may be blank.
495
+ for (const key of compiled.cells) {
496
+ const parsed = qualifiedKeyParts(key);
497
+ const target = parsed.sheet ? byName.get(parsed.sheet) : current;
498
+ const cell = target?.cells?.[parsed.addr.replace(/\$/g, "")];
499
+ if (!target) return fail("its sheet does not exist.");
500
+ if (!cell || cell.kind === "empty") return fail(`cell ${parsed.addr} is blank.`);
501
+ }
502
+ got = evaluateCompiledSheetFormula(compiled, get,
503
+ undefined, { dateSystem: book.dateSystem === "1904" ? "1904" : "1900",
504
+ sheets: book.sheets.map((sheet) => sheet.name) });
505
+ } catch {
506
+ return fail("the formula could not be read.");
507
+ }
508
+ if (got.kind === "error") return fail(got.message.endsWith(".") ? got.message : `${got.message}.`);
509
+ if (got.kind === "unsupported") return fail("it uses a function a filter cannot compute here.");
510
+ if (got.kind === "pending") return fail("one of its cells needs to be refreshed.");
511
+ if (got.kind === "empty" || !("value" in got) || String(got.value ?? "").trim() === "")
512
+ return fail("its result is blank.");
513
+ return { value: String(got.value) };
514
+ };
515
+
516
  /** One mounted workbook owns this cache; no tenant values enter a process-global cache. */
517
  export class WorkbookCalculationSession {
518
  readonly engine = new FormulaCalculation();
519
  sheets: readonly SheetTab[] = [];
520
+ /**
521
+ * HOTFIX 2026-09-29 (owner: "Sheet module is so laggy, we should only update or refresh cells
522
+ * that are affected"). The INPUT tabs the engine last saw. The next pass diffs against these,
523
+ * never against `sheets` (the computed copies): diffing stored tabs against computed ones made
524
+ * every formula look edited, so each keystroke recalculated the whole workbook (~200 ms per
525
+ * 3,200 formulas, several times per edit).
526
+ */
527
+ sourceSheets: readonly SheetTab[] = [];
528
+ /** The last computed cell per formula, reused while neither its input nor its answer moved. */
529
+ readonly results = new Map<string, { base: Cell | undefined; result: unknown; cell: Cell }>();
530
  metadata = "";
531
  revision = -1;
532
  sourceRevision = -1;
 
559
  book?.namedRanges, book?.dateSystem]);
560
  const reset = session.revision < 0 || session.metadata !== metadata
561
  || (book != null && (book.rev < session.sourceRevision || book.rev > session.sourceRevision + 1));
562
+ const previous = new Map(session.sourceSheets.map((sheet) => [sheet.id, sheet]));
563
  const changes: Record<string, QualifiedFormula | null> = {};
564
  const changed: string[] = [];
565
  const spillChildren: Record<string, SpillChildMarker> = {};
566
  const cellStyles: Record<string, Record<string, unknown>> = {};
567
+ if (reset) { session.cells.clear(); session.formulas.clear(); session.results.clear(); }
568
  for (const sheet of baseSheets) {
569
  const old = previous.get(sheet.id);
570
  if (!reset && old?.cells === sheet.cells) continue;
 
618
  if (!all && !graph.dirty.has(key)) continue;
619
  const result = graph.values.get(key);
620
  if (!result) continue;
621
+ const base = session.cells.get(key);
622
  const spill = graph.spills.get(key);
623
+ const kept = session.results.get(key);
624
+ if (kept && kept.result === result && kept.base === base && !spill && !graph.dirty.has(key)) {
625
+ write(key, kept.cell);
626
+ continue;
627
+ }
628
+ const next = cellFromFormulaResult(base ?? {}, spec.formula, result);
629
  if (spill) next.spill = { ...spill }; else delete next.spill;
630
  write(key, next);
631
  }
 
654
  return patch ? { ...sheet, cells: { ...(sheet.cells ?? {}), ...patch } } : sheet;
655
  });
656
  session.sheets = resultSheets;
657
+ session.sourceSheets = baseSheets;
658
  for (const sheet of resultSheets) for (const [addr, cell] of Object.entries(patches.get(sheet.id) ?? {})) {
659
  const key = formulaReferenceKey(sheet.name, addr);
660
+ if (cell.kind === "formula") {
661
+ const result = graph.values.get(key);
662
+ if (result) session.results.set(key, { base: cell, result, cell });
663
+ }
664
  session.cells.set(key, cell);
665
  if (cell.kind === "formula" && cell.formula) session.formulas.set(key, {
666
  formula: cell.formula, sheet: sheet.name, style: cell.style as Record<string, unknown> | undefined,