fsanyoto commited on
Commit
500275b
·
verified ·
1 Parent(s): f53aaca

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "current": "eda4a2ee5cf5",
3
  "releases": [
4
  {
5
  "version": "v86",
 
1
  {
2
+ "current": "b7770dd4d587",
3
  "releases": [
4
  {
5
  "version": "v86",
VERSION CHANGED
@@ -1 +1 @@
1
- eda4a2ee5cf5
 
1
+ b7770dd4d587
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
@@ -2384,7 +2390,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():
@@ -3315,7 +3322,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
 
2390
  return key, "runtime"
2391
  except Exception: # noqa: BLE001
2392
  pass
2393
+ import process_role as _resync_role
2394
+ return _resync_role.writer_tenant(), "fallback-literal"
2395
 
2396
 
2397
  def _resolve_resync_cadence():
 
3322
  # whether this cadence may skip both the full-document write and relation pass.
3323
  try:
3324
  from harness import runtime as _runtime
3325
+ _rt_resync = _runtime.get_runtime(_cad["tenant"])
3326
  _meta_state = _rebuild_meta_relational("resync", _rt_resync, _meta_previous)
3327
  # A zero Odoo report says nothing about Amazon either. Same reasoning, same pass,
3328
  # and it inherits the tenant binding the line above just established.
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.
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
- cccb6e0c433b1fbc2156c5b383d50686505dc4a26cffbf786b35f8496ee68a74
 
1
+ 45c6e82285ea1f609ec00848a159373540039d93b30340c79ae8b05cb83de8e5