fsanyoto commited on
Commit
264a352
·
verified ·
1 Parent(s): 0444129

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,4 +1,4 @@
1
  {
2
- "current": "9722ffc75",
3
  "releases": []
4
  }
 
1
  {
2
+ "current": "a1ff7ebec",
3
  "releases": []
4
  }
VERSION CHANGED
@@ -1 +1 @@
1
- 9722ffc75
 
1
+ a1ff7ebec
api/main.py CHANGED
@@ -1418,6 +1418,8 @@ def _restore_amazon_mirror_once(why, tenant_key):
1418
  result = (_amazon.restore_mirror(tenant_key, rt)
1419
  if rt.datastore_path.resolve() == _ds.DB_PATH.resolve()
1420
  else TenantAmazonMirror().restore_mirror(tenant_key, rt))
 
 
1421
  if result.get("state") == "refused":
1422
  raise RuntimeError("; ".join(result.get("problems") or ["Amazon mirror restore refused."]))
1423
  # Publish measured definitions before any Odoo read can block the resident writer.
@@ -1425,7 +1427,9 @@ def _restore_amazon_mirror_once(why, tenant_key):
1425
  # The relational rebuild writes the store, so only the sync worker runs it.
1426
  if (result.get("state") != "absent" and _process_role.may_write() and
1427
  rt.datastore_path.resolve() == _ds.DB_PATH.resolve()):
 
1428
  state = _rebuild_amazon_relational(why, rt)
 
1429
  if state.get("changed") and not state.get("applied") and not state.get("known"):
1430
  raise RuntimeError("Amazon mirror restored but relational rebuild failed.")
1431
  if result.get("problems"):
@@ -1433,10 +1437,13 @@ def _restore_amazon_mirror_once(why, tenant_key):
1433
  "type": "PartialRestore", "message": "; ".join(result["problems"])}
1434
  else:
1435
  RESYNC_STATE.setdefault("amazonRestoreErrors", {}).pop(tenant_key, None)
 
1436
  _rot.invalidate_sources()
1437
  _rot._sources()
 
1438
  print(f"[aios-api] amazon mirror {tenant_key} {result.get('state')} ({why}) in "
1439
- f"{_t.time() - started:.0f}s, before the Odoo catch-up")
 
1440
  return not bool(result.get("problems"))
1441
  except Exception as exc: # noqa: BLE001
1442
  RESYNC_STATE.setdefault("amazonRestoreErrors", {})[tenant_key] = {
@@ -3334,16 +3341,31 @@ def _sync_idle_wait(event, seconds):
3334
 
3335
  def _amazon_intraday_pass(tenant_key, previous_fingerprint):
3336
  """Run due Amazon tables and their projection without advancing the Odoo pass clock."""
3337
- if globals().get("_AMAZON_DESK", {}).get("job") is not None:
 
 
 
 
 
 
3338
  return previous_fingerprint
 
 
 
3339
  try:
3340
  from harness import amazon_store, runtime
3341
  rt = runtime.get_runtime(tenant_key)
3342
- if not amazon_store.credential(tenant_key, rt=rt) or amazon_store.first_load_job_live(rt):
3343
- return previous_fingerprint
 
 
3344
  plan = amazon_store.scheduled_sync_plan(tenant_key, rt=rt)
3345
  if not plan["tables"]:
3346
- return previous_fingerprint
 
 
 
 
3347
  print("[aios-api] amazon intraday pass due: " + ", ".join(plan["tables"]), flush=True)
3348
  RESYNC_STATE["slotPass"] = False
3349
  _pull_amazon("intraday")
 
1418
  result = (_amazon.restore_mirror(tenant_key, rt)
1419
  if rt.datastore_path.resolve() == _ds.DB_PATH.resolve()
1420
  else TenantAmazonMirror().restore_mirror(tenant_key, rt))
1421
+ # Each restore phase is timed, so a slow boot names the step that held it.
1422
+ phases = {"store restore": _t.time() - started}
1423
  if result.get("state") == "refused":
1424
  raise RuntimeError("; ".join(result.get("problems") or ["Amazon mirror restore refused."]))
1425
  # Publish measured definitions before any Odoo read can block the resident writer.
 
1427
  # The relational rebuild writes the store, so only the sync worker runs it.
1428
  if (result.get("state") != "absent" and _process_role.may_write() and
1429
  rt.datastore_path.resolve() == _ds.DB_PATH.resolve()):
1430
+ rebuild_started = _t.time()
1431
  state = _rebuild_amazon_relational(why, rt)
1432
+ phases["relational rebuild"] = _t.time() - rebuild_started
1433
  if state.get("changed") and not state.get("applied") and not state.get("known"):
1434
  raise RuntimeError("Amazon mirror restored but relational rebuild failed.")
1435
  if result.get("problems"):
 
1437
  "type": "PartialRestore", "message": "; ".join(result["problems"])}
1438
  else:
1439
  RESYNC_STATE.setdefault("amazonRestoreErrors", {}).pop(tenant_key, None)
1440
+ sources_started = _t.time()
1441
  _rot.invalidate_sources()
1442
  _rot._sources()
1443
+ phases["sources"] = _t.time() - sources_started
1444
  print(f"[aios-api] amazon mirror {tenant_key} {result.get('state')} ({why}) in "
1445
+ f"{_t.time() - started:.0f}s, before the Odoo catch-up ("
1446
+ + ", ".join(f"{name} {seconds:.0f}s" for name, seconds in phases.items()) + ")")
1447
  return not bool(result.get("problems"))
1448
  except Exception as exc: # noqa: BLE001
1449
  RESYNC_STATE.setdefault("amazonRestoreErrors", {})[tenant_key] = {
 
3341
 
3342
  def _amazon_intraday_pass(tenant_key, previous_fingerprint):
3343
  """Run due Amazon tables and their projection without advancing the Odoo pass clock."""
3344
+ # One log line per change of skip reason, never one per loop turn.
3345
+ skip = globals().setdefault("_AMAZON_INTRADAY_SKIP", [None])
3346
+
3347
+ def skipped(reason):
3348
+ if reason != skip[0]:
3349
+ skip[0] = reason
3350
+ print(f"[aios-api] amazon intraday pass skipped: {reason}", flush=True)
3351
  return previous_fingerprint
3352
+
3353
+ if globals().get("_AMAZON_DESK", {}).get("job") is not None:
3354
+ return skipped("a Sync now desk turn is running")
3355
  try:
3356
  from harness import amazon_store, runtime
3357
  rt = runtime.get_runtime(tenant_key)
3358
+ if not amazon_store.credential(tenant_key, rt=rt):
3359
+ return skipped(f"no stored amazon_sp credential for {tenant_key}")
3360
+ if amazon_store.first_load_job_live(rt):
3361
+ return skipped("the first-load job holds the Amazon writer lease")
3362
  plan = amazon_store.scheduled_sync_plan(tenant_key, rt=rt)
3363
  if not plan["tables"]:
3364
+ deferred = plan.get("deferred") or {}
3365
+ first = next(iter(deferred.items()), None)
3366
+ return skipped(f"no table is due ({len(deferred)} deferred"
3367
+ + (f"; {first[0]}: {first[1]})" if first else ")"))
3368
+ skip[0] = None
3369
  print("[aios-api] amazon intraday pass due: " + ", ".join(plan["tables"]), flush=True)
3370
  RESYNC_STATE["slotPass"] = False
3371
  _pull_amazon("intraday")
api/registry_source.py CHANGED
@@ -6,6 +6,7 @@ from dataclasses import is_dataclass, replace
6
  from deps import err
7
 
8
  BATCH_ROWS = 1024
 
9
 
10
 
11
  def with_runtime(session, runtime):
@@ -52,7 +53,10 @@ def paths(runtime, name, selected):
52
  reader = backend(runtime)
53
  method = getattr(reader, 'get_json_paths', None)
54
  if callable(method):
55
- return method(getattr(runtime, 'store_key', str)(name), selected)
 
 
 
56
  doc = runtime.get(name) or {}
57
  out = []
58
  for path in selected:
@@ -144,8 +148,11 @@ def members(runtime, name, path, ids, *, id_key=None, source_limit=None):
144
  reader = backend(runtime)
145
  method = getattr(reader, 'get_json_members', None)
146
  if callable(method):
147
- return method(getattr(runtime, 'store_key', str)(name), path, ids,
148
- id_key=id_key, source_limit=source_limit)
 
 
 
149
  value = runtime.get(name) or {}
150
  for part in path:
151
  value = value[int(part)] if isinstance(value, list) else value.get(str(part), {})
@@ -722,13 +729,15 @@ def canonical_selection(session, cur, table_key, metadata, needed, *, ids=None):
722
  cur.remove_function(hash_function)
723
 
724
 
725
- def canonical_batches(session, cur, table_key, *, ids=None, needed=None, metric_window=None, related=None):
 
726
  """Refuse a failed compiled source by name without publishing an empty population."""
727
  from fastapi import HTTPException
728
  from core.request_timing import raise_if_resource_error
729
  try:
730
  with closing(_canonical_batches(session, cur, table_key, ids=ids, needed=needed,
731
- metric_window=metric_window, related=related)) as batches:
 
732
  yield from batches
733
  except HTTPException:
734
  raise
@@ -737,7 +746,8 @@ def canonical_batches(session, cur, table_key, *, ids=None, needed=None, metric_
737
  raise err(503, 'canonical_source_unavailable', f'{table_key}: {type(exc).__name__}: {str(exc)[:180]}') from exc
738
 
739
 
740
- def _canonical_batches(session, cur, table_key, *, ids=None, needed=None, metric_window=None, related=None):
 
741
  """Run canonical family, permission, overlay and measure projections over bounded identities."""
742
  import aios_grid
743
  import routes_customers as customers
@@ -749,9 +759,10 @@ def _canonical_batches(session, cur, table_key, *, ids=None, needed=None, metric
749
  raise err(503, 'canonical_source_unavailable', f'{table_key} has no compiled source for this tenant.')
750
  session.require(table_key)
751
  team, agent = perm_scope.derive_pool_scope(session.user, table_key)
752
- before = generation(session, table_key)
753
- metadata = {'_scan': ids is None}
754
- definition = canonical_metadata(session, table_key, metadata=metadata, cur=cur)
 
755
  # Every permanent wall operand is populated before apply_row_scope judges the batch.
756
  tree = perm_scope.entry(session.user, table_key) or {}
757
  wall = tree.get('filter') or {}
@@ -791,12 +802,14 @@ def _canonical_batches(session, cur, table_key, *, ids=None, needed=None, metric
791
  paused = routes_keychain.odoo_paused(session.runtime)
792
  pool_key = ('product_pool', team) if table_key == 'product_data' else ('pool', team, agent)
793
  cached = session.runtime.pool_cache.get(pool_key)
 
 
794
  if cached and (paused or time.time() - cached[0] < 900):
795
  import itertools
796
  def borrowed():
797
  source = (r for r in cached[1] if ids is None or r['pid'] in ids)
798
  while True:
799
- batch = list(itertools.islice(source, BATCH_ROWS))
800
  if not batch:
801
  return
802
  yield batch
@@ -809,7 +822,7 @@ def _canonical_batches(session, cur, table_key, *, ids=None, needed=None, metric
809
  def frozen():
810
  source = (r for r in hit[1] if ids is None or r['pid'] in ids)
811
  while True:
812
- batch = list(itertools.islice(source, BATCH_ROWS))
813
  if not batch:
814
  return
815
  yield batch
@@ -848,7 +861,13 @@ def _canonical_batches(session, cur, table_key, *, ids=None, needed=None, metric
848
  ledger_batches=items(session.runtime, customer_data.LEDGER_KEY, selected=ids)
849
  if not agent and team is None and session.runtime.exists(customer_data.LEDGER_KEY) else ())
850
  with canonical_source.mirrored(source_cur, runtime, kind=kind), closing(source):
851
- yield from source
 
 
 
 
 
 
852
  finally:
853
  if owned is not None:
854
  owned.close()
@@ -894,7 +913,10 @@ def canonical_grid(session, cur, table_key, *, needed=None, metric_window=None):
894
  import odoo_relational as rel
895
  import routes_odoo_tables as rot
896
  from modules import sheet
897
- g = canonical_metadata(session, table_key)
 
 
 
898
  fields = g['fields']
899
  agent_field = {'key': 'agent_id', 'type': 'int', 'label': 'Current agent ID'}
900
  join_agent = False
@@ -912,7 +934,8 @@ def canonical_grid(session, cur, table_key, *, needed=None, metric_window=None):
912
  def rows():
913
  seen = False
914
  empty_limits = {}
915
- with closing(canonical_batches(session, cur, table_key, needed=needed, metric_window=metric_window)) as batches:
 
916
  for batch in batches:
917
  if batch['rows']:
918
  seen = True
 
6
  from deps import err
7
 
8
  BATCH_ROWS = 1024
9
+ PATH_LIMIT = 4096
10
 
11
 
12
  def with_runtime(session, runtime):
 
53
  reader = backend(runtime)
54
  method = getattr(reader, 'get_json_paths', None)
55
  if callable(method):
56
+ # The store door reads at most PATH_LIMIT paths per call, so a whole product drill chunks.
57
+ key, selected = getattr(runtime, 'store_key', str)(name), list(selected)
58
+ return [value for start in range(0, len(selected), PATH_LIMIT)
59
+ for value in method(key, selected[start:start + PATH_LIMIT])]
60
  doc = runtime.get(name) or {}
61
  out = []
62
  for path in selected:
 
148
  reader = backend(runtime)
149
  method = getattr(reader, 'get_json_members', None)
150
  if callable(method):
151
+ # The store door reads at most PATH_LIMIT ids per call. Above it, order is per chunk.
152
+ key, ids = getattr(runtime, 'store_key', str)(name), list(dict.fromkeys(str(int(pid)) for pid in ids))
153
+ return [item for start in range(0, len(ids), PATH_LIMIT)
154
+ for item in method(key, path, ids[start:start + PATH_LIMIT],
155
+ id_key=id_key, source_limit=source_limit)]
156
  value = runtime.get(name) or {}
157
  for part in path:
158
  value = value[int(part)] if isinstance(value, list) else value.get(str(part), {})
 
729
  cur.remove_function(hash_function)
730
 
731
 
732
+ def canonical_batches(session, cur, table_key, *, ids=None, needed=None, metric_window=None, related=None,
733
+ metadata=None):
734
  """Refuse a failed compiled source by name without publishing an empty population."""
735
  from fastapi import HTTPException
736
  from core.request_timing import raise_if_resource_error
737
  try:
738
  with closing(_canonical_batches(session, cur, table_key, ids=ids, needed=needed,
739
+ metric_window=metric_window, related=related,
740
+ metadata=metadata)) as batches:
741
  yield from batches
742
  except HTTPException:
743
  raise
 
746
  raise err(503, 'canonical_source_unavailable', f'{table_key}: {type(exc).__name__}: {str(exc)[:180]}') from exc
747
 
748
 
749
+ def _canonical_batches(session, cur, table_key, *, ids=None, needed=None, metric_window=None, related=None,
750
+ metadata=None):
751
  """Run canonical family, permission, overlay and measure projections over bounded identities."""
752
  import aios_grid
753
  import routes_customers as customers
 
759
  raise err(503, 'canonical_source_unavailable', f'{table_key} has no compiled source for this tenant.')
760
  session.require(table_key)
761
  team, agent = perm_scope.derive_pool_scope(session.user, table_key)
762
+ # A caller's request snapshot carries the generation taken before its first read.
763
+ metadata = {'_scan': ids is None} if metadata is None else metadata
764
+ before = metadata.get('_generation') or generation(session, table_key)
765
+ definition = metadata.get('_definition') or canonical_metadata(session, table_key, metadata=metadata, cur=cur)
766
  # Every permanent wall operand is populated before apply_row_scope judges the batch.
767
  tree = perm_scope.entry(session.user, table_key) or {}
768
  wall = tree.get('filter') or {}
 
802
  paused = routes_keychain.odoo_paused(session.runtime)
803
  pool_key = ('product_pool', team) if table_key == 'product_data' else ('pool', team, agent)
804
  cached = session.runtime.pool_cache.get(pool_key)
805
+ # One product assembly per drill: its store reads cost per call, not per row (sdlc85:23).
806
+ size = None if table_key == 'product_data' else BATCH_ROWS
807
  if cached and (paused or time.time() - cached[0] < 900):
808
  import itertools
809
  def borrowed():
810
  source = (r for r in cached[1] if ids is None or r['pid'] in ids)
811
  while True:
812
+ batch = list(itertools.islice(source, size))
813
  if not batch:
814
  return
815
  yield batch
 
822
  def frozen():
823
  source = (r for r in hit[1] if ids is None or r['pid'] in ids)
824
  while True:
825
+ batch = list(itertools.islice(source, size))
826
  if not batch:
827
  return
828
  yield batch
 
861
  ledger_batches=items(session.runtime, customer_data.LEDGER_KEY, selected=ids)
862
  if not agent and team is None and session.runtime.exists(customer_data.LEDGER_KEY) else ())
863
  with canonical_source.mirrored(source_cur, runtime, kind=kind), closing(source):
864
+ if size is not None:
865
+ yield from source
866
+ else:
867
+ # Source reads stay bounded per batch. Rows join here, inside the mirror context.
868
+ whole = [row for batch in source for row in batch]
869
+ if whole:
870
+ yield whole
871
  finally:
872
  if owned is not None:
873
  owned.close()
 
913
  import odoo_relational as rel
914
  import routes_odoo_tables as rot
915
  from modules import sheet
916
+ # One request snapshot serves the field list and every batch: one membership read per view.
917
+ session.require(table_key)
918
+ shared = {'_scan': True, '_generation': generation(session, table_key)}
919
+ g = shared['_definition'] = canonical_metadata(session, table_key, metadata=shared, cur=cur)
920
  fields = g['fields']
921
  agent_field = {'key': 'agent_id', 'type': 'int', 'label': 'Current agent ID'}
922
  join_agent = False
 
934
  def rows():
935
  seen = False
936
  empty_limits = {}
937
+ with closing(canonical_batches(session, cur, table_key, needed=needed, metric_window=metric_window,
938
+ metadata=shared)) as batches:
939
  for batch in batches:
940
  if batch['rows']:
941
  seen = True
api/routes_amazon_projects.py CHANGED
@@ -38,7 +38,7 @@ FIELDS = {"name": "name", "status": "status", "priority": "priority", "owner": "
38
  "completedOn": "completed_on", "resultConfigs": "result_configs", "contributors": "contributors"}
39
  #: Project JSON keys a client may echo back. They are ignored, never written.
40
  READ_ONLY = frozenset(("id", "health", "targetCount", "createdAt", "updatedAt", "createdBy",
41
- "rollup", "impact", "via"))
42
 
43
 
44
  def _call(fn, *args, **kwargs):
@@ -545,6 +545,114 @@ def _reported_reason(reported):
545
  return f"Amazon has reported economics through {reported.day} {_MONTHS[reported.month - 1]}."
546
 
547
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
548
  @router.get("")
549
  def row_projects(grain: str | None = None, key: str | None = None,
550
  session: Session = Depends(require_session)):
@@ -554,13 +662,17 @@ def row_projects(grain: str | None = None, key: str | None = None,
554
  today = projects._today()
555
  if grain is None and key is None:
556
  records = _call(projects.list_projects, runtime)
 
557
  return {"grain": None, "key": None, "canEdit": can_edit, "today": today.isoformat(),
558
- "projects": [_project(r, today) for r in records], "summary": projects.summary(records)}
 
559
  pair = _pair(grain, key)
560
  above, cause = _mirror(runtime, lambda cur: projects.lineage(cur, *pair), [])
561
  pairs = [pair] + [p for p in above if p != pair]
562
  listed = _distinct(_call(projects.projects_for, runtime, pairs), pairs)
563
- out = [{**_project(record, today), "via": {"grain": via[0], "key": via[1]}} for via, record in listed]
 
 
564
  return _with_cause({"grain": pair[0], "key": pair[1], "canEdit": can_edit, "today": today.isoformat(), "projects": out,
565
  "summary": projects.summary([record for _via, record in listed])}, cause)
566
 
@@ -704,40 +816,8 @@ def project_result_series(project_id: str, start: str | None = Query(None, alias
704
  "key": key} for key in selected["keys"]] if selected else [])
705
  available = _result_sources(session, targets + selected_targets)
706
  con = routes_sku_actions._results_mirror(runtime)
707
- bounds, reported = _reported_series_bounds(record, bounds, _last_reported_economics_day(con))
708
- cut_reason = _reported_reason(reported) if reported else None
709
- reason = None
710
- sku_count_reason = None
711
- try:
712
- skus = projects.resolve_target_skus(con, targets)
713
- if selected:
714
- selected_skus = set(projects.resolve_target_skus(con, selected_targets))
715
- skus = [sku for sku in skus if sku in selected_skus]
716
- if not skus:
717
- reason = "No project targets match the selected scope."
718
- elif not bounds["days"]:
719
- reason = cut_reason or "Today is incomplete. No completed days are available in this range."
720
- except projects.MirrorUnreadable as exc:
721
- skus, reason = [], str(exc)
722
- sku_count_reason = reason
723
- figures = {}
724
-
725
- def read(key):
726
- if reason:
727
- return {"reason": reason}
728
- metric = "sales" if key == "sales_yoy" else key
729
- if metric not in _SERIES_UNAVAILABLE and metric not in figures:
730
- figures[metric] = _result_figure(con, {"metric": metric}, bounds, skus, available)
731
- measured = _series_figure(key, figures.get(metric, {}), bounds)
732
- if cut_reason and measured.get("total") is not None:
733
- measured = {**measured, "reason": cut_reason}
734
- return measured
735
-
736
- answer = project_results.series(record, bounds=bounds, read=read,
737
- independent=lambda key: _series_economics_total(con, key, bounds, skus, available))
738
- return {**answer, "reportedThrough": reported.isoformat() if reported else None,
739
- "skuCount": len(skus) if sku_count_reason is None else None,
740
- "skuCountReason": sku_count_reason}
741
  except HTTPException:
742
  raise
743
  except (project_results.ValidationFailed, sku_action_results.ValidationFailed):
 
38
  "completedOn": "completed_on", "resultConfigs": "result_configs", "contributors": "contributors"}
39
  #: Project JSON keys a client may echo back. They are ignored, never written.
40
  READ_ONLY = frozenset(("id", "health", "targetCount", "createdAt", "updatedAt", "createdBy",
41
+ "rollup", "impact", "via", "figures"))
42
 
43
 
44
  def _call(fn, *args, **kwargs):
 
545
  return f"Amazon has reported economics through {reported.day} {_MONTHS[reported.month - 1]}."
546
 
547
 
548
+ def _project_series(con, record, targets, available, last_reported, bounds, selected=None, selected_targets=()):
549
+ """The tied Dashboard series of one project, shared by the series door and the project list."""
550
+ bounds, reported = _reported_series_bounds(record, bounds, last_reported)
551
+ cut_reason = _reported_reason(reported) if reported else None
552
+ reason = None
553
+ sku_count_reason = None
554
+ try:
555
+ skus = projects.resolve_target_skus(con, targets)
556
+ if selected:
557
+ selected_skus = set(projects.resolve_target_skus(con, selected_targets))
558
+ skus = [sku for sku in skus if sku in selected_skus]
559
+ if not skus:
560
+ reason = "No project targets match the selected scope."
561
+ elif not bounds["days"]:
562
+ reason = cut_reason or "Today is incomplete. No completed days are available in this range."
563
+ except projects.MirrorUnreadable as exc:
564
+ skus, reason = [], str(exc)
565
+ sku_count_reason = reason
566
+ figures = {}
567
+
568
+ def read(key):
569
+ if reason:
570
+ return {"reason": reason}
571
+ metric = "sales" if key == "sales_yoy" else key
572
+ if metric not in _SERIES_UNAVAILABLE and metric not in figures:
573
+ figures[metric] = _result_figure(con, {"metric": metric}, bounds, skus, available)
574
+ measured = _series_figure(key, figures.get(metric, {}), bounds)
575
+ if cut_reason and measured.get("total") is not None:
576
+ measured = {**measured, "reason": cut_reason}
577
+ return measured
578
+
579
+ answer = project_results.series(record, bounds=bounds, read=read,
580
+ independent=lambda key: _series_economics_total(con, key, bounds, skus, available))
581
+ return {**answer, "reportedThrough": reported.isoformat() if reported else None,
582
+ "skuCount": len(skus) if sku_count_reason is None else None,
583
+ "skuCountReason": sku_count_reason}
584
+
585
+
586
+ LIST_FIGURES = ("sales", "units")
587
+ LIST_UNREADABLE = "Results could not be read. Try again shortly."
588
+ LIST_NOT_TIED = "A result total does not tie to its Amazon source."
589
+
590
+
591
+ def _withheld_figures(reason):
592
+ return {"from": None, "to": None, **{key: {"total": None, "reason": reason} for key in LIST_FIGURES}}
593
+
594
+
595
+ def _refusal_reason(exc):
596
+ detail = getattr(exc, "detail", None)
597
+ message = (detail.get("error") or {}).get("message") if isinstance(detail, dict) else None
598
+ return message or LIST_UNREADABLE
599
+
600
+
601
+ def _list_figures(session, records, today):
602
+ """`{project id: default Dashboard Sales and Units}` through one mirror cursor per request."""
603
+ # A read that fails withholds that project only. Grants are applied before the mirror opens.
604
+ out, ready, grants = {}, [], {}
605
+ for record in records:
606
+ try:
607
+ targets = _call(projects.targets, session.runtime, record["id"]) if record.get("target_count", 1) else []
608
+ grouped = any(target["grain"] != "sku" for target in targets)
609
+ if grouped not in grants:
610
+ try:
611
+ grants[grouped] = (_result_sources(session, targets), None)
612
+ except HTTPException as exc:
613
+ grants[grouped] = (None, _refusal_reason(exc))
614
+ except Exception as exc: # noqa: BLE001
615
+ print(f"[amazon-projects] list grants failed: {type(exc).__name__}: {exc}", file=sys.stderr)
616
+ grants[grouped] = (None, LIST_UNREADABLE)
617
+ available, refused = grants[grouped]
618
+ if refused:
619
+ out[record["id"]] = _withheld_figures(refused)
620
+ else:
621
+ ready.append((record, targets, available))
622
+ except HTTPException as exc:
623
+ out[record["id"]] = _withheld_figures(_refusal_reason(exc))
624
+ except Exception as exc: # noqa: BLE001
625
+ print(f"[amazon-projects] list targets failed: {type(exc).__name__}: {exc}", file=sys.stderr)
626
+ out[record["id"]] = _withheld_figures(LIST_UNREADABLE)
627
+ if not ready:
628
+ return out
629
+ try:
630
+ con = routes_sku_actions._results_mirror(session.runtime)
631
+ except HTTPException as exc:
632
+ out.update({record["id"]: _withheld_figures(_refusal_reason(exc)) for record, _t, _a in ready})
633
+ return out
634
+ try:
635
+ last_reported = _last_reported_economics_day(con)
636
+ for record, targets, available in ready:
637
+ try:
638
+ bounds = project_results.series_window(record, today=today)
639
+ answer = _project_series(con, record, targets, available, last_reported, bounds)
640
+ metrics = {metric["key"]: metric for metric in answer["metrics"]}
641
+ out[record["id"]] = {"from": answer["from"], "to": answer["to"],
642
+ **{key: {"total": metrics[key]["total"], "reason": metrics[key]["reason"]}
643
+ for key in LIST_FIGURES}}
644
+ except (project_results.ValidationFailed, sku_action_results.ValidationFailed):
645
+ out[record["id"]] = _withheld_figures(LIST_NOT_TIED)
646
+ except ValueError as exc:
647
+ out[record["id"]] = _withheld_figures(str(exc))
648
+ except Exception as exc: # noqa: BLE001
649
+ print(f"[amazon-projects] list figures failed: {type(exc).__name__}: {exc}", file=sys.stderr)
650
+ out[record["id"]] = _withheld_figures(LIST_UNREADABLE)
651
+ finally:
652
+ con.close()
653
+ return out
654
+
655
+
656
  @router.get("")
657
  def row_projects(grain: str | None = None, key: str | None = None,
658
  session: Session = Depends(require_session)):
 
662
  today = projects._today()
663
  if grain is None and key is None:
664
  records = _call(projects.list_projects, runtime)
665
+ figures = _list_figures(session, records, today)
666
  return {"grain": None, "key": None, "canEdit": can_edit, "today": today.isoformat(),
667
+ "projects": [{**_project(r, today), "figures": figures.get(r["id"])} for r in records],
668
+ "summary": projects.summary(records)}
669
  pair = _pair(grain, key)
670
  above, cause = _mirror(runtime, lambda cur: projects.lineage(cur, *pair), [])
671
  pairs = [pair] + [p for p in above if p != pair]
672
  listed = _distinct(_call(projects.projects_for, runtime, pairs), pairs)
673
+ figures = _list_figures(session, [record for _via, record in listed], today)
674
+ out = [{**_project(record, today), "via": {"grain": via[0], "key": via[1]}, "figures": figures.get(record["id"])}
675
+ for via, record in listed]
676
  return _with_cause({"grain": pair[0], "key": pair[1], "canEdit": can_edit, "today": today.isoformat(), "projects": out,
677
  "summary": projects.summary([record for _via, record in listed])}, cause)
678
 
 
816
  "key": key} for key in selected["keys"]] if selected else [])
817
  available = _result_sources(session, targets + selected_targets)
818
  con = routes_sku_actions._results_mirror(runtime)
819
+ return _project_series(con, record, targets, available, _last_reported_economics_day(con), bounds,
820
+ selected, selected_targets)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
821
  except HTTPException:
822
  raise
823
  except (project_results.ValidationFailed, sku_action_results.ValidationFailed):
api/routes_connectors.py CHANGED
@@ -3073,6 +3073,11 @@ def _amazon_table_schedule(rt, connection_id=None, now=None):
3073
  from harness import amazon_store as az, datastore
3074
 
3075
  now = now or datetime.now(timezone.utc)
 
 
 
 
 
3076
  result = {"tableSchedule": [], "scheduleState": "unavailable",
3077
  "displayTimezone": stored_business_tz(rt) or "UTC"}
3078
 
@@ -5285,6 +5290,9 @@ def _databases_sync_health(databases):
5285
  state = next((state for state in ("failed", "partial", "running", "queued", "never_run",
5286
  "succeeded", "disabled") if state in states), "never_run")
5287
  successes = [_sync_stamp(row.get("lastSuccess")) for row in health]
 
 
 
5288
  failure = next((row.get("error") for row in health if row.get("error")), None)
5289
  answer = _database_sync_health(state=state,
5290
  last_success=max((stamp for stamp in successes if stamp), default=None),
 
3073
  from harness import amazon_store as az, datastore
3074
 
3075
  now = now or datetime.now(timezone.utc)
3076
+ import odoo_relational as rel
3077
+ import sync_alerts
3078
+ # The worker plans on deployment phases; the web shows the same due times only with the same offset.
3079
+ if az._SCHEDULE_OFFSET_READER is None and sync_alerts.environment() in {"LIVE", "STAGING"}:
3080
+ az.register_schedule_offset(rel.slot_offset_seconds)
3081
  result = {"tableSchedule": [], "scheduleState": "unavailable",
3082
  "displayTimezone": stored_business_tz(rt) or "UTC"}
3083
 
 
5290
  state = next((state for state in ("failed", "partial", "running", "queued", "never_run",
5291
  "succeeded", "disabled") if state in states), "never_run")
5292
  successes = [_sync_stamp(row.get("lastSuccess")) for row in health]
5293
+ # One refused database beside synced siblings is a partial sync, not a failed one. The error keeps the cause.
5294
+ if state == "failed" and states & {"succeeded", "partial"}:
5295
+ state = "partial"
5296
  failure = next((row.get("error") for row in health if row.get("error")), None)
5297
  answer = _database_sync_health(state=state,
5298
  last_success=max((stamp for stamp in successes if stamp), default=None),
api/sync_worker.py CHANGED
@@ -23,6 +23,18 @@ _RI = Path(os.environ.get("RI_DIR") or (API_DIR.parents[1] / "platform"))
23
  def configure(env=None):
24
  """Set the worker role, its own DuckDB files and its DuckDB caps. Returns the worker DuckDB path."""
25
  env = os.environ if env is None else env
 
 
 
 
 
 
 
 
 
 
 
 
26
  env["AIOS_PROCESS_ROLE"] = "worker"
27
  web_store = Path(env.get("AIOS_DUCKDB_STORE_DIR") or (_RI / "data" / "store"))
28
  web_db = Path(env.get("AIOS_DUCKDB_PATH") or (web_store / "royal.duckdb"))
@@ -40,7 +52,7 @@ def configure(env=None):
40
  env["AIOS_DUCKDB_PATH"] = str(worker_db)
41
  # Leave room for Python and the web processes when a full Brand Analytics week is parsed.
42
  env["AIOS_DUCKDB_MEMORY"] = env.get("AIOS_WORKER_DUCKDB_MEMORY") or "6GB"
43
- env["AIOS_DUCKDB_THREADS"] = env.get("AIOS_WORKER_DUCKDB_THREADS") or "1"
44
  env["AIOS_DUCKDB_MAX_TEMP_SIZE"] = env.get("AIOS_WORKER_DUCKDB_MAX_TEMP_SIZE") or "16GB"
45
  # The worker holds its own file read-write. Mirror versions are for the web workers only.
46
  env["AIOS_MIRROR_VERSIONS"] = "0"
 
23
  def configure(env=None):
24
  """Set the worker role, its own DuckDB files and its DuckDB caps. Returns the worker DuckDB path."""
25
  env = os.environ if env is None else env
26
+ threads = env.get("AIOS_WORKER_DUCKDB_THREADS")
27
+ if not threads and env.get("JOB_ID"):
28
+ # An HF job owns its box: DuckDB takes the job's CPUs (at most 4), so a boot restore is not one thread.
29
+ cpus = 0
30
+ try:
31
+ cpus = int(float(env.get("CPU_CORES") or 0))
32
+ if cpus < 1:
33
+ quota, period = Path("/sys/fs/cgroup/cpu.max").read_text().split()[:2]
34
+ cpus = int(quota) // int(period) if quota != "max" else 0
35
+ except (OSError, ValueError):
36
+ cpus = 0
37
+ threads = str(max(1, min(4, cpus)))
38
  env["AIOS_PROCESS_ROLE"] = "worker"
39
  web_store = Path(env.get("AIOS_DUCKDB_STORE_DIR") or (_RI / "data" / "store"))
40
  web_db = Path(env.get("AIOS_DUCKDB_PATH") or (web_store / "royal.duckdb"))
 
52
  env["AIOS_DUCKDB_PATH"] = str(worker_db)
53
  # Leave room for Python and the web processes when a full Brand Analytics week is parsed.
54
  env["AIOS_DUCKDB_MEMORY"] = env.get("AIOS_WORKER_DUCKDB_MEMORY") or "6GB"
55
+ env["AIOS_DUCKDB_THREADS"] = threads or "1"
56
  env["AIOS_DUCKDB_MAX_TEMP_SIZE"] = env.get("AIOS_WORKER_DUCKDB_MAX_TEMP_SIZE") or "16GB"
57
  # The worker holds its own file read-write. Mirror versions are for the web workers only.
58
  env["AIOS_MIRROR_VERSIONS"] = "0"
api/turn_audit.py CHANGED
@@ -206,3 +206,18 @@ def read(rt, user, *, tenant_wide=False, week=None, offset=0, limit=50):
206
  return {"week": week, "scope": "tenant" if tenant_wide else "me", "lines": copy.deepcopy(rows[offset:offset + limit]),
207
  "total": len(rows), "offset": offset, "limit": limit, "hasMore": offset + limit < len(rows),
208
  "overflow": int(doc.get("overflow") or 0) if tenant_wide else None, "retainedMax": MAX_LINES}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  return {"week": week, "scope": "tenant" if tenant_wide else "me", "lines": copy.deepcopy(rows[offset:offset + limit]),
207
  "total": len(rows), "offset": offset, "limit": limit, "hasMore": offset + limit < len(rows),
208
  "overflow": int(doc.get("overflow") or 0) if tenant_wide else None, "retainedMax": MAX_LINES}
209
+
210
+
211
+ def read_weeks(rt, weeks):
212
+ """Each week's tenant-wide lines, newest first, from one batched store read when offered."""
213
+ keys = {week: week_key(week) for week in weeks}
214
+ reader = getattr(rt, "get_many", None)
215
+ found = reader(list(keys.values())) if callable(reader) and keys else None
216
+ if not isinstance(found, dict):
217
+ found = {key: rt.get(key) for key in keys.values()}
218
+ out = {}
219
+ for week, key in keys.items():
220
+ doc = found.get(key) or {}
221
+ out[week] = {"week": week, "lines": copy.deepcopy(list(reversed(doc.get("lines") or []))),
222
+ "overflow": int(doc.get("overflow") or 0)}
223
+ return out
api/usage_activity.py CHANGED
@@ -67,7 +67,8 @@ def _unlimited_prefix(reader):
67
  rows = reader(limit)
68
  if len(rows) < limit:
69
  return rows
70
- limit *= 2
 
71
 
72
 
73
  def _tenant_row(row, tenant):
@@ -162,12 +163,14 @@ def _cells(session, start, stop, now, source):
162
  def _views(session, start, stop, now, source):
163
  source["retention"] = {"days": None, "documentRowsPerTable": view_audit.RING_CAP}
164
  from core.view_templates import _WS_KEYS
165
- keys = set(_WS_KEYS.values()) | {key for key in session.runtime.list_keys("ut_")
166
- if key.endswith("_table_workspace")}
167
- for table in sorted(keys):
168
- home = view_audit.home(session.runtime, table)
169
- data = None
170
- if home == view_audit.DOCUMENT:
 
 
171
  # Read outside rows(), whose legacy document fallback swallows store failures.
172
  data = session.runtime.get(table) or {}
173
  ring = data.get(view_audit.AUDIT_KEY) or []
@@ -176,8 +179,8 @@ def _views(session, start, stop, now, source):
176
  source["heldFrom"] = max(source["heldFrom"], held)
177
  source["limitations"].append({"code": "view_ring", "cause":
178
  "A view document retains only its newest 2000 audit rows."})
179
- rows = _unlimited_prefix(lambda limit: view_audit.rows(session.runtime,
180
- table_key=table, since=math.nextafter(start.timestamp(), -math.inf), limit=limit, data=data))
181
  for row in rows:
182
  if _tenant_row(row, session.tenant):
183
  yield _timestamp(row["ts"]), row.get("actor") or "", "view_edit"
@@ -186,35 +189,31 @@ def _views(session, start, stop, now, source):
186
  def _turns(session, start, stop, now, source):
187
  source["retention"] = {"days": None, "linesPerWeek": turn_audit.MAX_LINES,
188
  "bytesPerWeek": turn_audit.MAX_BYTES}
 
189
  monday = start.date() - timedelta(days=start.weekday())
190
  while monday <= min(stop, now).date():
191
  year, week, _ = monday.isocalendar()
192
- week = f"{year}-W{week:02d}"
193
- offset = 0
 
 
 
 
194
  capped, oldest = None, None
195
- while True:
196
- page = turn_audit.read(session.runtime, session.uname, tenant_wide=True,
197
- week=week, offset=offset, limit=PAGE)
198
- if offset == 0 and page["overflow"]:
199
- capped = {"code": "turn_week_cap", "week": week,
200
- "lost": page["overflow"], "limit": turn_audit.MAX_LINES,
201
- "cause": "Weekly turn documents evict oldest rows above the line or byte limit."}
202
- source["limitations"].append(capped)
203
- for row in page["lines"]:
204
- if _tenant_row(row, session.tenant):
205
- stamp = _timestamp(row["ts"])
206
- oldest = min(oldest, stamp) if oldest is not None else stamp
207
- yield stamp, row.get("user") or "", "ai_turn"
208
- if not page["hasMore"]:
209
- break
210
- if not page["lines"]:
211
- raise RuntimeError("Turn cursor did not advance.")
212
- offset += len(page["lines"])
213
  if capped is not None:
214
  held = oldest or datetime.combine(monday + timedelta(days=7), time.min, UTC)
215
  capped["heldFrom"] = held.isoformat()
216
  source["heldFrom"] = max(source["heldFrom"], held.isoformat())
217
- monday += timedelta(days=7)
218
 
219
 
220
  READERS = {"security_events": _security, "activity_events": _activity,
 
67
  rows = reader(limit)
68
  if len(rows) < limit:
69
  return rows
70
+ # Grow 16x: each re-read costs about 0.5 s on staging, so doubling spent 6 s on 14k rows.
71
+ limit *= 16
72
 
73
 
74
  def _tenant_row(row, tenant):
 
163
  def _views(session, start, stop, now, source):
164
  source["retention"] = {"days": None, "documentRowsPerTable": view_audit.RING_CAP}
165
  from core.view_templates import _WS_KEYS
166
+ keys = sorted(set(_WS_KEYS.values()) | {key for key in session.runtime.list_keys("ut_")
167
+ if key.endswith("_table_workspace")})
168
+ since = math.nextafter(start.timestamp(), -math.inf)
169
+ # One read per audit home: a per-table loop of three round trips ran 180 to 217 s on the Space.
170
+ trails = view_audit.rows_many(session.runtime, keys, since=since)
171
+ for table in keys:
172
+ rows = trails[table]
173
+ if rows is None:
174
  # Read outside rows(), whose legacy document fallback swallows store failures.
175
  data = session.runtime.get(table) or {}
176
  ring = data.get(view_audit.AUDIT_KEY) or []
 
179
  source["heldFrom"] = max(source["heldFrom"], held)
180
  source["limitations"].append({"code": "view_ring", "cause":
181
  "A view document retains only its newest 2000 audit rows."})
182
+ rows = _unlimited_prefix(lambda limit: view_audit.rows(session.runtime,
183
+ table_key=table, since=since, limit=limit, data=data))
184
  for row in rows:
185
  if _tenant_row(row, session.tenant):
186
  yield _timestamp(row["ts"]), row.get("actor") or "", "view_edit"
 
189
  def _turns(session, start, stop, now, source):
190
  source["retention"] = {"days": None, "linesPerWeek": turn_audit.MAX_LINES,
191
  "bytesPerWeek": turn_audit.MAX_BYTES}
192
+ weeks = []
193
  monday = start.date() - timedelta(days=start.weekday())
194
  while monday <= min(stop, now).date():
195
  year, week, _ = monday.isocalendar()
196
+ weeks.append((monday, f"{year}-W{week:02d}"))
197
+ monday += timedelta(days=7)
198
+ # Every week document in one batched read, each read once instead of once per page.
199
+ documents = turn_audit.read_weeks(session.runtime, [week for _, week in weeks])
200
+ for monday, week in weeks:
201
+ page = documents[week]
202
  capped, oldest = None, None
203
+ if page["overflow"]:
204
+ capped = {"code": "turn_week_cap", "week": week,
205
+ "lost": page["overflow"], "limit": turn_audit.MAX_LINES,
206
+ "cause": "Weekly turn documents evict oldest rows above the line or byte limit."}
207
+ source["limitations"].append(capped)
208
+ for row in page["lines"]:
209
+ if _tenant_row(row, session.tenant):
210
+ stamp = _timestamp(row["ts"])
211
+ oldest = min(oldest, stamp) if oldest is not None else stamp
212
+ yield stamp, row.get("user") or "", "ai_turn"
 
 
 
 
 
 
 
 
213
  if capped is not None:
214
  held = oldest or datetime.combine(monday + timedelta(days=7), time.min, UTC)
215
  capped["heldFrom"] = held.isoformat()
216
  source["heldFrom"] = max(source["heldFrom"], held.isoformat())
 
217
 
218
 
219
  READERS = {"security_events": _security, "activity_events": _activity,
platform/core/view_audit.py CHANGED
@@ -129,7 +129,8 @@ def _accepts(fn, *names):
129
  own closure looks identical to a backend that refused the keyword, so catching it would turn
130
  a genuine bug in a write callback into a silent downgrade to the advisory path.
131
  """
132
- key = (getattr(fn, '__module__', ''), getattr(fn, '__qualname__', repr(fn)), names)
 
133
  hit = _ACCEPTS_CACHE.get(key)
134
  if hit is None:
135
  import inspect
@@ -240,16 +241,116 @@ def _pg_rows(st, *, table_key, since, limit):
240
  params.append(int(limit))
241
  with store_pg._pool().connection() as con:
242
  found = con.execute(sql, params).fetchall()
243
- out = []
244
- for at, tenant_slug, username, action, target, detail in found:
245
- entry = dict(detail or {})
246
- entry.setdefault('tenant', tenant_slug)
247
- entry.setdefault('actor', username)
248
- entry['action'] = str(action or '')[len(PG_ACTION_PREFIX):] or entry.get('action')
249
- if at is not None and not entry.get('ts'):
250
- entry['ts'] = at.timestamp()
251
- entry.setdefault('table_key', str(target or '').split('/', 1)[0] or None)
252
- out.append(entry)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253
  return out
254
 
255
 
 
129
  own closure looks identical to a backend that refused the keyword, so catching it would turn
130
  a genuine bug in a write callback into a silent downgrade to the advisory path.
131
  """
132
+ # repr() only as a fallback: a bound TenantRuntime method's repr renders every runtime cache.
133
+ key = (getattr(fn, '__module__', ''), getattr(fn, '__qualname__', None) or repr(fn), names)
134
  hit = _ACCEPTS_CACHE.get(key)
135
  if hit is None:
136
  import inspect
 
241
  params.append(int(limit))
242
  with store_pg._pool().connection() as con:
243
  found = con.execute(sql, params).fetchall()
244
+ return [_pg_entry(*found_row) for found_row in found]
245
+
246
+
247
+ def _pg_entry(at, tenant_slug, username, action, target, detail):
248
+ """One `control.audit` row as the C3 row shape."""
249
+ entry = dict(detail or {})
250
+ entry.setdefault('tenant', tenant_slug)
251
+ entry.setdefault('actor', username)
252
+ entry['action'] = str(action or '')[len(PG_ACTION_PREFIX):] or entry.get('action')
253
+ if at is not None and not entry.get('ts'):
254
+ entry['ts'] = at.timestamp()
255
+ entry.setdefault('table_key', str(target or '').split('/', 1)[0] or None)
256
+ return entry
257
+
258
+
259
+ def _pg_rows_many(st, table_keys, *, since):
260
+ """`control.audit` rows for many tables in ONE statement, newest first, without a limit."""
261
+ import core.store_pg as store_pg
262
+ slug = tenant_of(st)
263
+ out = {key: [] for key in table_keys}
264
+ if not out:
265
+ return out
266
+ sql = ('SELECT at, tenant_slug, username, action, target, detail FROM control.audit '
267
+ "WHERE action LIKE %s AND strpos(target, '/') > 0 "
268
+ "AND split_part(target, '/', 1) = ANY(%s::text[])")
269
+ params = [PG_ACTION_PREFIX + '%', list(out)]
270
+ if slug:
271
+ sql += ' AND tenant_slug = %s'
272
+ params.append(slug)
273
+ if since:
274
+ sql += ' AND at > to_timestamp(%s)'
275
+ params.append(float(since))
276
+ sql += ' ORDER BY at DESC, id DESC'
277
+ with store_pg._pool().connection() as con:
278
+ cursor = con.execute(sql, params)
279
+ while batch := cursor.fetchmany(500):
280
+ for found in batch:
281
+ out[str(found[4]).split('/', 1)[0]].append(_pg_entry(*found))
282
+ return out
283
+
284
+
285
+ def _settings_many(st, table_keys):
286
+ """`_view_settings_backend` for many tables, with one layout-marker read per tenant."""
287
+ from core import view_settings_rows as settings
288
+ bound = {key: settings.bind(st, key) for key in table_keys}
289
+ bound = {key: rows for key, rows in bound.items() if rows is not None}
290
+ if not bound or callable(getattr(st, 'view_settings_rows', None)):
291
+ return bound
292
+ from core.store_pg import _view_rows_many
293
+ by_slug = {}
294
+ for key, rows in bound.items():
295
+ by_slug.setdefault(rows.tenant_slug, {})[rows.name] = key
296
+ found = {}
297
+ for slug, names in by_slug.items():
298
+ for name, rows in _view_rows_many(list(names), slug).items():
299
+ found[names[name]] = rows
300
+ return found
301
+
302
+
303
+ def _settings_audit_many(backends, floor):
304
+ """Settings-row trails for many tables: one statement per tenant for real PostgreSQL rows."""
305
+ from core import view_settings_rows as settings
306
+ import core.store_pg as store_pg
307
+ out, by_slug = {}, {}
308
+ for key, rows in backends.items():
309
+ if type(rows) is settings.PgRows:
310
+ out[key] = []
311
+ by_slug.setdefault(rows.tenant_slug, {})[rows.name] = key
312
+ continue
313
+ limit = 200
314
+ while True:
315
+ found = rows.audit(since=floor, limit=limit)
316
+ if len(found) < limit:
317
+ break
318
+ limit *= 2
319
+ out[key] = list(found)
320
+ for slug, names in by_slug.items():
321
+ enlisted = getattr(store_pg, '_CALLER_TRANSACTION', None)
322
+ enlisted = enlisted is not None and enlisted.get() is not None
323
+ with store_pg._pool().connection() as con:
324
+ with con.transaction():
325
+ if not enlisted:
326
+ con.execute('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY')
327
+ settings._limits(con)
328
+ cursor = con.execute(settings._sql(
329
+ "SELECT workspace_key, value FROM {rows} WHERE workspace_key = ANY(%s::text[]) "
330
+ "AND kind = 'audit' AND (value ->> 'ts')::double precision > %s "
331
+ "ORDER BY (value ->> 'ts')::double precision DESC, seq DESC", slug),
332
+ (list(names), float(floor)))
333
+ while batch := cursor.fetchmany(500):
334
+ for name, value in batch:
335
+ out[names[name]].append(value)
336
+ return out
337
+
338
+
339
+ def rows_many(st, table_keys, *, since=None):
340
+ """Every table's trail, newest first and unlimited, in one read per home instead of per table.
341
+
342
+ Returns `{table_key: rows}`. A table whose home is `DOCUMENT` maps to `None`: its caller reads
343
+ the document itself, because the ring cap is a property of the whole document.
344
+ """
345
+ keys = list(dict.fromkeys(str(key) for key in table_keys))
346
+ floor = float(since or 0)
347
+ backends = _settings_many(st, keys)
348
+ out = _settings_audit_many(backends, floor)
349
+ rest = [key for key in keys if key not in backends]
350
+ if rest and home(st) == CONTROL_AUDIT:
351
+ out.update(_pg_rows_many(st, rest, since=floor))
352
+ else:
353
+ out.update({key: None for key in rest})
354
  return out
355
 
356
 
platform/harness/amazon_store.py CHANGED
@@ -485,6 +485,10 @@ def _scheduled_phase_due(table, state, now, earliest):
485
  interval = SCHEDULED_FLOOR_SECONDS // _client().CADENCE[table]["perDay"]
486
  phase = ((now.timestamp() - shift) // interval) * interval + shift
487
  stamp = _utc(state["updated_at"]).timestamp() if state and state.get("state") == "done" else None
 
 
 
 
488
  if (now.timestamp() - phase > SCHEDULE_PHASE_GRACE_SECONDS
489
  or (stamp is not None and stamp >= phase)):
490
  phase += interval
@@ -523,8 +527,10 @@ def sync_schedule(states, now=None):
523
  if due is None and state and state.get("state") == "done":
524
  vendor = _client().REPORT_TYPES[table].get("min_interval_s", 0)
525
  due = _utc(state["updated_at"]) + timedelta(seconds=max(vendor, seconds))
 
526
  schedule.append({"table": table, "lastSyncAt": state.get("updated_at") if state else None,
527
- "nextSyncAt": _iso(due or now), "perDay": _client().CADENCE[table]["perDay"]})
 
528
  return schedule
529
 
530
 
 
485
  interval = SCHEDULED_FLOOR_SECONDS // _client().CADENCE[table]["perDay"]
486
  phase = ((now.timestamp() - shift) // interval) * interval + shift
487
  stamp = _utc(state["updated_at"]).timestamp() if state and state.get("state") == "done" else None
488
+ # A done tick that missed its phase runs late inside the first half of the interval.
489
+ # The second half is left alone: a staging copy of a live tick stays off the live phase.
490
+ if stamp is not None and stamp < phase and earliest.timestamp() - phase < interval / 2:
491
+ return earliest
492
  if (now.timestamp() - phase > SCHEDULE_PHASE_GRACE_SECONDS
493
  or (stamp is not None and stamp >= phase)):
494
  phase += interval
 
527
  if due is None and state and state.get("state") == "done":
528
  vendor = _client().REPORT_TYPES[table].get("min_interval_s", 0)
529
  due = _utc(state["updated_at"]) + timedelta(seconds=max(vendor, seconds))
530
+ # A due time already past is due now: the schedule never shows a past next sync.
531
  schedule.append({"table": table, "lastSyncAt": state.get("updated_at") if state else None,
532
+ "nextSyncAt": _iso(due if due is not None and due > now else now),
533
+ "perDay": _client().CADENCE[table]["perDay"]})
534
  return schedule
535
 
536
 
web/public/AIOS_DEPLOY_RECEIPT CHANGED
@@ -1 +1 @@
1
- 5550654043b2d2a41f2c5c03e9b78548e6020acf9a6c9c5598356bd3ee5a0bce
 
1
+ c9539862cff476612ccc51b0e65a05673ca185a733668bfafb0a5edb2c49839a
web/src/apps/amazon-profit/ProjectsList.tsx CHANGED
@@ -20,7 +20,7 @@ import { ProjectResultPreview } from "./ProjectResults";
20
  import {
21
  GRAIN_LABEL, PROJECT_PRIORITIES, PROJECT_STATUSES, HealthChip, LoadingRows, Owner,
22
  PriorityGlyph, ProjectRequestError, StatusRing, call, formatDay, messageOf, text,
23
- type Project, type ProjectGrain, type ProjectList,
24
  } from "./ProjectsShared";
25
  import "../../styles/sdlc85/project-list.css";
26
 
@@ -30,13 +30,30 @@ const money = (value: number | null | undefined) => value == null ? "Unknown" :
30
  value.toLocaleString("en-US", { style: "currency", currency: "USD" });
31
  const units = (value: number | null | undefined) => value == null ? "Unknown" : value.toLocaleString("en-US");
32
 
 
 
 
 
 
 
 
 
 
 
33
  function ProjectFigures({ project, compact = false }: { project: Project; compact?: boolean }) {
34
- const { rollup, impact } = project;
35
- if (!rollup && !impact) return null;
 
 
 
 
 
36
  if (compact) return <div className="lp-proj-row-figures">
37
- <div title={rollup?.asOf}>
38
- <span>Sales {money(rollup?.netSales)}</span>
39
- <span>Profit {money(rollup?.netProfit)}</span><span>Units {units(rollup?.units)}</span>
 
 
40
  </div>
41
  {project.status === "Completed" && project.completedOn ? <div title="Compared with the same days one year earlier">
42
  <span>Impact since {formatDay(project.completedOn)}</span>
@@ -45,11 +62,11 @@ function ProjectFigures({ project, compact = false }: { project: Project; compac
45
  </div> : null}
46
  </div>;
47
  return <section className="lp-proj-section" aria-label="Project figures" style={{ fontVariantNumeric: "tabular-nums" }}>
48
- <h4 className="lp-proj-section-title" title={rollup?.asOf}>Totals</h4>
49
  <dl className="lp-proj-facts">
50
- <div><dt>Net sales</dt><dd>{money(rollup?.netSales)}</dd></div>
51
- <div><dt>Net profit</dt><dd>{money(rollup?.netProfit)}</dd></div>
52
- <div><dt>Units</dt><dd>{units(rollup?.units)}</dd></div>
53
  </dl>
54
  <h4 className="lp-proj-section-title">Impact{project.completedOn ? ` since ${formatDay(project.completedOn)}` : ""}</h4>
55
  <dl className="lp-proj-facts">
 
20
  import {
21
  GRAIN_LABEL, PROJECT_PRIORITIES, PROJECT_STATUSES, HealthChip, LoadingRows, Owner,
22
  PriorityGlyph, ProjectRequestError, StatusRing, call, formatDay, messageOf, text,
23
+ type Project, type ProjectGrain, type ProjectList, type ProjectListFigure, type ProjectListFigures,
24
  } from "./ProjectsShared";
25
  import "../../styles/sdlc85/project-list.css";
26
 
 
30
  value.toLocaleString("en-US", { style: "currency", currency: "USD" });
31
  const units = (value: number | null | undefined) => value == null ? "Unknown" : value.toLocaleString("en-US");
32
 
33
+ // Sales and Units come from the project Dashboard's tied default series, never the stored rollup cells.
34
+ function dashboardValue(figure: ProjectListFigure | undefined, format: (value: number) => string) {
35
+ return figure?.total == null ? figure?.reason ?? "Unknown" : format(figure.total);
36
+ }
37
+
38
+ function dashboardTitle(figures: ProjectListFigures | null | undefined, figure?: ProjectListFigure) {
39
+ const span = figures?.from && figures.to ? `${formatDay(figures.from)} to ${formatDay(figures.to)}` : "";
40
+ return [span, figure?.total != null ? figure.reason : null].filter(Boolean).join(". ") || undefined;
41
+ }
42
+
43
  function ProjectFigures({ project, compact = false }: { project: Project; compact?: boolean }) {
44
+ const { rollup, impact, figures } = project;
45
+ if (!rollup && !impact && !figures) return null;
46
+ const sales = figures?.sales;
47
+ const sold = figures?.units;
48
+ // One shared withhold reason prints once in place of both numbers.
49
+ const withheld = sales?.total == null && sold?.total == null && sales?.reason && sales.reason === sold?.reason
50
+ ? sales.reason : null;
51
  if (compact) return <div className="lp-proj-row-figures">
52
+ <div>
53
+ {withheld ? <span title={dashboardTitle(figures)}>{withheld}</span>
54
+ : <span title={dashboardTitle(figures, sales)}>Sales {dashboardValue(sales, value => money(value))}</span>}
55
+ <span title={rollup?.asOf}>Profit {money(rollup?.netProfit)}</span>
56
+ {withheld ? null : <span title={dashboardTitle(figures, sold)}>Units {dashboardValue(sold, value => units(value))}</span>}
57
  </div>
58
  {project.status === "Completed" && project.completedOn ? <div title="Compared with the same days one year earlier">
59
  <span>Impact since {formatDay(project.completedOn)}</span>
 
62
  </div> : null}
63
  </div>;
64
  return <section className="lp-proj-section" aria-label="Project figures" style={{ fontVariantNumeric: "tabular-nums" }}>
65
+ <h4 className="lp-proj-section-title" title={dashboardTitle(figures)}>Totals</h4>
66
  <dl className="lp-proj-facts">
67
+ <div><dt>Net sales</dt><dd title={dashboardTitle(figures, sales)}>{dashboardValue(sales, value => money(value))}</dd></div>
68
+ <div><dt>Net profit</dt><dd title={rollup?.asOf}>{money(rollup?.netProfit)}</dd></div>
69
+ <div><dt>Units</dt><dd title={dashboardTitle(figures, sold)}>{dashboardValue(sold, value => units(value))}</dd></div>
70
  </dl>
71
  <h4 className="lp-proj-section-title">Impact{project.completedOn ? ` since ${formatDay(project.completedOn)}` : ""}</h4>
72
  <dl className="lp-proj-facts">
web/src/apps/amazon-profit/ProjectsShared.tsx CHANGED
@@ -55,8 +55,13 @@ export interface Project {
55
  rollup?: { period: string; netSales: number | null; netProfit: number | null; units: number | null; asOf: string } | null;
56
  impact?: { netSales: number | null; units: number | null; priorNetSales: number | null;
57
  priorUnits: number | null; state: string | null } | null;
 
 
58
  }
59
 
 
 
 
60
  export interface ProjectList {
61
  grain?: ProjectGrain;
62
  key?: string;
 
55
  rollup?: { period: string; netSales: number | null; netProfit: number | null; units: number | null; asOf: string } | null;
56
  impact?: { netSales: number | null; units: number | null; priorNetSales: number | null;
57
  priorUnits: number | null; state: string | null } | null;
58
+ /** The project Dashboard's default Sales and Units. A null total carries its withhold reason. */
59
+ figures?: ProjectListFigures | null;
60
  }
61
 
62
+ export interface ProjectListFigure { total: number | null; reason: string | null }
63
+ export interface ProjectListFigures { from: string | null; to: string | null; sales: ProjectListFigure; units: ProjectListFigure }
64
+
65
  export interface ProjectList {
66
  grain?: ProjectGrain;
67
  key?: string;
web/src/connectors/ConnectorModal.tsx CHANGED
@@ -781,9 +781,11 @@ export function ConnectorOverviewPanel({
781
  const state = syncReceipt?.state === "queued" ? "queued"
782
  : syncReceipt?.state === "running" || syncBusy ? "running"
783
  : syncReceipt?.state === "failed" ? "failed" : health?.state;
784
- const failed = state === "failed" || state === "partial";
 
 
785
  const notOffered = health?.notOffered ?? 0;
786
- const status = failed ? "Sync failed" : state === "running" ? "Syncing"
787
  : state === "queued" ? "Queued"
788
  : state === "succeeded" && notOffered > 0
789
  ? `Synced with ${notOffered.toLocaleString()} ${notOffered === 1 ? "report" : "reports"} not offered`
@@ -811,7 +813,9 @@ export function ConnectorOverviewPanel({
811
  <span className="conn-settings-status" data-sync-state={state || overview.status}
812
  data-tone={failed ? "error" : state === "running" || state === "queued" ? "active" : "neutral"}
813
  role="status">{status}</span>
814
- {health?.warning ? <span className="conn-settings-warning" role="note">{health.warning}</span> : null}
 
 
815
  </div>
816
  </div> : null}
817
  </header>
 
781
  const state = syncReceipt?.state === "queued" ? "queued"
782
  : syncReceipt?.state === "running" || syncBusy ? "running"
783
  : syncReceipt?.state === "failed" ? "failed" : health?.state;
784
+ // A partial sync landed most tables. Only a failed one reads as failed, and it names its cause.
785
+ const failed = state === "failed";
786
+ const partial = state === "partial";
787
  const notOffered = health?.notOffered ?? 0;
788
+ const status = failed ? "Sync failed" : partial ? "Partly synced" : state === "running" ? "Syncing"
789
  : state === "queued" ? "Queued"
790
  : state === "succeeded" && notOffered > 0
791
  ? `Synced with ${notOffered.toLocaleString()} ${notOffered === 1 ? "report" : "reports"} not offered`
 
813
  <span className="conn-settings-status" data-sync-state={state || overview.status}
814
  data-tone={failed ? "error" : state === "running" || state === "queued" ? "active" : "neutral"}
815
  role="status">{status}</span>
816
+ {health?.warning ? <span className="conn-settings-warning" role="note">{health.warning}</span>
817
+ : (failed || partial) && health?.error ? <span className="conn-settings-warning" role="note">{health.error.message}</span>
818
+ : null}
819
  </div>
820
  </div> : null}
821
  </header>
web/src/connectors/ConnectorsPage.tsx CHANGED
@@ -339,7 +339,8 @@ export function AmazonSyncSchedule({ reading, problem = "", onRetry }: {
339
  <td className="conn-settings-database-success">{row.lastSyncAt
340
  ? <time dateTime={row.lastSyncAt}>{amazonSyncStamp(row.lastSyncAt, reading.timezone)}</time> : "Not recorded"}</td>
341
  <td className="conn-settings-database-success">
342
- <time dateTime={row.nextSyncAt}>{amazonSyncStamp(row.nextSyncAt, reading.timezone)}</time>
 
343
  {row.state === "throttled" ? <p role="status">Rate limited, retry scheduled</p>
344
  : ["failed", "refused"].includes(row.state) ? <p role="status">Sync needs attention</p> : null}
345
  </td>
 
339
  <td className="conn-settings-database-success">{row.lastSyncAt
340
  ? <time dateTime={row.lastSyncAt}>{amazonSyncStamp(row.lastSyncAt, reading.timezone)}</time> : "Not recorded"}</td>
341
  <td className="conn-settings-database-success">
342
+ {Date.parse(row.nextSyncAt) <= Date.now() + 60000 ? "Due now"
343
+ : <time dateTime={row.nextSyncAt}>{amazonSyncStamp(row.nextSyncAt, reading.timezone)}</time>}
344
  {row.state === "throttled" ? <p role="status">Rate limited, retry scheduled</p>
345
  : ["failed", "refused"].includes(row.state) ? <p role="status">Sync needs attention</p> : null}
346
  </td>
web/src/connectors/OdooConfig.tsx CHANGED
@@ -993,7 +993,9 @@ export function syncBudgetWords(status: SyncBudget | null | undefined): string {
993
  const budget = finite(status?.budgetMinutes) ? status.budgetMinutes
994
  : finite(status?.pass?.budgetSeconds) ? status.pass.budgetSeconds / 60 : null;
995
  if (budget === null || budget <= 0) return "";
996
- return duration === null ? `${budget} min budget` : `${duration} min of ${budget} min budget`;
 
 
997
  }
998
 
999
  export function shortSyncCause(value: unknown, fallback = "Sync could not run."): string {
 
993
  const budget = finite(status?.budgetMinutes) ? status.budgetMinutes
994
  : finite(status?.pass?.budgetSeconds) ? status.pass.budgetSeconds / 60 : null;
995
  if (budget === null || budget <= 0) return "";
996
+ // A local copy of ConnectorsPage.tsx::wholeMinutes: that file imports this one.
997
+ const whole = (minutes: number) => minutes > 0 && minutes < 1 ? "under 1" : String(Math.round(minutes));
998
+ return duration === null ? `${whole(budget)} min budget` : `${whole(duration)} min of ${whole(budget)} min budget`;
999
  }
1000
 
1001
  export function shortSyncCause(value: unknown, fallback = "Sync could not run."): string {
web/src/settings/UsagePane.tsx CHANGED
@@ -1,4 +1,4 @@
1
- import { useCallback, useEffect, useId, useRef, useState } from "react";
2
  import type { CSSProperties } from "react";
3
  import { Funnel, X } from "@phosphor-icons/react";
4
  import { createPortal } from "react-dom";
@@ -180,11 +180,16 @@ const activityColors: Record<UsageKind, string> = {
180
  view_edit: "var(--lp-pink-deep)", ai_turn: "var(--lp-red-deep)",
181
  };
182
 
 
 
 
183
  function DailyActivityChart({ report, kinds }: { report: UsageActivity; kinds: UsageKind[] }) {
184
  const [hiddenKinds, setHiddenKinds] = useState<UsageKind[]>([]);
185
  const [focusedDay, setFocusedDay] = useState(0);
186
  const [hoveredDay, setHoveredDay] = useState<number | null>(null);
187
  const chartRef = useRef<SVGSVGElement>(null);
 
 
188
  const titleId = useId();
189
  const descriptionId = useId();
190
  const known = (value: number | null | undefined) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
@@ -206,7 +211,19 @@ function DailyActivityChart({ report, kinds }: { report: UsageActivity; kinds: U
206
  const step = Math.max(1, Math.ceil(maximum / 4));
207
  const ceiling = step * 4;
208
  const left = Math.max(48, count(ceiling).length * 8 + 12);
209
- const width = Math.max(600, left + days.length * 20 + 16);
 
 
 
 
 
 
 
 
 
 
 
 
210
  const top = 32;
211
  const plotHeight = 176;
212
  const bottom = top + plotHeight;
@@ -242,7 +259,7 @@ function DailyActivityChart({ report, kinds }: { report: UsageActivity; kinds: U
242
  <p className="set-help">{report.from} to {report.to} ({report.timezone}){retained ? " · Retained counts" : ""}</p>
243
  {!enabled.length ? <p className="set-help" role="status">{readable.length ? "Select a metric" : "Daily counts unavailable"}</p>
244
  : !days.length ? <p className="set-help" role="status">Daily counts unavailable</p> : <>
245
- <div className="set-usage-chart-scroll" role="region" aria-label="Daily columns" tabIndex={0}>
246
  <svg ref={chartRef} className="set-usage-chart-plot" width={width} height={248} viewBox={`0 0 ${width} 248`}
247
  role="group" aria-labelledby={titleId} aria-describedby={descriptionId}>
248
  <desc id={descriptionId}>Stacked daily event counts for the enabled metrics. Use the arrow keys to browse days, or open Daily values.
 
1
+ import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState } from "react";
2
  import type { CSSProperties } from "react";
3
  import { Funnel, X } from "@phosphor-icons/react";
4
  import { createPortal } from "react-dom";
 
180
  view_edit: "var(--lp-pink-deep)", ai_turn: "var(--lp-red-deep)",
181
  };
182
 
183
+ /** The narrowest readable day column, in px, before the Daily activity chart scrolls. */
184
+ const MIN_DAY_WIDTH = 12;
185
+
186
  function DailyActivityChart({ report, kinds }: { report: UsageActivity; kinds: UsageKind[] }) {
187
  const [hiddenKinds, setHiddenKinds] = useState<UsageKind[]>([]);
188
  const [focusedDay, setFocusedDay] = useState(0);
189
  const [hoveredDay, setHoveredDay] = useState<number | null>(null);
190
  const chartRef = useRef<SVGSVGElement>(null);
191
+ const scrollRef = useRef<HTMLDivElement>(null);
192
+ const [boxWidth, setBoxWidth] = useState(0);
193
  const titleId = useId();
194
  const descriptionId = useId();
195
  const known = (value: number | null | undefined) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
 
211
  const step = Math.max(1, Math.ceil(maximum / 4));
212
  const ceiling = step * 4;
213
  const left = Math.max(48, count(ceiling).length * 8 + 12);
214
+ const plotted = enabled.length > 0 && days.length > 0;
215
+ // The plot fills its scroll box. It scrolls only when a day would fall under the readable minimum.
216
+ useLayoutEffect(() => {
217
+ const box = scrollRef.current;
218
+ if (!box) return;
219
+ const measure = () => setBoxWidth(Math.floor(box.getBoundingClientRect().width));
220
+ measure();
221
+ if (typeof ResizeObserver === "undefined") return;
222
+ const observer = new ResizeObserver(measure);
223
+ observer.observe(box);
224
+ return () => observer.disconnect();
225
+ }, [plotted]);
226
+ const width = Math.max(left + days.length * MIN_DAY_WIDTH + 16, boxWidth || 600);
227
  const top = 32;
228
  const plotHeight = 176;
229
  const bottom = top + plotHeight;
 
259
  <p className="set-help">{report.from} to {report.to} ({report.timezone}){retained ? " · Retained counts" : ""}</p>
260
  {!enabled.length ? <p className="set-help" role="status">{readable.length ? "Select a metric" : "Daily counts unavailable"}</p>
261
  : !days.length ? <p className="set-help" role="status">Daily counts unavailable</p> : <>
262
+ <div ref={scrollRef} className="set-usage-chart-scroll" role="region" aria-label="Daily columns" tabIndex={0}>
263
  <svg ref={chartRef} className="set-usage-chart-plot" width={width} height={248} viewBox={`0 0 ${width} 248`}
264
  role="group" aria-labelledby={titleId} aria-describedby={descriptionId}>
265
  <desc id={descriptionId}>Stacked daily event counts for the enabled metrics. Use the arrow keys to browse days, or open Daily values.