Spaces:
Running

fsanyoto commited on
Commit
44226ee
·
verified ·
1 Parent(s): fe984c1

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,4 +1,4 @@
1
  {
2
- "current": "a5862e8a70",
3
  "releases": []
4
  }
 
1
  {
2
+ "current": "3c03ce294a",
3
  "releases": []
4
  }
VERSION CHANGED
@@ -1 +1 @@
1
- a5862e8a70
 
1
+ 3c03ce294a
api/process_role.py CHANGED
@@ -1177,13 +1177,37 @@ def _heartbeat_loop(parent_pid):
1177
  return
1178
 
1179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1180
  def start_worker_services():
1181
  """Called by sync_worker.py: heartbeat, the stored publication record and the store desk poll."""
1182
  from harness import mirror_store
1183
  mirror_store.register_publish_listener(record_publication)
 
 
1184
  parent = int(os.environ.get("AIOS_PARENT_PID") or 0)
1185
  note_progress("boot")
1186
  start("sync-worker-heartbeat", "light", _heartbeat_loop, args=(parent,))
 
1187
  # Before the first heavy job: each one now waits until this worker holds the writer lease.
1188
  arm_writer_lease()
1189
  start("sync-desk-poll", "heavy", _worker_desk_loop)
 
1177
  return
1178
 
1179
 
1180
+ STALL_DUMP_SECONDS = float(os.environ.get("AIOS_SYNC_STALL_DUMP_SECONDS") or 1500)
1181
+
1182
+
1183
+ def _stall_dump_loop():
1184
+ """Print every thread's stack once per progress mark that goes silent, before the Space cancels the job."""
1185
+ import faulthandler
1186
+ dumped = None
1187
+ while not _STOP.wait(60):
1188
+ last = _progress_copy()
1189
+ if not last or last == dumped or time.time() - last["at"] < STALL_DUMP_SECONDS:
1190
+ continue
1191
+ dumped = last
1192
+ print(f"[sync-worker] no progress for {int(time.time() - last['at'])} s (last step {last['step']}); "
1193
+ "thread stacks follow", flush=True)
1194
+ try:
1195
+ faulthandler.dump_traceback(file=sys.stdout, all_threads=True)
1196
+ sys.stdout.flush()
1197
+ except Exception as exc: # noqa: BLE001
1198
+ print(f"[sync-worker] stack dump failed ({type(exc).__name__})", flush=True)
1199
+
1200
+
1201
  def start_worker_services():
1202
  """Called by sync_worker.py: heartbeat, the stored publication record and the store desk poll."""
1203
  from harness import mirror_store
1204
  mirror_store.register_publish_listener(record_publication)
1205
+ # A publication's tables and parts are progress: without this a long publish read as a hung job.
1206
+ mirror_store.register_progress_listener(note_progress)
1207
  parent = int(os.environ.get("AIOS_PARENT_PID") or 0)
1208
  note_progress("boot")
1209
  start("sync-worker-heartbeat", "light", _heartbeat_loop, args=(parent,))
1210
+ start("sync-worker-stall-dump", "light", _stall_dump_loop)
1211
  # Before the first heavy job: each one now waits until this worker holds the writer lease.
1212
  arm_writer_lease()
1213
  start("sync-desk-poll", "heavy", _worker_desk_loop)
platform/harness/amazon_store.py CHANGED
@@ -7368,7 +7368,7 @@ def _sync_event(kind, tenant, table, detail, rt, report, log):
7368
 
7369
  def _sync_failure_context(exc, table):
7370
  """Keep unreadable-value locations without exception values, source text or frame locals."""
7371
- if not isinstance(exc, (KeyError, ValueError)):
7372
  return None
7373
  frame = exc.__traceback__
7374
  while frame and frame.tb_next:
@@ -7410,6 +7410,9 @@ def _sync_problem(exc, table, operation, tenant, rt, report, log):
7410
  elif isinstance(exc, AmazonOperationRefused):
7411
  state = "refused"
7412
  fix = "use an operation in the approved read-only scope; check the connector operation mapping"
 
 
 
7413
  elif re.search(r"\b(?:HTTP(?: status)?|status(?: code)?|answered)\s*[:=]?\s*403\b|\(403\)", str(exc), re.I):
7414
  state = "refused"
7415
  cx = _client()
@@ -7978,17 +7981,24 @@ def normalise_app_dates(table, rows):
7978
  return rows.map(fixed) if isinstance(rows, _DocumentRows) else [fixed(row) for row in rows]
7979
 
7980
 
 
 
 
 
 
 
 
7981
  def _snapshot_identity(table, row):
7982
  """Mirror identity only; legacy grid IDs and AWD's replacement keys stay unchanged."""
7983
  sku = row.get("seller_sku") if table == "listings" else row.get("msku") or row.get("fnsku")
7984
  if not sku or not row.get("_snapshot_date"):
7985
- raise ValueError(f"Amazon {table} snapshot is missing identity date or SKU")
7986
- identity = (row["_snapshot_date"], sku)
7987
- if table == "inventory":
7988
- if not row.get("disposition") or not row.get("location"):
7989
- raise ValueError("Amazon inventory snapshot is missing identity disposition or location")
7990
- identity += (row["disposition"], row["location"])
7991
- return identity
7992
 
7993
 
7994
  def _replace_legacy_snapshot(con, table, columns, rows, meta, source_count, window=None):
@@ -8016,23 +8026,27 @@ def _replace_legacy_snapshot(con, table, columns, rows, meta, source_count, wind
8016
 
8017
  lazy = isinstance(rows, _DocumentRows)
8018
  rows = rows.map(stamped) if lazy else rows
8019
- counts, identities, total = {}, set(), 0
8020
  for row in rows:
8021
  period = (row if lazy else stamped(row))["_snapshot_date"]
8022
  identity = _snapshot_identity(table, row)
8023
- if identity in identities:
8024
- raise ValueError(f"Amazon {table} document has duplicate snapshot identities")
8025
  identities.add(identity)
8026
  counts[period] = counts.get(period, 0) + 1
8027
  total += 1
 
 
 
 
 
8028
  if total != source_count:
8029
- raise ValueError(f"Amazon {table} snapshot row count differs from its document")
8030
  if table == "inventory" and not total and window:
8031
  detail, units = _ledger_detail_rows(con, *window), _fba_summary_units(con)
8032
  if detail or units:
8033
  evidence = (f"the ledger detail holds {detail} rows for those days" if detail
8034
  else f"the FBA inventory summaries hold {units} units")
8035
- raise ValueError(
8036
  f"Amazon returned no FBA ledger summary rows for {window[0]} to {window[1]} while "
8037
  f"{evidence}, so the last inventory rows are kept. "
8038
  "Retry Amazon sync after Amazon finishes those days")
@@ -12033,6 +12047,60 @@ def ledger_window_selftest(log=print, check=None):
12033
  ck("a truly empty seller still lands its empty proof",
12034
  con.execute("SELECT COUNT(*) FROM amzn_inventory").fetchone()[0] == 0
12035
  and marker["count"] == 0 and marker["dates"] == {"2026-11-25": 0})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12036
  finally:
12037
  con.close()
12038
  return len(failures)
@@ -12179,9 +12247,10 @@ def snapshot_selftest(log=print, check=None):
12179
  "09/24/2026\tB\tFB\tAB\tSELLABLE\tUS\t3\n")
12180
  sync(rt.key, tables=[table], rt=rt, log=lambda *_a: None)
12181
  date = "2026-09-26" if table == "listings" else "2026-09-24"
12182
- sku = "seller_sku" if table == "listings" else "msku"
 
12183
  try:
12184
- con.execute(f"UPDATE {mirror} SET {sku}='A' WHERE _snapshot_date=?", [date])
12185
  ck(table + " validation refuses duplicate identity at unchanged row count", lambda:
12186
  valid()["state"] == "refused")
12187
  con.execute(f"DELETE FROM {mirror} WHERE _snapshot_date=? AND _report_row_number=2", [date])
 
7368
 
7369
  def _sync_failure_context(exc, table):
7370
  """Keep unreadable-value locations without exception values, source text or frame locals."""
7371
+ if not isinstance(exc, (KeyError, ValueError)) or isinstance(exc, AmazonSnapshotRefused):
7372
  return None
7373
  frame = exc.__traceback__
7374
  while frame and frame.tb_next:
 
7410
  elif isinstance(exc, AmazonOperationRefused):
7411
  state = "refused"
7412
  fix = "use an operation in the approved read-only scope; check the connector operation mapping"
7413
+ elif isinstance(exc, AmazonSnapshotRefused):
7414
+ state = "refused"
7415
+ fix = "the next Amazon sync reads a new document and checks it again"
7416
  elif re.search(r"\b(?:HTTP(?: status)?|status(?: code)?|answered)\s*[:=]?\s*403\b|\(403\)", str(exc), re.I):
7417
  state = "refused"
7418
  cx = _client()
 
7981
  return rows.map(fixed) if isinstance(rows, _DocumentRows) else [fixed(row) for row in rows]
7982
 
7983
 
7984
+ class AmazonSnapshotRefused(ValueError):
7985
+ """A snapshot refusal this module raises on purpose. Its text names no source value and reaches the card."""
7986
+
7987
+
7988
+ _INVENTORY_IDENTITY = ("_snapshot_date", "msku", "fnsku", "asin", "disposition", "location")
7989
+
7990
+
7991
  def _snapshot_identity(table, row):
7992
  """Mirror identity only; legacy grid IDs and AWD's replacement keys stay unchanged."""
7993
  sku = row.get("seller_sku") if table == "listings" else row.get("msku") or row.get("fnsku")
7994
  if not sku or not row.get("_snapshot_date"):
7995
+ raise AmazonSnapshotRefused(f"Amazon {table} snapshot is missing identity date or SKU")
7996
+ if table != "inventory":
7997
+ return (row["_snapshot_date"], sku)
7998
+ if not row.get("disposition") or not row.get("location"):
7999
+ raise AmazonSnapshotRefused("Amazon inventory snapshot is missing identity disposition or location")
8000
+ # One MSKU can carry several FNSKUs and ASINs on one day: _HISTORY_KEYS already tells them apart.
8001
+ return tuple(row.get(key) or None for key in _INVENTORY_IDENTITY)
8002
 
8003
 
8004
  def _replace_legacy_snapshot(con, table, columns, rows, meta, source_count, window=None):
 
8026
 
8027
  lazy = isinstance(rows, _DocumentRows)
8028
  rows = rows.map(stamped) if lazy else rows
8029
+ counts, identities, total, repeated = {}, set(), 0, 0
8030
  for row in rows:
8031
  period = (row if lazy else stamped(row))["_snapshot_date"]
8032
  identity = _snapshot_identity(table, row)
8033
+ repeated += identity in identities
 
8034
  identities.add(identity)
8035
  counts[period] = counts.get(period, 0) + 1
8036
  total += 1
8037
+ if repeated:
8038
+ fields = ", ".join(_INVENTORY_IDENTITY if table == "inventory" else ("_snapshot_date", "sku"))
8039
+ raise AmazonSnapshotRefused(
8040
+ f"Amazon {table} document has {repeated} of {total} rows that repeat a snapshot identity "
8041
+ f"({fields}), so the last published rows are kept")
8042
  if total != source_count:
8043
+ raise AmazonSnapshotRefused(f"Amazon {table} snapshot row count differs from its document")
8044
  if table == "inventory" and not total and window:
8045
  detail, units = _ledger_detail_rows(con, *window), _fba_summary_units(con)
8046
  if detail or units:
8047
  evidence = (f"the ledger detail holds {detail} rows for those days" if detail
8048
  else f"the FBA inventory summaries hold {units} units")
8049
+ raise AmazonSnapshotRefused(
8050
  f"Amazon returned no FBA ledger summary rows for {window[0]} to {window[1]} while "
8051
  f"{evidence}, so the last inventory rows are kept. "
8052
  "Retry Amazon sync after Amazon finishes those days")
 
12047
  ck("a truly empty seller still lands its empty proof",
12048
  con.execute("SELECT COUNT(*) FROM amzn_inventory").fetchone()[0] == 0
12049
  and marker["count"] == 0 and marker["dates"] == {"2026-11-25": 0})
12050
+
12051
+ # The live document's shape: quoted cells, Amazon's own headers, and one MSKU on two FNSKUs and ASINs.
12052
+ real_header = "\t".join(f'"{name}"' for name in (
12053
+ "Date", "FNSKU", "ASIN", "MSKU", "Title", "Disposition", "Starting Warehouse Balance",
12054
+ "In Transit Between Warehouses", "Receipts", "Customer Shipments", "Customer Returns",
12055
+ "Vendor Returns", "Warehouse Transfer In/Out", "Found", "Lost", "Damaged", "Disposed",
12056
+ "Other Events", "Ending Warehouse Balance", "Unknown Events", "Location", "Store")) + "\n"
12057
+
12058
+ def real_row(day, fnsku, asin, msku, disposition="SELLABLE", end="4"):
12059
+ cells = (day, fnsku, asin, msku, "A title, with a comma", disposition, "5", "0", "0", "-1",
12060
+ "0", "0", "0", "0", "0", "0", "0", "0", end, "0", "US", "")
12061
+ return "\t".join(f'"{cell}"' for cell in cells) + "\n"
12062
+
12063
+ def landed_real(body, document):
12064
+ text = real_header + body
12065
+ columns, records = parse_flat_file(text, document_id=document,
12066
+ report_type="GET_LEDGER_SUMMARY_VIEW_DATA")
12067
+ meta = {"reportId": document, "processingStatus": "DONE", "reportDocumentId": document,
12068
+ "dataEndTime": "2026-11-28T23:59:59Z"}
12069
+ return _replace_legacy_snapshot(con, "inventory", columns, records, meta,
12070
+ document_row_count(text), window=("2026-11-26", "2026-11-28"))
12071
+
12072
+ body = "".join(real_row(day, f"F{i}", f"A{i}", f"M{i}") for day in ("11/26/2026", "11/27/2026")
12073
+ for i in range(3))
12074
+ body += "".join(real_row(day, "F9", "A9", "M1") for day in ("11/26/2026", "11/27/2026"))
12075
+ try:
12076
+ landed_real(body, "ledger-shared-msku")
12077
+ refused = ""
12078
+ except ValueError as exc:
12079
+ refused = f"{type(exc).__name__}: {exc}"
12080
+ kept = con.execute("SELECT msku, fnsku, asin FROM amzn_inventory WHERE inventory_source = 'FBA' "
12081
+ "AND CAST(_snapshot_date AS VARCHAR) = '2026-11-27' ORDER BY 1, 2").fetchall()
12082
+ marker = json.loads(_read_state(con, "amzn_reconcile_inventory")["detail"])
12083
+ ck("an MSKU on two FNSKUs and ASINs lands both rows (D-18058)", not refused
12084
+ and kept == [("M0", "F0", "A0"), ("M1", "F1", "A1"), ("M1", "F9", "A9"), ("M2", "F2", "A2")])
12085
+ ck("the kept day ties to the document's own count for that day",
12086
+ marker["count"] == 4 and marker["documentDates"] == {"2026-11-26": 4, "2026-11-27": 4}
12087
+ and con.execute("SELECT COUNT(*) FROM amzn_inventory").fetchone()[0] == 4)
12088
+ ck("the inventory history holds the shared MSKU's two rows",
12089
+ con.execute(f"SELECT COUNT(*) FROM {history_table('inventory')} WHERE msku = 'M1' "
12090
+ "AND valid_to IS NULL").fetchone()[0] == 2)
12091
+ try:
12092
+ landed_real(body + real_row("11/27/2026", "F9", "A9", "M1", end="7"), "ledger-true-repeat")
12093
+ repeat = None
12094
+ except ValueError as exc:
12095
+ repeat = exc
12096
+ problem = _sync_problem(repeat, "inventory", "report_document", "fixture", None,
12097
+ {"problems": []}, lambda *_: None) if repeat is not None else {}
12098
+ ck("a row repeating all six identity keys still refuses the document, keeping the last rows",
12099
+ isinstance(repeat, AmazonSnapshotRefused) and "1 of 9 rows" in str(repeat)
12100
+ and con.execute("SELECT COUNT(*) FROM amzn_inventory").fetchone()[0] == 4)
12101
+ ck("that refusal reaches the card in its own words, not as unreadable_value",
12102
+ "repeat a snapshot identity" in problem.get("diagnostic", "")
12103
+ and "unreadable_value" not in problem.get("diagnostic", "") and not problem.get("failure"))
12104
  finally:
12105
  con.close()
12106
  return len(failures)
 
12247
  "09/24/2026\tB\tFB\tAB\tSELLABLE\tUS\t3\n")
12248
  sync(rt.key, tables=[table], rt=rt, log=lambda *_a: None)
12249
  date = "2026-09-26" if table == "listings" else "2026-09-24"
12250
+ # The ledger identity holds fnsku and asin too: one MSKU on two FNSKUs is two rows (D-18058).
12251
+ repeat = "seller_sku='A'" if table == "listings" else "msku='A', fnsku='FA', asin='AA'"
12252
  try:
12253
+ con.execute(f"UPDATE {mirror} SET {repeat} WHERE _snapshot_date=?", [date])
12254
  ck(table + " validation refuses duplicate identity at unchanged row count", lambda:
12255
  valid()["state"] == "refused")
12256
  con.execute(f"DELETE FROM {mirror} WHERE _snapshot_date=? AND _report_row_number=2", [date])
platform/harness/mirror_store.py CHANGED
@@ -39,6 +39,8 @@ _PART_BLOB_RE = re.compile(r"([a-z][a-z0-9_]*)\.p([0-9a-z-]{1,48})\.([0-9a-f]{16
39
  _STATE_BLOB_RE = re.compile(r"sync_state(?:\.([0-9a-f]{16}))?(?:\.sealed-v1)?\.json")
40
  #: State over one part's byte limit is saved as consecutive row parts, as a table is.
41
  _STATE_PART_RE = re.compile(r"sync_state\.p([0-9]{1,6})\.([0-9a-f]{16})(?:\.sealed-v1)?\.json")
 
 
42
  _PART_COLUMNS = ("_period_start", "month", "_snapshot_date", "posted_date", "purchase_date",
43
  "shipment_date", "date", "snapshot_date", "last_updated_date", "settlement_start_date")
44
  ORPHAN_GRACE = timedelta(hours=24)
@@ -127,6 +129,24 @@ def register_publish_listener(fn):
127
  _PUBLISH_LISTENERS.append(fn)
128
 
129
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  def _web_waits_for_worker(connector):
131
  """True in the web process for every mirror but Odoo: those arrive only from the sync worker."""
132
  return os.environ.get("AIOS_PROCESS_ROLE") == "web" and connector != "odoo"
@@ -1042,6 +1062,7 @@ class MirrorStore:
1042
  with _restore_phase("table_install"):
1043
  con.execute(f"CREATE OR REPLACE TABLE {_quoted_identifier(name)} AS "
1044
  f"SELECT * FROM {_parquet_source(files)}")
 
1045
  with _restore_phase("state_install"):
1046
  old_rows = self._state_rows(con)
1047
  if old_rows:
@@ -1318,17 +1339,22 @@ class MirrorStore:
1318
  return 0
1319
 
1320
 
1321
- def _copy_part(self, con, name, where, path):
1322
- """Sort declared filter and sort keys first, then all remaining columns for stable bytes."""
 
 
 
1323
  columns = [row[0] for row in con.execute(
1324
  "SELECT column_name FROM information_schema.columns WHERE table_name = ? "
1325
  "AND table_schema = 'main' ORDER BY ordinal_position", [name]).fetchall()]
1326
  keys = connector_spec.mirror_table_keys(name) or {}
1327
  declared = (*keys.get("filter_keys", ()), *keys.get("sort_keys", ()))
1328
- ordered = list(dict.fromkeys(c for c in (*declared, *columns) if c in columns))
1329
- order = ", ".join(_quoted_identifier(c) for c in ordered)
1330
- con.execute(f"COPY (SELECT * FROM {_quoted_identifier(name)} AS t WHERE {where} ORDER BY {order}) "
 
1331
  "TO ? (FORMAT PARQUET, COMPRESSION ZSTD)", [str(path)])
 
1332
  return path.stat().st_size
1333
 
1334
 
@@ -1346,9 +1372,10 @@ class MirrorStore:
1346
  column = next((c for c in _PART_COLUMNS if c in cols), None)
1347
  if column:
1348
  expr = f"coalesce(substr(CAST(t.{_quoted_identifier(column)} AS VARCHAR), 1, 7), 'none')"
1349
- groups = [row[0] for row in con.execute(
1350
- f"SELECT DISTINCT {expr} AS g FROM {_quoted_identifier(name)} AS t ORDER BY g").fetchall()]
1351
- groups = groups or ["none"] # an emptied table is still one (empty) part
 
1352
  else:
1353
  total = max(1, con.execute(f"SELECT count(*) FROM {_quoted_identifier(name)}").fetchone()[0])
1354
  buckets = 2
@@ -1356,23 +1383,36 @@ class MirrorStore:
1356
  buckets *= 2
1357
  expr = f"CAST(hash(t) % {buckets} AS VARCHAR)"
1358
  groups = [str(b) for b in range(buckets)]
 
 
1359
  out = []
1360
  for group in groups:
1361
  slug = _part_slug(group)
1362
  path = tmp / f"{name}.p{slug}.parquet"
1363
- size = self._copy_part(con, name, f"{expr} = {_sql_literal(group)}", path)
1364
- if size <= self.part_max_bytes - len(be.HEADER) - 28:
 
 
 
 
 
 
1365
  out.append((slug, path, None))
1366
  continue
 
 
1367
  k = 2
 
 
1368
  while True:
1369
  files, fits = [], True
1370
  for j in range(k):
1371
  sub = tmp / f"{name}.p{slug}-s{j}.parquet"
1372
  files.append((f"{slug}-s{j}", sub))
1373
- if self._copy_part(con, name, f"{expr} = {_sql_literal(group)} AND hash(t) % {k} = {j}",
1374
- sub) > self.part_max_bytes - len(be.HEADER) - 28:
1375
  fits = False
 
1376
  if fits:
1377
  out.extend((s, f, None) for s, f in files)
1378
  break
@@ -1474,6 +1514,7 @@ class MirrorStore:
1474
  con.execute(f"COPY (SELECT * FROM {_quoted_identifier(name)}) TO ? "
1475
  "(FORMAT PARQUET, COMPRESSION ZSTD)", [str(path)])
1476
  size = path.stat().st_size
 
1477
  if size is None or size > part_limit:
1478
  return self._chunked_entry(con, name, Path(tmp), prior, named, sealed=sealed)
1479
  metadata = _blob_metadata(path.read_bytes())
@@ -1529,6 +1570,7 @@ class MirrorStore:
1529
  data = path.read_bytes()
1530
  self._upload(rt, key, data)
1531
  progress["uploaded"] += len(data)
 
1532
 
1533
 
1534
  def _publish_checkpoint(self, tenant_key, rt, con, cache, manifest, changed, pending, tmp, *,
@@ -1817,6 +1859,7 @@ def _export_tables(store, con, directory):
1817
  path = Path(directory) / (name + ".parquet")
1818
  con.execute(f"COPY {_quoted_identifier(name)} TO ? (FORMAT PARQUET, COMPRESSION ZSTD)", [str(path)])
1819
  paths[name] = [path]
 
1820
  return paths
1821
 
1822
 
@@ -1989,7 +2032,7 @@ def sync_mirror(connector, tenant_key, rt, *, report=None, log=print, before_pub
1989
  odoo = store.connector == "odoo"
1990
 
1991
  def note(message, started=None, names=None):
1992
- # Callers guard on odoo. A logging error never changes control flow.
1993
  try:
1994
  text = message
1995
  if names is not None:
@@ -2020,8 +2063,7 @@ def sync_mirror(connector, tenant_key, rt, *, report=None, log=print, before_pub
2020
  try:
2021
  opened = time.monotonic()
2022
  candidate, started = _open_candidate(store, tenant_key, rt, published)
2023
- if odoo:
2024
- note("candidate open", opened)
2025
  pending = {row[0] for row in candidate.execute("SELECT name FROM _candidate_pending").fetchall()}
2026
  requested = set(store.spec.tables if expected_tables is None else expected_tables)
2027
  if odoo and pending:
@@ -2129,13 +2171,11 @@ def sync_mirror(connector, tenant_key, rt, *, report=None, log=print, before_pub
2129
  with tempfile.TemporaryDirectory(prefix="mirror-publish-") as tmp:
2130
  exporting = time.monotonic()
2131
  paths = _export_tables(store, candidate, tmp)
2132
- if odoo:
2133
- note(f"export, {len(paths)} tables", exporting)
2134
  saving = time.monotonic()
2135
  manifest = store.persist_mirror(tenant_key, rt, candidate, store._tables(candidate),
2136
  report=result, log=log, _publication=metadata)
2137
- if odoo:
2138
- note("save" if manifest else "save failed", saving)
2139
  if not manifest:
2140
  problems = result["problems"] or ["The source snapshot is incomplete."]
2141
  if report is not None and "problems" in report:
@@ -2159,11 +2199,11 @@ def sync_mirror(connector, tenant_key, rt, *, report=None, log=print, before_pub
2159
  except BaseException:
2160
  store.cache.pop(store._mirror_cache_key(tenant_key, rt), None)
2161
  raise
2162
- if odoo:
2163
- note("install", installing)
2164
  for listener in list(_PUBLISH_LISTENERS):
2165
  try:
2166
  listener(store.connector, tenant_key, manifest, rows, paths)
 
2167
  except Exception as exc:
2168
  # The snapshot is saved and installed here. A failed hand-off only delays readers.
2169
  log(f"{store.label} mirror hand-off failed ({type(exc).__name__}: {exc})")
 
39
  _STATE_BLOB_RE = re.compile(r"sync_state(?:\.([0-9a-f]{16}))?(?:\.sealed-v1)?\.json")
40
  #: State over one part's byte limit is saved as consecutive row parts, as a table is.
41
  _STATE_PART_RE = re.compile(r"sync_state\.p([0-9]{1,6})\.([0-9a-f]{16})(?:\.sealed-v1)?\.json")
42
+ #: A part group above this many rows is never sorted whole: it is measured unsorted, then split.
43
+ _PART_SORT_ROWS = 1_000_000
44
  _PART_COLUMNS = ("_period_start", "month", "_snapshot_date", "posted_date", "purchase_date",
45
  "shipment_date", "date", "snapshot_date", "last_updated_date", "settlement_start_date")
46
  ORPHAN_GRACE = timedelta(hours=24)
 
129
  _PUBLISH_LISTENERS.append(fn)
130
 
131
 
132
+ _PROGRESS_LISTENERS = []
133
+
134
+
135
+ def register_progress_listener(fn):
136
+ """Call fn(step) after each table or part a publication writes, so a worker's liveness sees the work."""
137
+ if fn not in _PROGRESS_LISTENERS:
138
+ _PROGRESS_LISTENERS.append(fn)
139
+
140
+
141
+ def _note_progress(step):
142
+ # A listener error never changes control flow.
143
+ for listener in list(_PROGRESS_LISTENERS):
144
+ try:
145
+ listener(step)
146
+ except Exception:
147
+ pass
148
+
149
+
150
  def _web_waits_for_worker(connector):
151
  """True in the web process for every mirror but Odoo: those arrive only from the sync worker."""
152
  return os.environ.get("AIOS_PROCESS_ROLE") == "web" and connector != "odoo"
 
1062
  with _restore_phase("table_install"):
1063
  con.execute(f"CREATE OR REPLACE TABLE {_quoted_identifier(name)} AS "
1064
  f"SELECT * FROM {_parquet_source(files)}")
1065
+ _note_progress(f"{self.connector} mirror install {name}")
1066
  with _restore_phase("state_install"):
1067
  old_rows = self._state_rows(con)
1068
  if old_rows:
 
1339
  return 0
1340
 
1341
 
1342
+ def _copy_part(self, con, name, where, path, *, ordered=True):
1343
+ """Sort declared filter and sort keys first, then all remaining columns for stable bytes.
1344
+
1345
+ `ordered=False` streams the rows unsorted: it only measures a group too large to sort whole.
1346
+ """
1347
  columns = [row[0] for row in con.execute(
1348
  "SELECT column_name FROM information_schema.columns WHERE table_name = ? "
1349
  "AND table_schema = 'main' ORDER BY ordinal_position", [name]).fetchall()]
1350
  keys = connector_spec.mirror_table_keys(name) or {}
1351
  declared = (*keys.get("filter_keys", ()), *keys.get("sort_keys", ()))
1352
+ order = ", ".join(_quoted_identifier(c) for c in dict.fromkeys(
1353
+ c for c in (*declared, *columns) if c in columns))
1354
+ order_by = f" ORDER BY {order}" if ordered else ""
1355
+ con.execute(f"COPY (SELECT * FROM {_quoted_identifier(name)} AS t WHERE {where}{order_by}) "
1356
  "TO ? (FORMAT PARQUET, COMPRESSION ZSTD)", [str(path)])
1357
+ _note_progress(f"{self.connector} mirror part {name}")
1358
  return path.stat().st_size
1359
 
1360
 
 
1372
  column = next((c for c in _PART_COLUMNS if c in cols), None)
1373
  if column:
1374
  expr = f"coalesce(substr(CAST(t.{_quoted_identifier(column)} AS VARCHAR), 1, 7), 'none')"
1375
+ counted = con.execute(f"SELECT {expr} AS g, count(*) FROM {_quoted_identifier(name)} AS t "
1376
+ "GROUP BY g ORDER BY g").fetchall()
1377
+ groups = [row[0] for row in counted] or ["none"] # an emptied table is still one (empty) part
1378
+ sizes = {row[0]: row[1] for row in counted}
1379
  else:
1380
  total = max(1, con.execute(f"SELECT count(*) FROM {_quoted_identifier(name)}").fetchone()[0])
1381
  buckets = 2
 
1383
  buckets *= 2
1384
  expr = f"CAST(hash(t) % {buckets} AS VARCHAR)"
1385
  groups = [str(b) for b in range(buckets)]
1386
+ sizes = {}
1387
+ limit = self.part_max_bytes - len(be.HEADER) - 28
1388
  out = []
1389
  for group in groups:
1390
  slug = _part_slug(group)
1391
  path = tmp / f"{name}.p{slug}.parquet"
1392
+ where = f"{expr} = {_sql_literal(group)}"
1393
+ # Sorting a whole large group exhausted the worker's memory and spill (D-18061). Measure it unsorted.
1394
+ large = sizes.get(group, 0) > _PART_SORT_ROWS
1395
+ size = self._copy_part(con, name, where, path, ordered=not large)
1396
+ if large and size <= limit * 8:
1397
+ # Small enough to sort whole, so it takes the same path and bytes as any other group.
1398
+ large, size = False, self._copy_part(con, name, where, path)
1399
+ if not large and size <= limit:
1400
  out.append((slug, path, None))
1401
  continue
1402
+ # Each sub-part is a full scan, so skip each k that cannot fit: its parts would hold under half
1403
+ # the group, or under an eighth of an unsorted measure (sorting can shrink a group).
1404
  k = 2
1405
+ while k < 1024 and k * limit * (8 if large else 2) < size:
1406
+ k *= 2
1407
  while True:
1408
  files, fits = [], True
1409
  for j in range(k):
1410
  sub = tmp / f"{name}.p{slug}-s{j}.parquet"
1411
  files.append((f"{slug}-s{j}", sub))
1412
+ if self._copy_part(con, name, f"{where} AND hash(t) % {k} = {j}", sub) > limit:
1413
+ # The next k rewrites every sub-part, so the rest of this one is wasted work.
1414
  fits = False
1415
+ break
1416
  if fits:
1417
  out.extend((s, f, None) for s, f in files)
1418
  break
 
1514
  con.execute(f"COPY (SELECT * FROM {_quoted_identifier(name)}) TO ? "
1515
  "(FORMAT PARQUET, COMPRESSION ZSTD)", [str(path)])
1516
  size = path.stat().st_size
1517
+ _note_progress(f"{self.connector} mirror checkpoint {name}")
1518
  if size is None or size > part_limit:
1519
  return self._chunked_entry(con, name, Path(tmp), prior, named, sealed=sealed)
1520
  metadata = _blob_metadata(path.read_bytes())
 
1570
  data = path.read_bytes()
1571
  self._upload(rt, key, data)
1572
  progress["uploaded"] += len(data)
1573
+ _note_progress(f"{self.connector} mirror upload")
1574
 
1575
 
1576
  def _publish_checkpoint(self, tenant_key, rt, con, cache, manifest, changed, pending, tmp, *,
 
1859
  path = Path(directory) / (name + ".parquet")
1860
  con.execute(f"COPY {_quoted_identifier(name)} TO ? (FORMAT PARQUET, COMPRESSION ZSTD)", [str(path)])
1861
  paths[name] = [path]
1862
+ _note_progress(f"{store.connector} mirror export {name}")
1863
  return paths
1864
 
1865
 
 
2032
  odoo = store.connector == "odoo"
2033
 
2034
  def note(message, started=None, names=None):
2035
+ # Every connector logs its publish steps, so a slow step names itself. A log error never changes control flow.
2036
  try:
2037
  text = message
2038
  if names is not None:
 
2063
  try:
2064
  opened = time.monotonic()
2065
  candidate, started = _open_candidate(store, tenant_key, rt, published)
2066
+ note("candidate open", opened)
 
2067
  pending = {row[0] for row in candidate.execute("SELECT name FROM _candidate_pending").fetchall()}
2068
  requested = set(store.spec.tables if expected_tables is None else expected_tables)
2069
  if odoo and pending:
 
2171
  with tempfile.TemporaryDirectory(prefix="mirror-publish-") as tmp:
2172
  exporting = time.monotonic()
2173
  paths = _export_tables(store, candidate, tmp)
2174
+ note(f"export, {len(paths)} tables", exporting)
 
2175
  saving = time.monotonic()
2176
  manifest = store.persist_mirror(tenant_key, rt, candidate, store._tables(candidate),
2177
  report=result, log=log, _publication=metadata)
2178
+ note("save" if manifest else "save failed", saving)
 
2179
  if not manifest:
2180
  problems = result["problems"] or ["The source snapshot is incomplete."]
2181
  if report is not None and "problems" in report:
 
2199
  except BaseException:
2200
  store.cache.pop(store._mirror_cache_key(tenant_key, rt), None)
2201
  raise
2202
+ note("install", installing)
 
2203
  for listener in list(_PUBLISH_LISTENERS):
2204
  try:
2205
  listener(store.connector, tenant_key, manifest, rows, paths)
2206
+ _note_progress(f"{store.connector} mirror hand-off")
2207
  except Exception as exc:
2208
  # The snapshot is saved and installed here. A failed hand-off only delays readers.
2209
  log(f"{store.label} mirror hand-off failed ({type(exc).__name__}: {exc})")
web/public/AIOS_DEPLOY_RECEIPT CHANGED
@@ -1 +1 @@
1
- 06c1c671e68eec5fa194450c3930cec81debf51cccf9ecefb8d9ea9b0ca064c1
 
1
+ a6f25a81706b22189ac685acb89a7b2fb67cd089c3813325b1ddde7ee0834c32