fsanyoto commited on
Commit
62c5213
·
verified ·
1 Parent(s): 89d8428

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "current": "eda4a2ee5cf5 (eda4a2ee5cf5)",
3
  "releases": [
4
  {
5
  "version": "v86",
 
1
  {
2
+ "current": "a9bce8ca6c17 (a9bce8ca6c17)",
3
  "releases": [
4
  {
5
  "version": "v86",
VERSION CHANGED
@@ -1 +1 @@
1
- eda4a2ee5cf5 (eda4a2ee5cf5)
 
1
+ a9bce8ca6c17 (a9bce8ca6c17)
api/main.py CHANGED
@@ -945,6 +945,8 @@ def _migrate_env_odoo(why):
945
  try:
946
  import routes_keychain as _kc_routes
947
  from harness import runtime as _runtime
 
 
948
  rep = _kc_routes.migrate_env_odoo(_runtime.get_runtime("royal-imports"))
949
  if rep.get("done"):
950
  print(f"[aios-api] odoo credential migrated onto the keychain ({why}): "
@@ -974,7 +976,10 @@ def _pull_meta(why, tenant_key=None):
974
  from harness import meta_store as _meta, runtime, mirror_store
975
  outcomes = {}
976
  try:
977
- tenants = [tenant_key] if tenant_key else runtime.known_tenants()
 
 
 
978
  for key in tenants:
979
  outcomes[key] = False
980
  try:
@@ -1062,9 +1067,10 @@ def _pull_amazon(why, vendor=True):
1062
  from harness import amazon_store as _amazon
1063
  from harness import runtime as _runtime
1064
  import routes_odoo_tables as _rot
1065
- # The existing boot/resync projection targets tenant #0. Keep credential, mirror and
1066
- # projection on that same tenant; never fall back to an operator's environment credential.
1067
- tenant_key = "royal-imports"
 
1068
  rt = _runtime.get_runtime(tenant_key)
1069
  from harness import datastore as _ds
1070
  if (rt.key != tenant_key or
@@ -1074,7 +1080,7 @@ def _pull_amazon(why, vendor=True):
1074
  _drain_amazon_connection_revocations(rt)
1075
  if not _amazon.credential(tenant_key, rt=rt):
1076
  print(f"[aios-api] amazon sync skipped ({why}): no stored amazon_sp credential "
1077
- "for royal-imports; the connector is idle, not broken")
1078
  return False
1079
  # Hotfix 2026-09-24: an unfinished first load goes through the Sync now desk, whose
1080
  # bounded passes requeue themselves until every table is loaded. `scheduled=True` loaded
@@ -1405,7 +1411,7 @@ def _sync_now_detail(provider, tenant, *, ok, detail="", cause=None):
1405
  return sentence + suffix
1406
 
1407
 
1408
- def _run_sync_requests(outcome=None, *, during_odoo=False):
1409
  """Drain Sync now intents on the resident resync thread, the mirror's single writer.
1410
 
1411
  D-29 / intake F6: HTTP handlers only queue intents. Provider calls stay here, before the
@@ -1487,9 +1493,12 @@ def _run_sync_requests(outcome=None, *, during_odoo=False):
1487
  return log, lines
1488
 
1489
  odoo_requested = False
 
 
1490
  # Claim only work this turn executes. A later provider remains queued with an honest wait.
1491
  pending = connector_sync.take_sync_requests(limit=1, exclude_providers=("odoo",) if during_odoo else (),
1492
- refresh_remote=True)
 
1493
  while True:
1494
  receipt = next((row for row in pending
1495
  if not during_odoo or row["provider"] != "odoo"), None)
@@ -2384,7 +2393,8 @@ def _resync_tenant():
2384
  return key, "runtime"
2385
  except Exception: # noqa: BLE001
2386
  pass
2387
- return "royal-imports", "fallback-literal"
 
2388
 
2389
 
2390
  def _resolve_resync_cadence():
@@ -2998,6 +3008,14 @@ def _store_resync_loop():
2998
  # H73: a tenant with a daily wall-clock slot reads Odoo only when that slot is due.
2999
  # Looked up by name so loop fixtures that list main.py defs by hand keep running slotless.
3000
  _slot = (globals().get("_resolve_resync_slot") or (lambda: None))()
 
 
 
 
 
 
 
 
3001
  _woken = False
3002
  if passes and _slot is None:
3003
  # The wait is what remains of the cadence since the last scheduled pass STARTED, so
@@ -3058,7 +3076,7 @@ def _store_resync_loop():
3058
  if _woken and (_t.time() - last_full_pass_at < _every if _slot is None else not _slot_due):
3059
  _desk = {}
3060
  _desk_started = _t.time()
3061
- if not _run_sync_requests(_desk):
3062
  _project_desk(_desk, _cad["tenant"])
3063
  if "continuing" in _desk.values():
3064
  # A floor between continuations, so a chunk that returns at once cannot spin.
@@ -3074,7 +3092,7 @@ def _store_resync_loop():
3074
  if _slot is not None and not _slot_due and _odoo_requested is None and not _continuation:
3075
  # H73: outside the slot no Odoo call is made. Serve the stored mirror, drain the desk.
3076
  _desk = {}
3077
- if _run_sync_requests(_desk):
3078
  _odoo_requested = True
3079
  else:
3080
  _project_desk(_desk, _cad["tenant"])
@@ -3098,7 +3116,7 @@ def _store_resync_loop():
3098
  last_slot_pass_at = last_full_pass_at
3099
  _slot_write(last_full_pass_at)
3100
  if _odoo_requested is None:
3101
- _odoo_requested = _run_sync_requests()
3102
  _warm_generation = _sheet_warm_generation()
3103
  _backfill_before = _backfill_read(_cad["tenant"]) if _backfill_read else None
3104
  try:
@@ -3106,6 +3124,8 @@ def _store_resync_loop():
3106
  sync_report, delete_report, _err = _resync_mirror_pass(_manual, passes, selected_entities)
3107
  except Exception as exc:
3108
  sync_report, delete_report, _err = None, None, _classify_resync_error(exc)
 
 
3109
  if _err is None and sync_report:
3110
  RESYNC_STATE["passes"] = RESYNC_STATE.get("passes", 0) + 1
3111
  _held_check = globals().get("_resync_publication_held")
@@ -3315,7 +3335,7 @@ def _store_resync_loop():
3315
  # whether this cadence may skip both the full-document write and relation pass.
3316
  try:
3317
  from harness import runtime as _runtime
3318
- _rt_resync = _runtime.get_runtime("royal-imports")
3319
  _meta_state = _rebuild_meta_relational("resync", _rt_resync, _meta_previous)
3320
  # A zero Odoo report says nothing about Amazon either. Same reasoning, same pass,
3321
  # and it inherits the tenant binding the line above just established.
 
945
  try:
946
  import routes_keychain as _kc_routes
947
  from harness import runtime as _runtime
948
+ if _runtime.worker_tenant():
949
+ return # Env credentials are Royal's; a tenant worker never holds them.
950
  rep = _kc_routes.migrate_env_odoo(_runtime.get_runtime("royal-imports"))
951
  if rep.get("done"):
952
  print(f"[aios-api] odoo credential migrated onto the keychain ({why}): "
 
976
  from harness import meta_store as _meta, runtime, mirror_store
977
  outcomes = {}
978
  try:
979
+ import process_role as _meta_role
980
+ # Each tenant is pulled by exactly one worker: its own, else the primary.
981
+ tenants = [tenant_key] if tenant_key else [
982
+ key for key in runtime.known_tenants() if _meta_role.syncs_here(key)]
983
  for key in tenants:
984
  outcomes[key] = False
985
  try:
 
1067
  from harness import amazon_store as _amazon
1068
  from harness import runtime as _runtime
1069
  import routes_odoo_tables as _rot
1070
+ import process_role as _amazon_role
1071
+ # The worker's own tenant: credential, mirror and projection stay on it, never on the
1072
+ # operator's environment credential.
1073
+ tenant_key = _amazon_role.writer_tenant()
1074
  rt = _runtime.get_runtime(tenant_key)
1075
  from harness import datastore as _ds
1076
  if (rt.key != tenant_key or
 
1080
  _drain_amazon_connection_revocations(rt)
1081
  if not _amazon.credential(tenant_key, rt=rt):
1082
  print(f"[aios-api] amazon sync skipped ({why}): no stored amazon_sp credential "
1083
+ f"for {tenant_key}; the connector is idle, not broken")
1084
  return False
1085
  # Hotfix 2026-09-24: an unfinished first load goes through the Sync now desk, whose
1086
  # bounded passes requeue themselves until every table is loaded. `scheduled=True` loaded
 
1411
  return sentence + suffix
1412
 
1413
 
1414
+ def _run_sync_requests(outcome=None, *, during_odoo=False, hold_first_load=None):
1415
  """Drain Sync now intents on the resident resync thread, the mirror's single writer.
1416
 
1417
  D-29 / intake F6: HTTP handlers only queue intents. Provider calls stay here, before the
 
1493
  return log, lines
1494
 
1495
  odoo_requested = False
1496
+ # A first-load continuation never runs inside an Odoo pass: it requeues itself without end.
1497
+ hold = during_odoo if hold_first_load is None else hold_first_load
1498
  # Claim only work this turn executes. A later provider remains queued with an honest wait.
1499
  pending = connector_sync.take_sync_requests(limit=1, exclude_providers=("odoo",) if during_odoo else (),
1500
+ refresh_remote=True,
1501
+ exclude_requested_by=("first load",) if hold else ())
1502
  while True:
1503
  receipt = next((row for row in pending
1504
  if not during_odoo or row["provider"] != "odoo"), None)
 
2393
  return key, "runtime"
2394
  except Exception: # noqa: BLE001
2395
  pass
2396
+ import process_role as _resync_role
2397
+ return _resync_role.writer_tenant(), "fallback-literal"
2398
 
2399
 
2400
  def _resolve_resync_cadence():
 
3008
  # H73: a tenant with a daily wall-clock slot reads Odoo only when that slot is due.
3009
  # Looked up by name so loop fixtures that list main.py defs by hand keep running slotless.
3010
  _slot = (globals().get("_resolve_resync_slot") or (lambda: None))()
3011
+
3012
+ def _near_slot():
3013
+ # A first-load continuation does not start this close to the next Odoo slot.
3014
+ if _slot is None:
3015
+ return False
3016
+ import odoo_relational as _rel_near
3017
+ return _rel_near.slot_near(_t.time(), _slot)
3018
+
3019
  _woken = False
3020
  if passes and _slot is None:
3021
  # The wait is what remains of the cadence since the last scheduled pass STARTED, so
 
3076
  if _woken and (_t.time() - last_full_pass_at < _every if _slot is None else not _slot_due):
3077
  _desk = {}
3078
  _desk_started = _t.time()
3079
+ if not _run_sync_requests(_desk, hold_first_load=_near_slot()):
3080
  _project_desk(_desk, _cad["tenant"])
3081
  if "continuing" in _desk.values():
3082
  # A floor between continuations, so a chunk that returns at once cannot spin.
 
3092
  if _slot is not None and not _slot_due and _odoo_requested is None and not _continuation:
3093
  # H73: outside the slot no Odoo call is made. Serve the stored mirror, drain the desk.
3094
  _desk = {}
3095
+ if _run_sync_requests(_desk, hold_first_load=_near_slot()):
3096
  _odoo_requested = True
3097
  else:
3098
  _project_desk(_desk, _cad["tenant"])
 
3116
  last_slot_pass_at = last_full_pass_at
3117
  _slot_write(last_full_pass_at)
3118
  if _odoo_requested is None:
3119
+ _odoo_requested = _run_sync_requests(hold_first_load=True)
3120
  _warm_generation = _sheet_warm_generation()
3121
  _backfill_before = _backfill_read(_cad["tenant"]) if _backfill_read else None
3122
  try:
 
3124
  sync_report, delete_report, _err = _resync_mirror_pass(_manual, passes, selected_entities)
3125
  except Exception as exc:
3126
  sync_report, delete_report, _err = None, None, _classify_resync_error(exc)
3127
+ # The Odoo pull is over: the continuations it held run on the next loop turn.
3128
+ connector_sync.resume_held_requests()
3129
  if _err is None and sync_report:
3130
  RESYNC_STATE["passes"] = RESYNC_STATE.get("passes", 0) + 1
3131
  _held_check = globals().get("_resync_publication_held")
 
3335
  # whether this cadence may skip both the full-document write and relation pass.
3336
  try:
3337
  from harness import runtime as _runtime
3338
+ _rt_resync = _runtime.get_runtime(_cad["tenant"])
3339
  _meta_state = _rebuild_meta_relational("resync", _rt_resync, _meta_previous)
3340
  # A zero Odoo report says nothing about Amazon either. Same reasoning, same pass,
3341
  # and it inherits the tenant binding the line above just established.
api/odoo_relational.py CHANGED
@@ -5608,6 +5608,18 @@ def slot_after(now, slot):
5608
  raise ValueError("no slot occurrence found")
5609
 
5610
 
 
 
 
 
 
 
 
 
 
 
 
 
5611
  def slot_due(now, slot, last_pass_at):
5612
  """True when no pass has started since the latest slot occurrence."""
5613
  return last_pass_at is None or float(last_pass_at) < slot_before(now, slot)
@@ -5918,6 +5930,18 @@ def sync_freshness(rt, now=None):
5918
  if allowed is not None and not cfg["frozen"]:
5919
  good_at = _parse_iso(last_good)
5920
  stale = good_at is None or (now - good_at).total_seconds() > allowed
 
 
 
 
 
 
 
 
 
 
 
 
5921
  failure = None
5922
  errors = status.get("errors") if isinstance(status.get("errors"), list) else []
5923
  if phase == "error" and errors:
@@ -5937,6 +5961,7 @@ def sync_freshness(rt, now=None):
5937
  for name in ("key", "label", "code", "message", "stage", "at")
5938
  + (("cause",) if item.get("cause") else ())})
5939
  return {"stale": bool(stale), "lastGoodSyncAt": last_good,
 
5940
  "failedDatabases": failed_databases,
5941
  "schedule": cfg["syncEvery"], "staleAfterSeconds": allowed,
5942
  "lastRunAt": status.get("lastRun") or None, "phase": phase,
 
5608
  raise ValueError("no slot occurrence found")
5609
 
5610
 
5611
+ #: A first-load continuation does not start this close to the next slot, so it cannot delay the slot.
5612
+ FIRST_LOAD_SLOT_QUIET_SECONDS = 2 * 3600
5613
+
5614
+ #: A slot whose pass has not ended good this long after it is LATE, and the watchdog alerts.
5615
+ SLOT_LATE_SECONDS = 90 * 60
5616
+
5617
+
5618
+ def slot_near(now, slot, seconds=FIRST_LOAD_SLOT_QUIET_SECONDS):
5619
+ """True when the next slot occurrence is at most `seconds` after epoch `now`."""
5620
+ return slot is not None and slot_after(now, slot) - float(now) <= seconds
5621
+
5622
+
5623
  def slot_due(now, slot, last_pass_at):
5624
  """True when no pass has started since the latest slot occurrence."""
5625
  return last_pass_at is None or float(last_pass_at) < slot_before(now, slot)
 
5930
  if allowed is not None and not cfg["frozen"]:
5931
  good_at = _parse_iso(last_good)
5932
  stale = good_at is None or (now - good_at).total_seconds() > allowed
5933
+ # A daily slot that passed SLOT_LATE_SECONDS ago with no good sync since is late, not fresh.
5934
+ late_slot = None
5935
+ slot = sync_slot(cfg)
5936
+ if slot is not None and not cfg["frozen"] and not stale:
5937
+ try:
5938
+ due = slot_before(now.timestamp(), slot)
5939
+ except Exception: # noqa: BLE001
5940
+ due = None
5941
+ good_at = _parse_iso(last_good)
5942
+ if (due is not None and now.timestamp() - due > SLOT_LATE_SECONDS
5943
+ and (good_at is None or good_at.timestamp() < due)):
5944
+ late_slot = slot_iso(due)
5945
  failure = None
5946
  errors = status.get("errors") if isinstance(status.get("errors"), list) else []
5947
  if phase == "error" and errors:
 
5961
  for name in ("key", "label", "code", "message", "stage", "at")
5962
  + (("cause",) if item.get("cause") else ())})
5963
  return {"stale": bool(stale), "lastGoodSyncAt": last_good,
5964
+ "late": late_slot is not None, "lateSlotAt": late_slot,
5965
  "failedDatabases": failed_databases,
5966
  "schedule": cfg["syncEvery"], "staleAfterSeconds": allowed,
5967
  "lastRunAt": status.get("lastRun") or None, "phase": phase,
api/process_role.py CHANGED
@@ -10,6 +10,11 @@ lease, so a second Space's worker waits instead of becoming a second writer.
10
 
11
  Several uvicorn workers (AIOS_UVICORN_WORKERS > 1): one web worker holds the primary lock and
12
  supervises the sync worker and installs hand-offs. The others only read the mirror read-only.
 
 
 
 
 
13
  """
14
  from __future__ import annotations
15
 
@@ -32,6 +37,11 @@ API_DIR = Path(__file__).resolve().parent
32
  POLL_SECONDS = 15
33
  HEARTBEAT_SECONDS = 30
34
  HEARTBEAT_FILE = "worker.heartbeat.json"
 
 
 
 
 
35
  READY_FILE = "READY.json"
36
  PRIMARY_LOCK = "web-primary.lock"
37
  PRIMARY_FILE = "web-primary.json"
@@ -83,10 +93,88 @@ def allows(kind, role_name=None):
83
 
84
  def admit(name, kind, role_name=None):
85
  """allows(), plus one refusal line. For call sites whose callee owns its thread."""
86
- if allows(kind, role_name):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  return True
88
- print(f"[process-role] refused {name} ({kind}) in role {role_name or ROLE}", flush=True)
89
- return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
 
92
  class _Refused:
@@ -615,6 +703,8 @@ def poll_worker_desk():
615
  """Worker side: pick up event receipts and Sync now hand-offs from the store desk."""
616
  from core import connector_sync
617
  for slug, rt in _tenants():
 
 
618
  try:
619
  connector_sync.restore_sync_requests(rt)
620
  admitted = connector_sync.poll_remote_requests(rt)
@@ -646,7 +736,13 @@ def _apply_worker_state():
646
  from core import connector_sync
647
  from harness import mirror_store
648
  beat = _read_json(handoff_dir() / HEARTBEAT_FILE) or {}
649
- catch_up = beat.get("catchUp") if isinstance(beat.get("catchUp"), dict) else {}
 
 
 
 
 
 
650
  resync = beat.get("resync")
651
  app_main = _running_main()
652
  if isinstance(resync, dict) and app_main is not None:
@@ -687,8 +783,8 @@ def write_heartbeat(now=None):
687
  catch_up = {}
688
  app_main = _running_main()
689
  resync = dict(getattr(app_main, "RESYNC_STATE", None) or {})
690
- _write_json(handoff_dir() / HEARTBEAT_FILE,
691
- {"pid": os.getpid(), "at": time.time() if now is None else now,
692
  "catchUp": catch_up, "resync": resync, "bootRestore": dict(_BOOT_RESTORE)})
693
 
694
 
@@ -717,10 +813,13 @@ def start_worker_services():
717
  start("sync-desk-poll", "heavy", _worker_desk_loop)
718
 
719
 
720
- def _worker_env():
721
  env = dict(os.environ)
722
  env.update(AIOS_PROCESS_ROLE="worker", AIOS_PARENT_PID=str(os.getpid()),
723
  AIOS_MIRROR_HANDOFF_DIR=str(handoff_dir()), PYTHONUNBUFFERED="1")
 
 
 
724
  for name in ("AIOS_DUCKDB_MEMORY", "AIOS_DUCKDB_THREADS"):
725
  env.pop(name, None) # the worker sets its own caps
726
  # The worker writes its own file read-write and is never a web worker.
@@ -728,45 +827,109 @@ def _worker_env():
728
  return env
729
 
730
 
731
- def _supervise():
 
 
 
732
  backoff = 5.0
733
  while not _STOP.is_set():
734
  started = time.time()
735
  try:
736
- proc = subprocess.Popen([sys.executable, "sync_worker.py"], cwd=str(API_DIR), env=_worker_env())
 
737
  except OSError as exc:
738
- print(f"[process-role] sync worker could not start ({type(exc).__name__}: {exc})", flush=True)
739
  proc = None
740
  if proc is not None:
741
- _WORKER.update(proc=proc, pid=proc.pid, startedAt=started)
742
- print(f"[process-role] sync worker started pid={proc.pid}", flush=True)
743
- write_primary_state()
 
744
  code = proc.wait()
745
- _WORKER["lastExit"] = code
746
  else:
747
  code = None
748
  if _STOP.is_set():
749
  return
750
  if time.time() - started > 600:
751
  backoff = 5.0
752
- _WORKER["restarts"] += 1
753
- print(f"[process-role] sync worker exited code={code}; restart {_WORKER['restarts']} "
754
  f"in {int(backoff)}s", flush=True)
755
  if _STOP.wait(backoff):
756
  return
757
  backoff = min(backoff * 2, 300.0)
758
 
759
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
760
  def stop_worker():
761
- """Stop the supervised worker by its own pid."""
762
  _STOP.set()
763
- proc = _WORKER.get("proc")
764
- if proc is not None and proc.poll() is None:
765
- proc.terminate()
766
- try:
767
- proc.wait(10)
768
- except subprocess.TimeoutExpired:
769
- proc.kill()
 
770
 
771
 
772
  def start_web_services():
@@ -786,6 +949,7 @@ def start_web_services():
786
  f"the primary supervises the sync worker", flush=True)
787
  return False
788
  _WORKER["supervisor"] = start("sync-worker-supervisor", "light", _supervise)
 
789
  start("mirror-handoff-watcher", "light", _web_watch_loop)
790
  atexit.register(stop_worker)
791
  return True
@@ -805,7 +969,14 @@ def status():
805
  age = None
806
  if isinstance(beat, dict) and beat.get("pid") == pid and beat.get("at"):
807
  age = round(max(0.0, time.time() - float(beat["at"])), 1)
 
 
 
 
 
808
  return {"role": ROLE, "roleSource": ROLE_SOURCE, "webWorkers": web_workers(), "primary": is_primary(),
 
 
809
  "worker": {"pid": pid, "alive": alive, "heartbeatAgeS": age,
810
  "restarts": _WORKER["restarts"], "lastInstall": dict(LAST_INSTALL) or None,
811
  "lastInstallError": dict(LAST_INSTALL_ERROR) or None},
 
10
 
11
  Several uvicorn workers (AIOS_UVICORN_WORKERS > 1): one web worker holds the primary lock and
12
  supervises the sync worker and installs hand-offs. The others only read the mirror read-only.
13
+
14
+ One sync worker per tenant: the primary worker serves AIOS_SYNC_WRITER_TENANT (royal-imports when
15
+ unset) and runs every job that loops all tenants. Each other tenant that holds a sync connector
16
+ gets a tenant worker (AIOS_WORKER_SCOPE=tenant) with its own DuckDB file and lease, which runs only
17
+ that tenant's sync jobs. AIOS_SYNC_WORKERS_MAX caps the total; a tenant past the cap is reported.
18
  """
19
  from __future__ import annotations
20
 
 
37
  POLL_SECONDS = 15
38
  HEARTBEAT_SECONDS = 30
39
  HEARTBEAT_FILE = "worker.heartbeat.json"
40
+ FLEET_FILE = "sync-fleet.json"
41
+ FLEET_SCAN_SECONDS = 60
42
+ #: The heavy jobs a tenant worker runs. Every other heavy job loops all tenants, so only the primary runs it.
43
+ TENANT_WORKER_JOBS = frozenset({"store-resync", "sync-desk-poll", "connector-materialization",
44
+ "amazon-first-load-floor"})
45
  READY_FILE = "READY.json"
46
  PRIMARY_LOCK = "web-primary.lock"
47
  PRIMARY_FILE = "web-primary.json"
 
93
 
94
  def admit(name, kind, role_name=None):
95
  """allows(), plus one refusal line. For call sites whose callee owns its thread."""
96
+ if not allows(kind, role_name):
97
+ print(f"[process-role] refused {name} ({kind}) in role {role_name or ROLE}", flush=True)
98
+ return False
99
+ if (kind == "heavy" and (role_name or ROLE) == "worker" and worker_scope() == "tenant"
100
+ and name not in TENANT_WORKER_JOBS):
101
+ print(f"[process-role] refused {name} ({kind}) in the {writer_tenant()} tenant worker: "
102
+ f"the primary worker runs it", flush=True)
103
+ return False
104
+ return True
105
+
106
+
107
+ # ----------------------------------------------------------------------------- one worker per tenant
108
+ def writer_tenant(env=None):
109
+ """The tenant this worker syncs: AIOS_SYNC_WRITER_TENANT, else royal-imports."""
110
+ env = os.environ if env is None else env
111
+ return str(env.get("AIOS_SYNC_WRITER_TENANT") or "royal-imports").strip().lower()
112
+
113
+
114
+ def worker_scope(env=None):
115
+ """`tenant` in a tenant worker, else `primary`."""
116
+ env = os.environ if env is None else env
117
+ return "tenant" if env.get("AIOS_WORKER_SCOPE") == "tenant" else "primary"
118
+
119
+
120
+ def heartbeat_name(env=None):
121
+ """The primary keeps HEARTBEAT_FILE, so web readiness reads it unchanged. A tenant worker has its own."""
122
+ if worker_scope(env) != "tenant":
123
+ return HEARTBEAT_FILE
124
+ stem = "".join(c if (c.isalnum() or c in "-_") else "_" for c in writer_tenant(env))[:60]
125
+ return f"worker.{stem}.heartbeat.json"
126
+
127
+
128
+ def fleet_tenants(root=None):
129
+ """Tenants with their own tenant worker, from the web supervisor's fleet file."""
130
+ state = _read_json(Path(root or handoff_dir()) / FLEET_FILE)
131
+ tenants = state.get("tenants") if isinstance(state, dict) else None
132
+ return {str(slug) for slug in tenants} if isinstance(tenants, dict) else set()
133
+
134
+
135
+ def syncs_here(slug, root=None):
136
+ """Whether this process runs sync work for `slug`. Exactly one worker answers True per tenant."""
137
+ slug = str(slug or "").strip().lower()
138
+ if ROLE != "worker":
139
  return True
140
+ if worker_scope() == "tenant":
141
+ return slug == writer_tenant()
142
+ return slug == writer_tenant() or slug not in fleet_tenants(root)
143
+
144
+
145
+ def sync_worker_cap(env=None):
146
+ """AIOS_SYNC_WORKERS_MAX: sync worker processes per container, the primary included. Default 4."""
147
+ env = os.environ if env is None else env
148
+ try:
149
+ return max(1, int(env.get("AIOS_SYNC_WORKERS_MAX") or 4))
150
+ except ValueError:
151
+ return 4
152
+
153
+
154
+ def sync_connector_types():
155
+ """Keychain entry types that need a sync worker: every registered sync provider and declared mirror."""
156
+ from core import connector_spec, connector_sync
157
+ return set(connector_sync.providers()) | set(connector_spec.MIRRORS)
158
+
159
+
160
+ def fleet_wanted():
161
+ """Live tenants other than the primary's that hold a sync connector, sorted."""
162
+ import tenant_scan
163
+ from core import keychain
164
+ from harness import runtime
165
+ types, primary, out = sync_connector_types(), writer_tenant(), []
166
+ for slug, rt in tenant_scan.live_tenants(runtime):
167
+ if slug == primary:
168
+ continue
169
+ try:
170
+ kinds = {str(row.get("type") or "") for row in keychain.list_entries(rt)}
171
+ except Exception as exc: # noqa: BLE001
172
+ print(f"[process-role] connectors of {slug} unreadable ({type(exc).__name__}); "
173
+ f"its sync stays with the primary worker", flush=True)
174
+ continue
175
+ if kinds & types:
176
+ out.append(slug)
177
+ return sorted(out)
178
 
179
 
180
  class _Refused:
 
703
  """Worker side: pick up event receipts and Sync now hand-offs from the store desk."""
704
  from core import connector_sync
705
  for slug, rt in _tenants():
706
+ if not syncs_here(slug):
707
+ continue
708
  try:
709
  connector_sync.restore_sync_requests(rt)
710
  admitted = connector_sync.poll_remote_requests(rt)
 
736
  from core import connector_sync
737
  from harness import mirror_store
738
  beat = _read_json(handoff_dir() / HEARTBEAT_FILE) or {}
739
+ catch_up = dict(beat.get("catchUp")) if isinstance(beat.get("catchUp"), dict) else {}
740
+ for slug in list(_FLEET):
741
+ tenant_beat = _read_json(handoff_dir() / heartbeat_name(
742
+ {"AIOS_WORKER_SCOPE": "tenant", "AIOS_SYNC_WRITER_TENANT": slug})) or {}
743
+ if isinstance(tenant_beat.get("catchUp"), dict) and slug in tenant_beat["catchUp"]:
744
+ # A tenant worker's own catch-up wins for its tenant.
745
+ catch_up[slug] = tenant_beat["catchUp"][slug]
746
  resync = beat.get("resync")
747
  app_main = _running_main()
748
  if isinstance(resync, dict) and app_main is not None:
 
783
  catch_up = {}
784
  app_main = _running_main()
785
  resync = dict(getattr(app_main, "RESYNC_STATE", None) or {})
786
+ _write_json(handoff_dir() / heartbeat_name(),
787
+ {"pid": os.getpid(), "tenant": writer_tenant(), "scope": worker_scope(), "at": time.time() if now is None else now,
788
  "catchUp": catch_up, "resync": resync, "bootRestore": dict(_BOOT_RESTORE)})
789
 
790
 
 
813
  start("sync-desk-poll", "heavy", _worker_desk_loop)
814
 
815
 
816
+ def _worker_env(tenant=None):
817
  env = dict(os.environ)
818
  env.update(AIOS_PROCESS_ROLE="worker", AIOS_PARENT_PID=str(os.getpid()),
819
  AIOS_MIRROR_HANDOFF_DIR=str(handoff_dir()), PYTHONUNBUFFERED="1")
820
+ env.pop("AIOS_WORKER_SCOPE", None)
821
+ if tenant:
822
+ env.update(AIOS_WORKER_SCOPE="tenant", AIOS_SYNC_WRITER_TENANT=tenant)
823
  for name in ("AIOS_DUCKDB_MEMORY", "AIOS_DUCKDB_THREADS"):
824
  env.pop(name, None) # the worker sets its own caps
825
  # The worker writes its own file read-write and is never a web worker.
 
827
  return env
828
 
829
 
830
+ def _supervise(tenant=None):
831
+ """Keep one sync worker running: the primary when `tenant` is None, else that tenant's."""
832
+ record = _WORKER if tenant is None else _FLEET[tenant]
833
+ label = "sync worker" if tenant is None else f"sync worker for {tenant}"
834
  backoff = 5.0
835
  while not _STOP.is_set():
836
  started = time.time()
837
  try:
838
+ proc = subprocess.Popen([sys.executable, "sync_worker.py"], cwd=str(API_DIR),
839
+ env=_worker_env(tenant))
840
  except OSError as exc:
841
+ print(f"[process-role] {label} could not start ({type(exc).__name__}: {exc})", flush=True)
842
  proc = None
843
  if proc is not None:
844
+ record.update(proc=proc, pid=proc.pid, startedAt=started)
845
+ print(f"[process-role] {label} started pid={proc.pid}", flush=True)
846
+ if tenant is None:
847
+ write_primary_state()
848
  code = proc.wait()
849
+ record["lastExit"] = code
850
  else:
851
  code = None
852
  if _STOP.is_set():
853
  return
854
  if time.time() - started > 600:
855
  backoff = 5.0
856
+ record["restarts"] += 1
857
+ print(f"[process-role] {label} exited code={code}; restart {record['restarts']} "
858
  f"in {int(backoff)}s", flush=True)
859
  if _STOP.wait(backoff):
860
  return
861
  backoff = min(backoff * 2, 300.0)
862
 
863
 
864
+ _FLEET = {}
865
+ _FLEET_STATE = {"overCap": [], "error": None, "at": None}
866
+
867
+
868
+ def _write_fleet(root=None):
869
+ _write_json(Path(root or handoff_dir()) / FLEET_FILE, {
870
+ "at": time.time(), "primary": writer_tenant(),
871
+ "tenants": {slug: {"pid": row.get("pid")} for slug, row in _FLEET.items()},
872
+ "overCap": list(_FLEET_STATE["overCap"])})
873
+
874
+
875
+ def _report_over_cap(over, cap):
876
+ """Rule 1: a tenant past the cap is told, with the cause and the fix, never skipped in silence."""
877
+ cause = (f"its daily Odoo and Amazon sync cannot run: this container allows {cap} sync worker(s) "
878
+ f"(AIOS_SYNC_WORKERS_MAX) and they are all in use. Raise AIOS_SYNC_WORKERS_MAX or move "
879
+ f"to a larger box.")
880
+ for slug in over:
881
+ print(f"[process-role] sync worker for {slug} NOT started: {cause}", flush=True)
882
+ try:
883
+ import sync_alerts
884
+ from harness import runtime
885
+ sync_alerts.notify(slug, "sync-worker", [{"key": "worker", "label": "Sync worker",
886
+ "code": "over_cap", "cause": cause}],
887
+ store=runtime.get_runtime(slug))
888
+ except Exception as exc: # noqa: BLE001
889
+ print(f"[process-role] over-cap alert for {slug} failed ({type(exc).__name__})", flush=True)
890
+
891
+
892
+ def fleet_tick(wanted=None, *, starter=None, root=None):
893
+ """Start a tenant worker for each wanted tenant inside the cap; report the rest. Returns the started slugs."""
894
+ wanted = fleet_wanted() if wanted is None else list(wanted)
895
+ cap = sync_worker_cap()
896
+ new = [slug for slug in wanted if slug not in _FLEET]
897
+ room = max(0, cap - 1 - len(_FLEET))
898
+ starting, over = new[:room], new[room:]
899
+ for slug in starting:
900
+ _FLEET[slug] = {"proc": None, "pid": None, "restarts": 0, "startedAt": None, "lastExit": None}
901
+ _FLEET_STATE.update(overCap=over, at=time.time(), error=None)
902
+ # The fleet file names a tenant before its worker starts, so the primary stops serving it first.
903
+ _write_fleet(root)
904
+ for slug in starting:
905
+ (starter or (lambda s: start(f"sync-worker-supervisor-{s}", "light", _supervise, args=(s,))))(slug)
906
+ if over:
907
+ _report_over_cap(over, cap)
908
+ return starting
909
+
910
+
911
+ def _fleet_loop():
912
+ while not _STOP.is_set():
913
+ try:
914
+ fleet_tick()
915
+ except Exception as exc: # noqa: BLE001
916
+ _FLEET_STATE.update(error=type(exc).__name__, at=time.time())
917
+ print(f"[process-role] tenant worker scan failed ({type(exc).__name__}: {exc})", flush=True)
918
+ if _STOP.wait(FLEET_SCAN_SECONDS):
919
+ return
920
+
921
+
922
  def stop_worker():
923
+ """Stop every supervised worker by its own pid."""
924
  _STOP.set()
925
+ for record in [_WORKER, *_FLEET.values()]:
926
+ proc = record.get("proc")
927
+ if proc is not None and proc.poll() is None:
928
+ proc.terminate()
929
+ try:
930
+ proc.wait(10)
931
+ except subprocess.TimeoutExpired:
932
+ proc.kill()
933
 
934
 
935
  def start_web_services():
 
949
  f"the primary supervises the sync worker", flush=True)
950
  return False
951
  _WORKER["supervisor"] = start("sync-worker-supervisor", "light", _supervise)
952
+ start("sync-worker-fleet", "light", _fleet_loop)
953
  start("mirror-handoff-watcher", "light", _web_watch_loop)
954
  atexit.register(stop_worker)
955
  return True
 
969
  age = None
970
  if isinstance(beat, dict) and beat.get("pid") == pid and beat.get("at"):
971
  age = round(max(0.0, time.time() - float(beat["at"])), 1)
972
+ fleet = {}
973
+ for slug, row in _FLEET.items():
974
+ tproc = row.get("proc")
975
+ fleet[slug] = {"pid": row.get("pid"), "alive": tproc is not None and tproc.poll() is None,
976
+ "restarts": row.get("restarts", 0), "lastExit": row.get("lastExit")}
977
  return {"role": ROLE, "roleSource": ROLE_SOURCE, "webWorkers": web_workers(), "primary": is_primary(),
978
+ "tenant": writer_tenant(), "scope": worker_scope(), "tenantWorkers": fleet,
979
+ "tenantWorkersOverCap": list(_FLEET_STATE["overCap"]), "syncWorkersMax": sync_worker_cap(),
980
  "worker": {"pid": pid, "alive": alive, "heartbeatAgeS": age,
981
  "restarts": _WORKER["restarts"], "lastInstall": dict(LAST_INSTALL) or None,
982
  "lastInstallError": dict(LAST_INSTALL_ERROR) or None},
api/routes_connectors.py CHANGED
@@ -2676,6 +2676,9 @@ def _start_database_jobs():
2676
  tenant, type(exc).__name__)):
2677
  if _materialization_stop.is_set():
2678
  break
 
 
 
2679
  try:
2680
  _dispatch_database_jobs(rt)
2681
  except Exception as exc:
 
2676
  tenant, type(exc).__name__)):
2677
  if _materialization_stop.is_set():
2678
  break
2679
+ import process_role
2680
+ if not process_role.syncs_here(tenant):
2681
+ continue # That tenant's own worker runs its jobs.
2682
  try:
2683
  _dispatch_database_jobs(rt)
2684
  except Exception as exc:
api/sync_worker.py CHANGED
@@ -21,6 +21,14 @@ def configure(env=None):
21
  web_db = Path(env.get("AIOS_DUCKDB_PATH") or (web_store / "royal.duckdb"))
22
  worker_dir = Path(env.get("AIOS_WORKER_STORE_DIR") or (web_db.parent / "worker"))
23
  worker_db = worker_dir / web_db.name
 
 
 
 
 
 
 
 
24
  env["AIOS_DUCKDB_STORE_DIR"] = str(worker_dir)
25
  env["AIOS_DUCKDB_PATH"] = str(worker_db)
26
  # The launcher (request_class.py --env) sizes these to the box. Unset: the 2 vCPU values.
@@ -32,6 +40,24 @@ def configure(env=None):
32
  return worker_db
33
 
34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  def lower_priority(env=None):
36
  """Drop this process to a low CPU priority, so the web process wins every contested core."""
37
  env = os.environ if env is None else env
@@ -51,7 +77,8 @@ def main():
51
  for path in (str(_RI), str(API_DIR)):
52
  if path not in sys.path:
53
  sys.path.insert(0, path)
54
- print(f"[sync-worker] pid={os.getpid()} duckdb={worker_db} "
 
55
  f"memory_limit={os.environ['AIOS_DUCKDB_MEMORY']} threads={os.environ['AIOS_DUCKDB_THREADS']} "
56
  f"nice={niceness}",
57
  flush=True)
@@ -59,6 +86,7 @@ def main():
59
  "they stay out of this worker too", flush=True)
60
  from dotenv import load_dotenv
61
  load_dotenv(_RI / ".env")
 
62
  import process_role
63
  process_role.start_worker_services()
64
  # Importing the app starts every role-allowed thread at module level. Startup hooks need a call.
 
21
  web_db = Path(env.get("AIOS_DUCKDB_PATH") or (web_store / "royal.duckdb"))
22
  worker_dir = Path(env.get("AIOS_WORKER_STORE_DIR") or (web_db.parent / "worker"))
23
  worker_db = worker_dir / web_db.name
24
+ tenant = str(env.get("AIOS_SYNC_WRITER_TENANT") or "").strip().lower()
25
+ if env.get("AIOS_WORKER_SCOPE") == "tenant":
26
+ if not tenant:
27
+ raise SystemExit("[sync-worker] a tenant worker needs AIOS_SYNC_WRITER_TENANT")
28
+ # One directory and one file per tenant, named as datastore.path_for names it.
29
+ safe = tenant_file_stem(tenant)
30
+ worker_dir = worker_dir / safe
31
+ worker_db = worker_dir / f"{safe}.duckdb"
32
  env["AIOS_DUCKDB_STORE_DIR"] = str(worker_dir)
33
  env["AIOS_DUCKDB_PATH"] = str(worker_db)
34
  # The launcher (request_class.py --env) sizes these to the box. Unset: the 2 vCPU values.
 
40
  return worker_db
41
 
42
 
43
+ def tenant_file_stem(tenant):
44
+ """The file stem `datastore.path_for` gives a tenant other than royal-imports."""
45
+ return "".join(c if (c.isalnum() or c in "-_") else "_" for c in tenant)[:60]
46
+
47
+
48
+ def check_tenant_file(env=None):
49
+ """A tenant worker exits unless its open file is the one its tenant's runtime expects."""
50
+ env = os.environ if env is None else env
51
+ tenant = str(env.get("AIOS_SYNC_WRITER_TENANT") or "").strip().lower()
52
+ if env.get("AIOS_WORKER_SCOPE") != "tenant":
53
+ return True
54
+ from harness import datastore
55
+ want, have = datastore.path_for(tenant).resolve(), datastore.DB_PATH.resolve()
56
+ if want != have:
57
+ raise SystemExit(f"[sync-worker] {tenant} expects {want} but has {have} open")
58
+ return True
59
+
60
+
61
  def lower_priority(env=None):
62
  """Drop this process to a low CPU priority, so the web process wins every contested core."""
63
  env = os.environ if env is None else env
 
77
  for path in (str(_RI), str(API_DIR)):
78
  if path not in sys.path:
79
  sys.path.insert(0, path)
80
+ print(f"[sync-worker] pid={os.getpid()} tenant={os.environ.get('AIOS_SYNC_WRITER_TENANT') or 'royal-imports'} "
81
+ f"scope={os.environ.get('AIOS_WORKER_SCOPE') or 'primary'} duckdb={worker_db} "
82
  f"memory_limit={os.environ['AIOS_DUCKDB_MEMORY']} threads={os.environ['AIOS_DUCKDB_THREADS']} "
83
  f"nice={niceness}",
84
  flush=True)
 
86
  "they stay out of this worker too", flush=True)
87
  from dotenv import load_dotenv
88
  load_dotenv(_RI / ".env")
89
+ check_tenant_file()
90
  import process_role
91
  process_role.start_worker_services()
92
  # Importing the app starts every role-allowed thread at module level. Startup hooks need a call.
api/test_odoo_rank_refresh.py CHANGED
@@ -765,7 +765,7 @@ class RankRefreshTests(unittest.TestCase):
765
  return datetime.fromisoformat(text.replace('Z', '+00:00')).timestamp()
766
 
767
  def run_slot_loop(self, memory, *, boot, max_sleeps, tenant='royal-imports', config=None,
768
- reports=None, checkpoints=None):
769
  """Drive the real loop and its real slot resolver on a clock that advances at each wait."""
770
  import odoo_relational as rel
771
  source = ast.parse(Path(__file__).with_name('main.py').read_text(encoding='utf-8'))
@@ -828,7 +828,8 @@ class RankRefreshTests(unittest.TestCase):
828
  with patch.dict(sys.modules, {'time': clock, 'harness.runtime': runtime}), \
829
  patch.object(harness, 'runtime', runtime, create=True), \
830
  patch.object(connector_sync, 'sync_wake_event', return_value=wake), \
831
- patch.object(connector_sync, 'take_sync_requests', return_value=[]), \
 
832
  redirect_stdout(out):
833
  with self.assertRaisesRegex(StopIteration, 'bounded synthetic'):
834
  ns['_store_resync_loop']()
@@ -967,6 +968,69 @@ class RankRefreshTests(unittest.TestCase):
967
  tzinfo=timezone.utc))['nextSyncAt'],
968
  '2026-10-25T07:30:00Z')
969
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
970
 
971
  def test_h1_a_held_backfill_that_moved_queues_one_odoo_only_pass(self):
972
  """H1: a held backfill that moved runs again 60s later, Odoo only and unstamped; no progress stops"""
 
765
  return datetime.fromisoformat(text.replace('Z', '+00:00')).timestamp()
766
 
767
  def run_slot_loop(self, memory, *, boot, max_sleeps, tenant='royal-imports', config=None,
768
+ reports=None, checkpoints=None, take=None):
769
  """Drive the real loop and its real slot resolver on a clock that advances at each wait."""
770
  import odoo_relational as rel
771
  source = ast.parse(Path(__file__).with_name('main.py').read_text(encoding='utf-8'))
 
828
  with patch.dict(sys.modules, {'time': clock, 'harness.runtime': runtime}), \
829
  patch.object(harness, 'runtime', runtime, create=True), \
830
  patch.object(connector_sync, 'sync_wake_event', return_value=wake), \
831
+ patch.object(connector_sync, 'take_sync_requests',
832
+ **({'new': take} if take else {'return_value': []})), \
833
  redirect_stdout(out):
834
  with self.assertRaisesRegex(StopIteration, 'bounded synthetic'):
835
  ns['_store_resync_loop']()
 
968
  tzinfo=timezone.utc))['nextSyncAt'],
969
  '2026-10-25T07:30:00Z')
970
 
971
+ def test_first_load_never_runs_at_the_slot_claim_or_in_the_quiet_window(self):
972
+ """Live 10-29: an Amazon first-load chunk held the 06:00Z slot to 08:12Z. It is held near and at the slot"""
973
+ last = self.utc('2026-10-23T06:05:00Z')
974
+ held = []
975
+ take = lambda **kwargs: held.append(tuple(kwargs.get('exclude_requested_by') or ())) or []
976
+ _events, _sleeps, odoo = self.run_slot_loop(
977
+ {'passAt': last, 'fullRebuildAt': last, 'fingerprints': {'res_partner': (3, 7)}},
978
+ boot=self.utc('2026-10-24T04:30:00Z'), max_sleeps=2, take=take)
979
+ self.assertTrue(odoo, 'the slot pass ran')
980
+ # Boot 90 min before the slot: the drain outside the slot holds first load, and so does the claim.
981
+ self.assertTrue(len(held) >= 2 and all(h == ('first load',) for h in held), held)
982
+
983
+ def test_first_load_runs_far_from_the_slot(self):
984
+ """A first-load continuation keeps running when the next slot is more than two hours away"""
985
+ last = self.utc('2026-10-23T06:05:00Z')
986
+ held = []
987
+ take = lambda **kwargs: held.append(tuple(kwargs.get('exclude_requested_by') or ())) or []
988
+ self.run_slot_loop({'passAt': last, 'fullRebuildAt': last, 'fingerprints': {'res_partner': (3, 7)}},
989
+ boot=self.utc('2026-10-24T02:30:00Z'), max_sleeps=1, take=take)
990
+ self.assertEqual(held[0], ())
991
+
992
+ def test_slot_near_and_late(self):
993
+ """The quiet window is two hours before the slot; a slot with no good sync 90 min after it is late"""
994
+ from datetime import datetime, timezone
995
+ import odoo_relational as rel
996
+ slot = rel.sync_slot(rel.read_config(self.SlotStore('royal-imports')))
997
+ self.assertTrue(rel.slot_near(self.utc('2026-10-24T04:00:00Z'), slot))
998
+ self.assertFalse(rel.slot_near(self.utc('2026-10-24T03:59:00Z'), slot))
999
+ self.assertFalse(rel.slot_near(self.utc('2026-10-24T06:00:01Z'), slot))
1000
+ live = self.SlotStore('royal-imports', {rel.CONFIG_KEY: {'lastGoodSyncAt': '2026-10-28T19:44:42+00:00'}})
1001
+ at = lambda h, m: datetime(2026, 10, 29, h, m, tzinfo=timezone.utc)
1002
+ self.assertFalse(rel.sync_freshness(live, now=at(7, 29))['late'])
1003
+ late = rel.sync_freshness(live, now=at(7, 31))
1004
+ self.assertEqual((late['late'], late['lateSlotAt'], late['stale']), (True, '2026-10-29T06:00:00Z', False))
1005
+ done = self.SlotStore('royal-imports', {rel.CONFIG_KEY: {'lastGoodSyncAt': '2026-10-29T06:38:05+00:00'}})
1006
+ self.assertFalse(rel.sync_freshness(done, now=at(8, 30))['late'])
1007
+ frozen = self.SlotStore('royal-imports', {rel.CONFIG_KEY: {'lastGoodSyncAt': '2026-10-28T19:44:42+00:00',
1008
+ 'frozen': True}})
1009
+ self.assertFalse(rel.sync_freshness(frozen, now=at(8, 30))['late'])
1010
+
1011
+ def test_a_held_first_load_stays_queued_and_wakes_nobody(self):
1012
+ """The desk leaves a held first load queued, claims a click, and wakes the loop only on resume"""
1013
+ from core import connector_sync as desk
1014
+ saved = dict(desk._SYNC_REQUESTS)
1015
+ desk._SYNC_REQUESTS.clear()
1016
+ desk._SYNC_WAKE.clear()
1017
+ try:
1018
+ with patch.dict(desk._PROVIDERS, {'amazon_sp': desk._PROVIDERS.get('amazon_sp', {}),
1019
+ 'meta_ads': desk._PROVIDERS.get('meta_ads', {})}):
1020
+ desk.request_sync('amazon_sp', 't-hold', requested_by='first load', now=100)
1021
+ desk.request_sync('meta_ads', 't-hold', requested_by='admin', now=101)
1022
+ desk._SYNC_WAKE.clear()
1023
+ claimed = desk.take_sync_requests(now=200, exclude_requested_by=('first load',))
1024
+ self.assertEqual([r['provider'] for r in claimed], ['meta_ads'])
1025
+ self.assertEqual(desk.sync_request('amazon_sp', 't-hold')['state'], 'queued')
1026
+ self.assertFalse(desk.sync_wake_event().is_set())
1027
+ desk.resume_held_requests(now=300)
1028
+ self.assertTrue(desk.sync_wake_event().is_set())
1029
+ self.assertEqual([r['provider'] for r in desk.take_sync_requests(now=300)], ['amazon_sp'])
1030
+ finally:
1031
+ desk._SYNC_REQUESTS.clear()
1032
+ desk._SYNC_REQUESTS.update(saved)
1033
+ desk._SYNC_WAKE.clear()
1034
 
1035
  def test_h1_a_held_backfill_that_moved_queues_one_odoo_only_pass(self):
1036
  """H1: a held backfill that moved runs again 60s later, Odoo only and unstamped; no progress stops"""
platform/core/connector_sync.py CHANGED
@@ -79,13 +79,20 @@ def _cache_sync_requests(rt, document):
79
  _SYNC_REQUEST_RUNTIMES[rt.key] = rt
80
 
81
 
82
- def _wake_sync_requests(stamp):
83
  _arm_sync_wake(stamp)
84
  if any(row["state"] == "queued" and (row.get("notBefore") or 0) <= stamp
 
85
  for row in _SYNC_REQUESTS.values()):
86
  _SYNC_WAKE.set()
87
 
88
 
 
 
 
 
 
 
89
  def restore_sync_requests(rt, *, now=None, requeue=True):
90
  """Restore durable events and requeue claims abandoned by a previous process.
91
 
@@ -273,8 +280,12 @@ def sync_request(provider, tenant):
273
  return {**_request_wait(receipt), "accepted": False}
274
 
275
 
276
- def take_sync_requests(*, now=None, limit=None, exclude_providers=(), refresh_remote=False):
277
- """Claim manual work first, preserving provider floors, tenant claims and event siblings."""
 
 
 
 
278
  if refresh_remote:
279
  with _SYNC_REQUEST_LOCK:
280
  runtimes = list(_SYNC_REQUEST_RUNTIMES.values())
@@ -294,6 +305,7 @@ def take_sync_requests(*, now=None, limit=None, exclude_providers=(), refresh_re
294
  break
295
  pair = (receipt["provider"], receipt["tenant"])
296
  if (receipt["provider"] in exclude_providers or pair in busy or receipt["state"] != "queued"
 
297
  or max(receipt.get("notBefore") or 0, _SYNC_NOT_BEFORE.get(pair, 0)) > stamp):
298
  continue
299
  if receipt.get("tables") is not None:
@@ -325,7 +337,7 @@ def take_sync_requests(*, now=None, limit=None, exclude_providers=(), refresh_re
325
  receipt["detail"] = ""
326
  claimed.append(deepcopy(receipt))
327
  busy.add(pair)
328
- _wake_sync_requests(stamp)
329
  return claimed
330
 
331
 
 
79
  _SYNC_REQUEST_RUNTIMES[rt.key] = rt
80
 
81
 
82
+ def _wake_sync_requests(stamp, held=()):
83
  _arm_sync_wake(stamp)
84
  if any(row["state"] == "queued" and (row.get("notBefore") or 0) <= stamp
85
+ and row.get("requestedBy") not in held
86
  for row in _SYNC_REQUESTS.values()):
87
  _SYNC_WAKE.set()
88
 
89
 
90
+ def resume_held_requests(now=None):
91
+ """Wake the resident loop for queued work a hold left waiting."""
92
+ with _SYNC_REQUEST_LOCK:
93
+ _wake_sync_requests(time.time() if now is None else now)
94
+
95
+
96
  def restore_sync_requests(rt, *, now=None, requeue=True):
97
  """Restore durable events and requeue claims abandoned by a previous process.
98
 
 
280
  return {**_request_wait(receipt), "accepted": False}
281
 
282
 
283
+ def take_sync_requests(*, now=None, limit=None, exclude_providers=(), refresh_remote=False,
284
+ exclude_requested_by=()):
285
+ """Claim manual work first, preserving provider floors, tenant claims and event siblings.
286
+
287
+ `exclude_requested_by` leaves those receipts queued and does not wake the loop for them.
288
+ """
289
  if refresh_remote:
290
  with _SYNC_REQUEST_LOCK:
291
  runtimes = list(_SYNC_REQUEST_RUNTIMES.values())
 
305
  break
306
  pair = (receipt["provider"], receipt["tenant"])
307
  if (receipt["provider"] in exclude_providers or pair in busy or receipt["state"] != "queued"
308
+ or receipt.get("requestedBy") in exclude_requested_by
309
  or max(receipt.get("notBefore") or 0, _SYNC_NOT_BEFORE.get(pair, 0)) > stamp):
310
  continue
311
  if receipt.get("tables") is not None:
 
337
  receipt["detail"] = ""
338
  claimed.append(deepcopy(receipt))
339
  busy.add(pair)
340
+ _wake_sync_requests(stamp, exclude_requested_by)
341
  return claimed
342
 
343
 
platform/harness/runtime.py CHANGED
@@ -625,12 +625,24 @@ def register(key, builder):
625
  invalidate(key)
626
 
627
 
 
 
 
 
 
 
 
 
628
  def known_tenants():
629
  keys = set(_BUILDERS)
630
  try:
631
  keys |= set(_tenant_records())
632
  except Exception:
633
  pass
 
 
 
 
634
  return sorted(keys)
635
 
636
 
@@ -671,6 +683,10 @@ def get_runtime(tenant_key):
671
  key = str(tenant_key or "").strip().lower()
672
  if not key:
673
  raise KeyError("no tenant")
 
 
 
 
674
  with _LOCK:
675
  rt = _CACHE.get(key)
676
  if rt is not None:
 
625
  invalidate(key)
626
 
627
 
628
+ def worker_tenant():
629
+ """The one tenant a per-tenant sync worker serves, or "" in every other process."""
630
+ if (os.environ.get("AIOS_PROCESS_ROLE") != "worker"
631
+ or os.environ.get("AIOS_WORKER_SCOPE") != "tenant"):
632
+ return ""
633
+ return str(os.environ.get("AIOS_SYNC_WRITER_TENANT") or "").strip().lower()
634
+
635
+
636
  def known_tenants():
637
  keys = set(_BUILDERS)
638
  try:
639
  keys |= set(_tenant_records())
640
  except Exception:
641
  pass
642
+ # A per-tenant sync worker holds one tenant's file, so it never sees another tenant.
643
+ only = worker_tenant()
644
+ if only:
645
+ keys &= {only}
646
  return sorted(keys)
647
 
648
 
 
683
  key = str(tenant_key or "").strip().lower()
684
  if not key:
685
  raise KeyError("no tenant")
686
+ only = worker_tenant()
687
+ if only and key != only:
688
+ # Fail closed: this process's DuckDB file belongs to `only`.
689
+ raise KeyError(key)
690
  with _LOCK:
691
  rt = _CACHE.get(key)
692
  if rt is not None:
web/public/AIOS_DEPLOY_RECEIPT CHANGED
@@ -1 +1 @@
1
- f8fbaa9615aa924d504ee1421880fa42358ace44cae3257345d88081cc31bacb
 
1
+ 8d2caed2a3c46beee3efed555f9a1ccf41176fa7237d6f8ba8857b6821c15eda