Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Deploy AIOS web (React glide grid + FastAPI slice)
Browse files- RELEASES.json +1 -1
- VERSION +1 -1
- api/main.py +25 -0
- api/routes_sheet.py +8 -4
- api/sheet_warm.py +320 -0
- platform/core/sheets.py +2 -2
- platform/harness/datastore.py +13 -0
- platform/harness/mirror_store.py +3 -0
- platform/harness/mirror_tokens.py +60 -8
- web/public/AIOS_DEPLOY_RECEIPT +1 -1
RELEASES.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
{
|
| 2 |
-
"current": "
|
| 3 |
"releases": [
|
| 4 |
{
|
| 5 |
"version": "v81",
|
|
|
|
| 1 |
{
|
| 2 |
+
"current": "613cb6029 (613cb60299e4)",
|
| 3 |
"releases": [
|
| 4 |
{
|
| 5 |
"version": "v81",
|
VERSION
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
|
|
|
|
| 1 |
+
613cb6029 (613cb60299e4)
|
api/main.py
CHANGED
|
@@ -2346,6 +2346,25 @@ def _capture_resync_source_counts(tenant):
|
|
| 2346 |
return None
|
| 2347 |
|
| 2348 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2349 |
def _store_resync_loop():
|
| 2350 |
"""Keep the analytical mirror current — the API-process stand-in for the re-sync the
|
| 2351 |
Streamlit app piggybacks on page renders. Measure memos key on the pool stamp, so a
|
|
@@ -2496,6 +2515,7 @@ def _store_resync_loop():
|
|
| 2496 |
last_full_pass_at = _t.time()
|
| 2497 |
if _odoo_requested is None:
|
| 2498 |
_odoo_requested = _run_sync_requests()
|
|
|
|
| 2499 |
try:
|
| 2500 |
selected_entities = _configured_mirror_entities(_cad["tenant"])
|
| 2501 |
sync_report, delete_report, _err = _resync_mirror_pass(_manual, passes, selected_entities)
|
|
@@ -2545,6 +2565,7 @@ def _store_resync_loop():
|
|
| 2545 |
f"only the local mirror was caught up and no store table was rewritten; the "
|
| 2546 |
f"next scheduled pass is due in {max(0, _every - _age)}s")
|
| 2547 |
last_full_pass_at = last_good_pass_at
|
|
|
|
| 2548 |
continue
|
| 2549 |
# D-9131: count the source now, before the vendor pulls, so reconciliation compares the
|
| 2550 |
# mirror with the source as of the same moment. A pass without a good pull counts nothing.
|
|
@@ -2711,6 +2732,8 @@ def _store_resync_loop():
|
|
| 2711 |
if _resumed else _meta_now)
|
| 2712 |
_resync_memory_write(last_good_pass_at, last_relational_success_at,
|
| 2713 |
last_source_fingerprints, None if _pass_good else dict(_pulls))
|
|
|
|
|
|
|
| 2714 |
|
| 2715 |
|
| 2716 |
def _boot_app_migrations(why):
|
|
@@ -3000,3 +3023,5 @@ if (not data_binding.gate_process()
|
|
| 3000 |
and os.environ.get("AIOS_STORE_RESYNC") == "1" and not _freeze_holds("store resync")):
|
| 3001 |
import threading as _threading_resync
|
| 3002 |
_threading_resync.Thread(target=_store_resync_loop, daemon=True, name="store-resync").start()
|
|
|
|
|
|
|
|
|
| 2346 |
return None
|
| 2347 |
|
| 2348 |
|
| 2349 |
+
def _sheet_warm_generation():
|
| 2350 |
+
"""The mirror install generation before a pass, or None when it cannot be read."""
|
| 2351 |
+
try:
|
| 2352 |
+
from harness import datastore as _warm_ds
|
| 2353 |
+
return _warm_ds.mirror_generation()
|
| 2354 |
+
except Exception: # noqa: BLE001
|
| 2355 |
+
return None
|
| 2356 |
+
|
| 2357 |
+
|
| 2358 |
+
def _sheet_warm_after_pass(tenant, good, generation_before, rebuilt):
|
| 2359 |
+
"""Hand a finished pass to the Sheet warm. Never blocks and never raises into the loop."""
|
| 2360 |
+
try:
|
| 2361 |
+
import sheet_warm
|
| 2362 |
+
sheet_warm.after_pass(tenant, good=good, generation_before=generation_before,
|
| 2363 |
+
generation_after=_sheet_warm_generation(), rebuilt=rebuilt)
|
| 2364 |
+
except Exception as exc: # noqa: BLE001
|
| 2365 |
+
print(f"[sheet-warm] request failed: {type(exc).__name__}: {exc}")
|
| 2366 |
+
|
| 2367 |
+
|
| 2368 |
def _store_resync_loop():
|
| 2369 |
"""Keep the analytical mirror current — the API-process stand-in for the re-sync the
|
| 2370 |
Streamlit app piggybacks on page renders. Measure memos key on the pool stamp, so a
|
|
|
|
| 2515 |
last_full_pass_at = _t.time()
|
| 2516 |
if _odoo_requested is None:
|
| 2517 |
_odoo_requested = _run_sync_requests()
|
| 2518 |
+
_warm_generation = _sheet_warm_generation()
|
| 2519 |
try:
|
| 2520 |
selected_entities = _configured_mirror_entities(_cad["tenant"])
|
| 2521 |
sync_report, delete_report, _err = _resync_mirror_pass(_manual, passes, selected_entities)
|
|
|
|
| 2565 |
f"only the local mirror was caught up and no store table was rewritten; the "
|
| 2566 |
f"next scheduled pass is due in {max(0, _every - _age)}s")
|
| 2567 |
last_full_pass_at = last_good_pass_at
|
| 2568 |
+
_sheet_warm_after_pass(_cad["tenant"], _err is None, _warm_generation, False)
|
| 2569 |
continue
|
| 2570 |
# D-9131: count the source now, before the vendor pulls, so reconciliation compares the
|
| 2571 |
# mirror with the source as of the same moment. A pass without a good pull counts nothing.
|
|
|
|
| 2732 |
if _resumed else _meta_now)
|
| 2733 |
_resync_memory_write(last_good_pass_at, last_relational_success_at,
|
| 2734 |
last_source_fingerprints, None if _pass_good else dict(_pulls))
|
| 2735 |
+
_sheet_warm_after_pass(_cad["tenant"], _pass_good, _warm_generation,
|
| 2736 |
+
_reason is not None or bool(_meta_state.get("applied")))
|
| 2737 |
|
| 2738 |
|
| 2739 |
def _boot_app_migrations(why):
|
|
|
|
| 3023 |
and os.environ.get("AIOS_STORE_RESYNC") == "1" and not _freeze_holds("store resync")):
|
| 3024 |
import threading as _threading_resync
|
| 3025 |
_threading_resync.Thread(target=_store_resync_loop, daemon=True, name="store-resync").start()
|
| 3026 |
+
import sheet_warm as _sheet_warm
|
| 3027 |
+
_sheet_warm.start()
|
api/routes_sheet.py
CHANGED
|
@@ -4016,11 +4016,13 @@ def _resolve_refresh_sheet(workbook_id: str, session: Session, *, only=None, for
|
|
| 4016 |
return {"workbook": {**{key: saved.get(key) for key in ("id", "name", "rev", "refreshed_at")}, **check_metadata},
|
| 4017 |
"cells": {key: deepcopy(sheets.find_tab(projected, key.rsplit("!", 1)[0])["cells"][key.rsplit("!", 1)[1]])
|
| 4018 |
for key in addresses}, "addresses": addresses, "recalc_ms": recalc_ms,
|
| 4019 |
-
"binding_refresh": {"databases": status, "token_reads": token_reads
|
|
|
|
| 4020 |
if force:
|
| 4021 |
return {"workbook": projected, "addresses": addresses,
|
| 4022 |
"recalc_ms": recalc_ms,
|
| 4023 |
-
"binding_refresh": {"databases": status, "token_reads": token_reads
|
|
|
|
| 4024 |
if only is not None:
|
| 4025 |
# ⛔ C5: a targeted answer carries ONLY the cells it resolved for this caller. The rest of
|
| 4026 |
# the document holds the owner's stored answers, which a scoped reader must never adopt.
|
|
@@ -4028,9 +4030,11 @@ def _resolve_refresh_sheet(workbook_id: str, session: Session, *, only=None, for
|
|
| 4028 |
"cells": {cell_key: _public_refresh_snapshot(entry["cell"]) for cell_key, _, entry in entries},
|
| 4029 |
"addresses": addresses,
|
| 4030 |
"recalc_ms": recalc_ms,
|
| 4031 |
-
"binding_refresh": {"databases": status, "token_reads": token_reads
|
|
|
|
| 4032 |
return {"workbook": projected, "addresses": addresses, "recalc_ms": recalc_ms,
|
| 4033 |
-
"binding_refresh": {"databases": status, "token_reads": token_reads
|
|
|
|
| 4034 |
|
| 4035 |
|
| 4036 |
from core import sheets as _sheet_capabilities
|
|
|
|
| 4016 |
return {"workbook": {**{key: saved.get(key) for key in ("id", "name", "rev", "refreshed_at")}, **check_metadata},
|
| 4017 |
"cells": {key: deepcopy(sheets.find_tab(projected, key.rsplit("!", 1)[0])["cells"][key.rsplit("!", 1)[1]])
|
| 4018 |
for key in addresses}, "addresses": addresses, "recalc_ms": recalc_ms,
|
| 4019 |
+
"binding_refresh": {"databases": status, "token_reads": token_reads,
|
| 4020 |
+
"resolved": resolved_count, "skipped": len(skipped_entries)}}
|
| 4021 |
if force:
|
| 4022 |
return {"workbook": projected, "addresses": addresses,
|
| 4023 |
"recalc_ms": recalc_ms,
|
| 4024 |
+
"binding_refresh": {"databases": status, "token_reads": token_reads,
|
| 4025 |
+
"resolved": resolved_count, "skipped": len(skipped_entries)}}
|
| 4026 |
if only is not None:
|
| 4027 |
# ⛔ C5: a targeted answer carries ONLY the cells it resolved for this caller. The rest of
|
| 4028 |
# the document holds the owner's stored answers, which a scoped reader must never adopt.
|
|
|
|
| 4030 |
"cells": {cell_key: _public_refresh_snapshot(entry["cell"]) for cell_key, _, entry in entries},
|
| 4031 |
"addresses": addresses,
|
| 4032 |
"recalc_ms": recalc_ms,
|
| 4033 |
+
"binding_refresh": {"databases": status, "token_reads": token_reads,
|
| 4034 |
+
"resolved": resolved_count, "skipped": len(skipped_entries)}}
|
| 4035 |
return {"workbook": projected, "addresses": addresses, "recalc_ms": recalc_ms,
|
| 4036 |
+
"binding_refresh": {"databases": status, "token_reads": token_reads,
|
| 4037 |
+
"resolved": resolved_count, "skipped": len(skipped_entries)}}
|
| 4038 |
|
| 4039 |
|
| 4040 |
from core import sheets as _sheet_capabilities
|
api/sheet_warm.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Post-sync Sheet warm: after an Odoo pass changed data, refresh each reader's stale bound cells.
|
| 2 |
+
|
| 3 |
+
One daemon thread ("sheet-warm") does the work, one workbook at a time, after the resync pass has
|
| 4 |
+
finished. The resync loop only calls `after_pass`, which records a request and returns.
|
| 5 |
+
|
| 6 |
+
Each reader is the active registry record of the workbook owner or a grantee (EVERYONE expanded),
|
| 7 |
+
admitted by `sheets.workbook_role`. The warm runs `refresh_sheet`'s own non-forced path as that
|
| 8 |
+
reader, so it computes only the slot that reader would compute on open and never widens a wall.
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import atexit
|
| 13 |
+
import os
|
| 14 |
+
import threading
|
| 15 |
+
import time
|
| 16 |
+
from datetime import datetime, time as dtime, timedelta, timezone
|
| 17 |
+
from time import perf_counter
|
| 18 |
+
|
| 19 |
+
import routes_sheet
|
| 20 |
+
from core import external_access, perms, shares, sheets, users
|
| 21 |
+
from deps import Session
|
| 22 |
+
|
| 23 |
+
#: The rollover warm starts this long after 00:00 UTC, so the day clock has moved for every reader.
|
| 24 |
+
ROLLOVER_GRACE_SECONDS = 60
|
| 25 |
+
#: Pause after each refresh call. The warm is low priority and yields to people.
|
| 26 |
+
GAP_SECONDS = 1.0
|
| 27 |
+
|
| 28 |
+
_LOCK = threading.Lock()
|
| 29 |
+
_WAKE = threading.Event()
|
| 30 |
+
_STOP = threading.Event()
|
| 31 |
+
#: pending: {tenant: reason}. progress: the pass in flight, read by the exit hook.
|
| 32 |
+
_STATE = {"pending": {}, "last_tenant": None, "thread": None, "progress": None}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def enabled() -> bool:
|
| 36 |
+
"""`AIOS_SHEET_WARM=0` turns the warm off. Any other value, or none, leaves it on."""
|
| 37 |
+
return os.environ.get("AIOS_SHEET_WARM", "1").strip() != "0"
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def should_warm(good, generation_before, generation_after, rebuilt) -> bool:
|
| 41 |
+
"""A good pass warms when the mirror install generation moved or store tables were rebuilt."""
|
| 42 |
+
return bool(good) and (generation_before != generation_after or bool(rebuilt))
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def after_pass(tenant, *, good, generation_before, generation_after, rebuilt=False) -> bool:
|
| 46 |
+
"""Record a warm request after a resync pass. Never blocks and never starts a thread."""
|
| 47 |
+
if tenant:
|
| 48 |
+
with _LOCK:
|
| 49 |
+
_STATE["last_tenant"] = str(tenant)
|
| 50 |
+
if not enabled() or not tenant or not should_warm(good, generation_before,
|
| 51 |
+
generation_after, rebuilt):
|
| 52 |
+
return False
|
| 53 |
+
_request("sync", str(tenant))
|
| 54 |
+
return True
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _request(reason, tenant):
|
| 58 |
+
with _LOCK:
|
| 59 |
+
pending = _STATE["pending"]
|
| 60 |
+
# A sync request outranks a rollover for the same tenant: it names the newer cause.
|
| 61 |
+
if pending.get(tenant) != "sync":
|
| 62 |
+
pending[tenant] = reason
|
| 63 |
+
_WAKE.set()
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _take():
|
| 67 |
+
"""Pop every pending request and clear the wake, under one lock, so none is lost."""
|
| 68 |
+
with _LOCK:
|
| 69 |
+
jobs = list(_STATE["pending"].items())
|
| 70 |
+
_STATE["pending"] = {}
|
| 71 |
+
_WAKE.clear()
|
| 72 |
+
return jobs
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def next_rollover(now) -> datetime:
|
| 76 |
+
"""The first `00:00 UTC + ROLLOVER_GRACE_SECONDS` strictly after `now`."""
|
| 77 |
+
if now.tzinfo is None:
|
| 78 |
+
now = now.replace(tzinfo=timezone.utc)
|
| 79 |
+
now = now.astimezone(timezone.utc)
|
| 80 |
+
grace = timedelta(seconds=ROLLOVER_GRACE_SECONDS)
|
| 81 |
+
today = datetime.combine(now.date(), dtime(0), tzinfo=timezone.utc) + grace
|
| 82 |
+
return today if today > now else today + timedelta(days=1)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def format_reader_line(wid, reader, resolved, skipped, ms) -> str:
|
| 86 |
+
return (f"[sheet-warm] wb={wid} reader={reader} resolved={int(resolved)} "
|
| 87 |
+
f"skipped={int(skipped)} ms={int(ms)}")
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def format_pass_line(reason, tenant, workbooks, readers, conflicts, ms) -> str:
|
| 91 |
+
return (f"[sheet-warm] pass reason={reason} tenant={tenant} workbooks={int(workbooks)} "
|
| 92 |
+
f"readers={int(readers)} conflicts={int(conflicts)} ms={int(ms)}")
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _is_bound(cell) -> bool:
|
| 96 |
+
return (isinstance(cell, dict) and cell.get("kind") == "bound"
|
| 97 |
+
and not routes_sheet._is_view_binding(cell))
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def bound_cells(book) -> set:
|
| 101 |
+
"""Every `<tab id>!<ADDR>` holding a metric binding (placed views are never refreshed)."""
|
| 102 |
+
return {f"{tab.get('id')}!{addr}" for tab in (book or {}).get("sheets") or []
|
| 103 |
+
for addr, cell in (tab.get("cells") or {}).items() if _is_bound(cell)}
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def cells_needing_warm(view) -> set:
|
| 107 |
+
"""Bound cells a reader's projection marks stale (any reason) or `sheet_refresh_required`."""
|
| 108 |
+
out = set()
|
| 109 |
+
for tab in (view or {}).get("sheets") or []:
|
| 110 |
+
for addr, cell in (tab.get("cells") or {}).items():
|
| 111 |
+
if not _is_bound(cell):
|
| 112 |
+
continue
|
| 113 |
+
state = cell.get("state")
|
| 114 |
+
code = (cell.get("refusal") or {}).get("code")
|
| 115 |
+
if state == "stale" or (state == "refused" and code == "sheet_refresh_required"):
|
| 116 |
+
out.add(f"{tab.get('id')}!{addr}")
|
| 117 |
+
return out
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def reader_names(book, rec, tenant) -> list:
|
| 121 |
+
"""Owner first, then grantees in grant order. EVERYONE expands to the registry's usernames."""
|
| 122 |
+
names = []
|
| 123 |
+
owner = str((book or {}).get("created_by") or "").strip().lower()
|
| 124 |
+
if owner:
|
| 125 |
+
names.append(owner)
|
| 126 |
+
everyone = False
|
| 127 |
+
for entry in (rec or {}).get("entries") or ():
|
| 128 |
+
user = str(entry.get("user") or "").strip().lower()
|
| 129 |
+
if user == shares.EVERYONE:
|
| 130 |
+
everyone = True
|
| 131 |
+
elif user:
|
| 132 |
+
names.append(user)
|
| 133 |
+
if everyone:
|
| 134 |
+
# Other tenants and inactive accounts fall out at `resolve_active_user`.
|
| 135 |
+
names.extend(sorted(str(name).strip().lower() for name in (users.registry() or {})))
|
| 136 |
+
return list(dict.fromkeys(names))
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def reader_session(rt, tenant, uname, book, rec):
|
| 140 |
+
"""A fresh Session for one admitted, active reader, or None. Never an admin or stub user."""
|
| 141 |
+
try:
|
| 142 |
+
user = external_access.resolve_active_user(uname, tenant)
|
| 143 |
+
except external_access.ExternalAccessError:
|
| 144 |
+
return None
|
| 145 |
+
role = sheets.workbook_role(rt, book, uname, is_admin=perms.is_admin(user), rec=rec)
|
| 146 |
+
if not sheets.may_read_workbook(book, role):
|
| 147 |
+
return None
|
| 148 |
+
return Session(tenant=tenant, user=user, claims={}, runtime=rt)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _conflict_code(exc):
|
| 152 |
+
"""The refusal code when a refresh lost to a concurrent save (a 409), else None."""
|
| 153 |
+
if isinstance(exc, sheets.SheetStaleRefusal):
|
| 154 |
+
return exc.code
|
| 155 |
+
if isinstance(exc, sheets.SheetRefusal) and str(exc.code).endswith("_stale"):
|
| 156 |
+
return exc.code
|
| 157 |
+
if getattr(exc, "status_code", None) == 409:
|
| 158 |
+
detail = getattr(exc, "detail", None)
|
| 159 |
+
error = detail.get("error") if isinstance(detail, dict) else None
|
| 160 |
+
return (error if isinstance(error, dict) else {}).get("code") or "conflict"
|
| 161 |
+
return None
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def warm_reader(session, wid):
|
| 165 |
+
"""`(resolved, called)` for one reader. Calls the refresh only when a bound cell needs it."""
|
| 166 |
+
# Two scopes, like the open GET and its POST: the refresh never reuses the read's memo.
|
| 167 |
+
with routes_sheet._sheet_request_scope(session):
|
| 168 |
+
book = sheets.get_workbook(session.runtime, wid)
|
| 169 |
+
needs = cells_needing_warm(routes_sheet._read_for(session, book))
|
| 170 |
+
if not needs:
|
| 171 |
+
return 0, False
|
| 172 |
+
with routes_sheet._sheet_request_scope(session):
|
| 173 |
+
out = routes_sheet._refresh_sheet_scoped(wid, session, only=needs, force=False)
|
| 174 |
+
report = (out or {}).get("binding_refresh") or {}
|
| 175 |
+
return int(report.get("resolved", len(needs))), True
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def warm_workbook(rt, tenant, wid) -> dict:
|
| 179 |
+
"""Warm every reader of one workbook. A 409 skips the rest of this workbook for this pass."""
|
| 180 |
+
book = sheets.get_workbook(rt, wid)
|
| 181 |
+
bound = bound_cells(book)
|
| 182 |
+
result = {"warmed": bool(bound), "readers": 0, "conflict": False}
|
| 183 |
+
if not bound:
|
| 184 |
+
return result
|
| 185 |
+
rec = shares.grants("workbook", book.get("id") or wid, st=rt)
|
| 186 |
+
for uname in reader_names(book, rec, tenant):
|
| 187 |
+
session = reader_session(rt, tenant, uname, book, rec)
|
| 188 |
+
if session is None:
|
| 189 |
+
continue
|
| 190 |
+
result["readers"] += 1
|
| 191 |
+
started = perf_counter()
|
| 192 |
+
try:
|
| 193 |
+
resolved, called = warm_reader(session, wid)
|
| 194 |
+
except Exception as exc: # noqa: BLE001
|
| 195 |
+
ms = (perf_counter() - started) * 1000.0
|
| 196 |
+
code = _conflict_code(exc)
|
| 197 |
+
if code:
|
| 198 |
+
print(format_reader_line(wid, uname, 0, len(bound), ms), flush=True)
|
| 199 |
+
print(f"[sheet-warm] conflict wb={wid} reader={uname} code={code}: a person saved "
|
| 200 |
+
f"this workbook during the warm, so its remaining readers wait for the next "
|
| 201 |
+
f"pass", flush=True)
|
| 202 |
+
result["conflict"] = True
|
| 203 |
+
return result
|
| 204 |
+
print(f"[sheet-warm] wb={wid} reader={uname} failed {type(exc).__name__}: {exc}",
|
| 205 |
+
flush=True)
|
| 206 |
+
continue
|
| 207 |
+
ms = (perf_counter() - started) * 1000.0
|
| 208 |
+
print(format_reader_line(wid, uname, resolved, max(0, len(bound) - resolved), ms),
|
| 209 |
+
flush=True)
|
| 210 |
+
if called and GAP_SECONDS > 0:
|
| 211 |
+
time.sleep(GAP_SECONDS)
|
| 212 |
+
return result
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def _limit(reason, tenant, left, cause):
|
| 216 |
+
"""Name every workbook a stopped pass did not reach. A pass never ends short silently."""
|
| 217 |
+
print(f"[sheet-warm] limit reason={reason} tenant={tenant} cause={cause} left={len(left)} "
|
| 218 |
+
f"workbooks={','.join(left) if left else 'unknown'}", flush=True)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def warm_tenant(tenant, reason="sync") -> dict:
|
| 222 |
+
"""One warm pass over every workbook of one tenant. No row cap and no time budget."""
|
| 223 |
+
from harness import runtime
|
| 224 |
+
started = perf_counter()
|
| 225 |
+
totals = {"workbooks": 0, "readers": 0, "conflicts": 0, "stopped": None}
|
| 226 |
+
ids, done = [], 0
|
| 227 |
+
try:
|
| 228 |
+
rt = runtime.get_runtime(tenant)
|
| 229 |
+
ids = [str(row["id"]) for row in sheets.list_workbooks(rt)]
|
| 230 |
+
for wid in ids:
|
| 231 |
+
with _LOCK:
|
| 232 |
+
_STATE["progress"] = {"reason": reason, "tenant": tenant, "left": ids[done:]}
|
| 233 |
+
if _STOP.is_set():
|
| 234 |
+
totals["stopped"] = "shutdown"
|
| 235 |
+
if not _STATE.get("exit_reported"):
|
| 236 |
+
_limit(reason, tenant, ids[done:], "shutdown")
|
| 237 |
+
break
|
| 238 |
+
try:
|
| 239 |
+
part = warm_workbook(rt, tenant, wid)
|
| 240 |
+
except Exception as exc: # noqa: BLE001
|
| 241 |
+
print(f"[sheet-warm] wb={wid} failed {type(exc).__name__}: {exc}", flush=True)
|
| 242 |
+
else:
|
| 243 |
+
totals["workbooks"] += int(part["warmed"])
|
| 244 |
+
totals["readers"] += part["readers"]
|
| 245 |
+
totals["conflicts"] += int(part["conflict"])
|
| 246 |
+
done += 1
|
| 247 |
+
except Exception as exc: # noqa: BLE001
|
| 248 |
+
totals["stopped"] = type(exc).__name__
|
| 249 |
+
_limit(reason, tenant, ids[done:], f"{type(exc).__name__}: {exc}")
|
| 250 |
+
finally:
|
| 251 |
+
with _LOCK:
|
| 252 |
+
_STATE["progress"] = None
|
| 253 |
+
print(format_pass_line(reason, tenant, totals["workbooks"], totals["readers"],
|
| 254 |
+
totals["conflicts"], (perf_counter() - started) * 1000.0), flush=True)
|
| 255 |
+
return totals
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def _rollover_tenant():
|
| 259 |
+
with _LOCK:
|
| 260 |
+
tenant = _STATE["last_tenant"]
|
| 261 |
+
if tenant:
|
| 262 |
+
return tenant
|
| 263 |
+
try:
|
| 264 |
+
from harness import datastore
|
| 265 |
+
rt = datastore._resident_odoo_runtime()
|
| 266 |
+
return getattr(rt, "key", None) if rt is not None else None
|
| 267 |
+
except Exception: # noqa: BLE001
|
| 268 |
+
return None
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def _utcnow():
|
| 272 |
+
return datetime.now(timezone.utc)
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def _run():
|
| 276 |
+
rollover_at = next_rollover(_utcnow())
|
| 277 |
+
while not _STOP.is_set():
|
| 278 |
+
_WAKE.wait(max(0.0, (rollover_at - _utcnow()).total_seconds()))
|
| 279 |
+
if _STOP.is_set():
|
| 280 |
+
return
|
| 281 |
+
if _utcnow() >= rollover_at:
|
| 282 |
+
rollover_at = next_rollover(_utcnow())
|
| 283 |
+
tenant = _rollover_tenant()
|
| 284 |
+
if tenant:
|
| 285 |
+
_request("rollover", tenant)
|
| 286 |
+
else:
|
| 287 |
+
print("[sheet-warm] rollover skipped: no tenant is known yet", flush=True)
|
| 288 |
+
for tenant, reason in _take():
|
| 289 |
+
try:
|
| 290 |
+
warm_tenant(tenant, reason)
|
| 291 |
+
except Exception as exc: # noqa: BLE001
|
| 292 |
+
print(f"[sheet-warm] pass failed tenant={tenant} {type(exc).__name__}: {exc}",
|
| 293 |
+
flush=True)
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def _on_exit():
|
| 297 |
+
"""At shutdown, name the workbooks an unfinished pass did not reach."""
|
| 298 |
+
_STOP.set()
|
| 299 |
+
with _LOCK:
|
| 300 |
+
progress = _STATE["progress"]
|
| 301 |
+
_STATE["progress"] = None
|
| 302 |
+
_STATE["exit_reported"] = bool(progress)
|
| 303 |
+
if progress:
|
| 304 |
+
_limit(progress["reason"], progress["tenant"], progress["left"], "shutdown")
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def start():
|
| 308 |
+
"""Start the one "sheet-warm" daemon thread when enabled. Returns it, or None."""
|
| 309 |
+
if not enabled():
|
| 310 |
+
print("[sheet-warm] off: AIOS_SHEET_WARM=0", flush=True)
|
| 311 |
+
return None
|
| 312 |
+
with _LOCK:
|
| 313 |
+
thread = _STATE["thread"]
|
| 314 |
+
if thread is not None and thread.is_alive():
|
| 315 |
+
return thread
|
| 316 |
+
thread = threading.Thread(target=_run, daemon=True, name="sheet-warm")
|
| 317 |
+
_STATE["thread"] = thread
|
| 318 |
+
atexit.register(_on_exit)
|
| 319 |
+
thread.start()
|
| 320 |
+
return thread
|
platform/core/sheets.py
CHANGED
|
@@ -3115,8 +3115,8 @@ def duplicate_tab(rt, workbook, tab_id, name, actor):
|
|
| 3115 |
# in-memory re-resolve (`routes_sheet.py::_reresolved_for_reader`) is the only place that ever
|
| 3116 |
# calls `fill_scope_cache`, right after `_resolve_binding` answers under THAT reader's own scope.
|
| 3117 |
# `refresh_sheet` is the only place that ever calls `clear_scope_cache`. A connector sync never
|
| 3118 |
-
#
|
| 3119 |
-
#
|
| 3120 |
|
| 3121 |
SCOPE_CACHE_KEY_PREFIX = "sheet_scope_cache_"
|
| 3122 |
|
|
|
|
| 3115 |
# in-memory re-resolve (`routes_sheet.py::_reresolved_for_reader`) is the only place that ever
|
| 3116 |
# calls `fill_scope_cache`, right after `_resolve_binding` answers under THAT reader's own scope.
|
| 3117 |
# `refresh_sheet` is the only place that ever calls `clear_scope_cache`. A connector sync never
|
| 3118 |
+
# clears this cache itself. The post-sync warm (`aios-web/api/sheet_warm.py`) runs the
|
| 3119 |
+
# non-forced refresh path as each reader and clears no cache.
|
| 3120 |
|
| 3121 |
SCOPE_CACHE_KEY_PREFIX = "sheet_scope_cache_"
|
| 3122 |
|
platform/harness/datastore.py
CHANGED
|
@@ -810,6 +810,19 @@ _INSTANCE_LOCK = _thr.Lock()
|
|
| 810 |
#: reading the previous tenant's file — see `ro_con`. A plain "is the cursor alive?" probe cannot
|
| 811 |
#: answer that question, which is why this counter exists rather than more probing.
|
| 812 |
_GENERATION = [0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 813 |
|
| 814 |
|
| 815 |
def mark_ready():
|
|
|
|
| 810 |
#: reading the previous tenant's file — see `ro_con`. A plain "is the cursor alive?" probe cannot
|
| 811 |
#: answer that question, which is why this counter exists rather than more probing.
|
| 812 |
_GENERATION = [0]
|
| 813 |
+
#: Bumped after every mirror snapshot install (`MirrorStore._install_snapshot`). D-2670: the
|
| 814 |
+
#: Sheet change token caches its table scan per generation, so an install must move this.
|
| 815 |
+
_MIRROR_INSTALLS = [0]
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
def note_mirror_install():
|
| 819 |
+
"""Mark that a mirror install committed or rolled back, so cached change tokens recompute."""
|
| 820 |
+
_MIRROR_INSTALLS[0] += 1
|
| 821 |
+
|
| 822 |
+
|
| 823 |
+
def mirror_generation():
|
| 824 |
+
"""The install generation of the serving mirror: file swaps and snapshot installs both move it."""
|
| 825 |
+
return (str(DB_PATH), _GENERATION[0], _MIRROR_INSTALLS[0])
|
| 826 |
|
| 827 |
|
| 828 |
def mark_ready():
|
platform/harness/mirror_store.py
CHANGED
|
@@ -584,6 +584,9 @@ class MirrorStore:
|
|
| 584 |
except BaseException:
|
| 585 |
con.execute("ROLLBACK")
|
| 586 |
raise
|
|
|
|
|
|
|
|
|
|
| 587 |
|
| 588 |
|
| 589 |
def restore_mirror(self, tenant_key, rt, log=None):
|
|
|
|
| 584 |
except BaseException:
|
| 585 |
con.execute("ROLLBACK")
|
| 586 |
raise
|
| 587 |
+
finally:
|
| 588 |
+
# D-2670: a cached Sheet change token never outlives an install.
|
| 589 |
+
datastore.note_mirror_install()
|
| 590 |
|
| 591 |
|
| 592 |
def restore_mirror(self, tenant_key, rt, log=None):
|
platform/harness/mirror_tokens.py
CHANGED
|
@@ -13,11 +13,36 @@ does it. Until then that function RAISES, which `database_change_token` already
|
|
| 13 |
prove unchanged, therefore resolve" -- the safe direction.
|
| 14 |
"""
|
| 15 |
from __future__ import annotations
|
|
|
|
| 16 |
import re
|
|
|
|
|
|
|
| 17 |
|
| 18 |
from core import sheet_binding
|
| 19 |
from core.sheet_binding import fingerprint
|
| 20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
def mirror_change_token(st, database):
|
| 23 |
"""One SQL token read over source tables, not N binding queries or Python row copies.
|
|
@@ -44,7 +69,11 @@ def mirror_change_token(st, database):
|
|
| 44 |
if not sources or any(not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", s) for s in sources):
|
| 45 |
raise RuntimeError("The connector source identity is invalid.")
|
| 46 |
sources = sorted(sources)
|
|
|
|
|
|
|
| 47 |
cur = mirror_cursor(st)
|
|
|
|
|
|
|
| 48 |
placeholders = ",".join("?" for _ in sources)
|
| 49 |
# An ENTITIES table or a link target may be absent from a seed. A connector's own source may not.
|
| 50 |
present = set()
|
|
@@ -60,14 +89,37 @@ def mirror_change_token(st, database):
|
|
| 60 |
f"CAST(bit_xor(hash(t)) AS VARCHAR) AS x, "
|
| 61 |
f"CAST(sum(CAST(hash(t) AS HUGEINT)) AS VARCHAR) AS s FROM \"{source}\" t"
|
| 62 |
for source in hashed]
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
if not any(row[0] == "sync" for row in rows):
|
| 72 |
raise RuntimeError("The connector has no sync receipt.")
|
| 73 |
absent = sorted(optional - present)
|
|
|
|
| 13 |
prove unchanged, therefore resolve" -- the safe direction.
|
| 14 |
"""
|
| 15 |
from __future__ import annotations
|
| 16 |
+
import os
|
| 17 |
import re
|
| 18 |
+
import threading
|
| 19 |
+
import time
|
| 20 |
|
| 21 |
from core import sheet_binding
|
| 22 |
from core.sheet_binding import fingerprint
|
| 23 |
|
| 24 |
+
# D-2670: database -> (key, table rows). The key holds the mirror file's size and mtime (and its
|
| 25 |
+
# WAL's), the install generation, the receipts and the schema, so any committed write rescans.
|
| 26 |
+
_TABLE_ROWS = {}
|
| 27 |
+
_TABLE_ROWS_LOCK = threading.Lock()
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _file_marks(cur):
|
| 31 |
+
"""Size and mtime of the mirror file and its WAL, or None when the mirror has no file."""
|
| 32 |
+
row = cur.execute("SELECT path FROM duckdb_databases() "
|
| 33 |
+
"WHERE database_name = current_database()").fetchone()
|
| 34 |
+
path = row[0] if row else None
|
| 35 |
+
if not path or path == ":memory:":
|
| 36 |
+
return None
|
| 37 |
+
marks = []
|
| 38 |
+
for name in (path, path + ".wal"):
|
| 39 |
+
try:
|
| 40 |
+
stat = os.stat(name)
|
| 41 |
+
marks.append([stat.st_size, stat.st_mtime_ns])
|
| 42 |
+
except OSError:
|
| 43 |
+
marks.append(None)
|
| 44 |
+
return marks
|
| 45 |
+
|
| 46 |
|
| 47 |
def mirror_change_token(st, database):
|
| 48 |
"""One SQL token read over source tables, not N binding queries or Python row copies.
|
|
|
|
| 69 |
if not sources or any(not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", s) for s in sources):
|
| 70 |
raise RuntimeError("The connector source identity is invalid.")
|
| 71 |
sources = sorted(sources)
|
| 72 |
+
# Read before any table query, so a write during this call leaves its entry unusable.
|
| 73 |
+
generation = datastore.mirror_generation()
|
| 74 |
cur = mirror_cursor(st)
|
| 75 |
+
# An in-memory mirror cannot show an in-place write, so it is never cached.
|
| 76 |
+
marks = _file_marks(cur)
|
| 77 |
placeholders = ",".join("?" for _ in sources)
|
| 78 |
# An ENTITIES table or a link target may be absent from a seed. A connector's own source may not.
|
| 79 |
present = set()
|
|
|
|
| 89 |
f"CAST(bit_xor(hash(t)) AS VARCHAR) AS x, "
|
| 90 |
f"CAST(sum(CAST(hash(t) AS HUGEINT)) AS VARCHAR) AS s FROM \"{source}\" t"
|
| 91 |
for source in hashed]
|
| 92 |
+
meta = ["SELECT 'schema', table_name, column_name, data_type FROM duckdb_columns() "
|
| 93 |
+
f"WHERE table_name IN ({placeholders})",
|
| 94 |
+
# _sync_state is the resident mirror writer's receipt, not the app's status cache.
|
| 95 |
+
"SELECT 'sync', entity, phase, concat_ws('|', last_id, cursor_wd, rows, updated_at) "
|
| 96 |
+
"FROM _sync_state WHERE split_part(entity, '.', 1) IN ("
|
| 97 |
+
+ ",".join("?" for _ in receipt_sources) + ")"]
|
| 98 |
+
meta_params = [*sources, *receipt_sources]
|
| 99 |
+
sizes = ("SELECT 'size', table_name, CAST(estimated_size AS VARCHAR), '' FROM duckdb_tables() "
|
| 100 |
+
f"WHERE table_name IN ({','.join('?' for _ in hashed)})")
|
| 101 |
+
key = None if marks is None else fingerprint([
|
| 102 |
+
marks, list(generation), hashed, sorted(optional - present),
|
| 103 |
+
cur.execute(" UNION ALL ".join([*meta, sizes]) + " ORDER BY 1,2,3,4",
|
| 104 |
+
[*meta_params, *hashed]).fetchall()])
|
| 105 |
+
with _TABLE_ROWS_LOCK:
|
| 106 |
+
cached = _TABLE_ROWS.get(database)
|
| 107 |
+
if key is not None and cached is not None and cached[0] == key:
|
| 108 |
+
table_rows = cached[1]
|
| 109 |
+
else:
|
| 110 |
+
started = time.perf_counter()
|
| 111 |
+
table_rows = [tuple(row) for row in cur.execute(" UNION ALL ".join(clauses)).fetchall()]
|
| 112 |
+
if key is not None:
|
| 113 |
+
with _TABLE_ROWS_LOCK:
|
| 114 |
+
_TABLE_ROWS[database] = (key, table_rows)
|
| 115 |
+
# One line per scan: an opening GET that prints none read no mirror table.
|
| 116 |
+
print(f"[sheet-token] scan db={database} tables={len(hashed)} "
|
| 117 |
+
f"ms={round((time.perf_counter() - started) * 1000)}", flush=True)
|
| 118 |
+
# The final ORDER BY runs in DuckDB, so the token is byte for byte the uncached one.
|
| 119 |
+
values = ["SELECT CAST(? AS VARCHAR), CAST(? AS VARCHAR), CAST(? AS VARCHAR), CAST(? AS VARCHAR)"
|
| 120 |
+
for _ in table_rows]
|
| 121 |
+
rows = cur.execute(" UNION ALL ".join([*values, *meta]) + " ORDER BY 1,2,3,4",
|
| 122 |
+
[*(value for row in table_rows for value in row), *meta_params]).fetchall()
|
| 123 |
if not any(row[0] == "sync" for row in rows):
|
| 124 |
raise RuntimeError("The connector has no sync receipt.")
|
| 125 |
absent = sorted(optional - present)
|
web/public/AIOS_DEPLOY_RECEIPT
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
|
|
|
|
| 1 |
+
e1833381f5b2cd271b7e5625bcbb7826c7b92d0f735e0e2637da38ac9b962c7d
|