Spaces:
Running

fsanyoto commited on
Commit
0834dd0
·
verified ·
1 Parent(s): 4a336de

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,4 +1,4 @@
1
  {
2
- "current": "d55ae1af55",
3
  "releases": []
4
  }
 
1
  {
2
+ "current": "12a9276481",
3
  "releases": []
4
  }
VERSION CHANGED
@@ -1 +1 @@
1
- d55ae1af55
 
1
+ 12a9276481
api/routes_connectors.py CHANGED
@@ -3195,7 +3195,7 @@ def amazon_hold_cause(row=None, held="", *, table=""):
3195
  elif state == "deferred" and row.get("lastRefusal"):
3196
  # A table this pass did not ask keeps the cause of its last refusal, never a scheduling delay.
3197
  last = str(row["lastRefusal"]).strip() # already plain: `refused_reports` projects it
3198
- cause = (last if last.startswith(("Amazon refused", "Amazon does not offer", "Reconciliation"))
3199
  else "Amazon refused the last request: " + last) + " The next try is scheduled."
3200
  elif state == "deferred" or (not row and (not held or held.startswith("not reached"))):
3201
  cause = "This pass ended before this table's turn. The next pass continues it."
@@ -3212,7 +3212,7 @@ def amazon_hold_cause(row=None, held="", *, table=""):
3212
  plain = plain_refusal_reason(reason or held, status=status, table=table)
3213
  # A reconciliation hold is our own check, never an Amazon refusal.
3214
  reconciled = "reconciliation refused" in (reason or held)
3215
- cause = plain if reconciled or plain.startswith(("Amazon refused", "Amazon does not offer")) else (
3216
  "Amazon refused this report: " + plain)
3217
  else:
3218
  problem = held[len("a problem names this table: "):] if held.startswith("a problem names this table: ") else ""
@@ -3346,7 +3346,11 @@ def _amazon_table_schedule(rt, connection_id=None, now=None):
3346
  return " ".join(part for part in parts if part) or None
3347
 
3348
  # C1 owns every due time, including throttle retries and calendar periods.
3349
- for row in az.sync_schedule(states, now):
 
 
 
 
3350
  table = row["table"]
3351
  tick = states.get(table) or {}
3352
  watermark = markers.get(prefix + az.entity_key(az.WATERMARK_PREFIX + table)) or {}
 
3195
  elif state == "deferred" and row.get("lastRefusal"):
3196
  # A table this pass did not ask keeps the cause of its last refusal, never a scheduling delay.
3197
  last = str(row["lastRefusal"]).strip() # already plain: `refused_reports` projects it
3198
+ cause = (last if last.startswith(("Amazon refused", "Amazon does not offer", "Amazon ended", "Reconciliation"))
3199
  else "Amazon refused the last request: " + last) + " The next try is scheduled."
3200
  elif state == "deferred" or (not row and (not held or held.startswith("not reached"))):
3201
  cause = "This pass ended before this table's turn. The next pass continues it."
 
3212
  plain = plain_refusal_reason(reason or held, status=status, table=table)
3213
  # A reconciliation hold is our own check, never an Amazon refusal.
3214
  reconciled = "reconciliation refused" in (reason or held)
3215
+ cause = plain if reconciled or plain.startswith(("Amazon refused", "Amazon does not offer", "Amazon ended")) else (
3216
  "Amazon refused this report: " + plain)
3217
  else:
3218
  problem = held[len("a problem names this table: "):] if held.startswith("a problem names this table: ") else ""
 
3346
  return " ".join(part for part in parts if part) or None
3347
 
3348
  # C1 owns every due time, including throttle retries and calendar periods.
3349
+ # A no-reason FATAL's next sync is its retry deadline, the same time the planner uses.
3350
+ due_states = {table: az._no_reason_retry_tick(
3351
+ state, markers.get(prefix + az.entity_key(table)),
3352
+ {"detail": saved.get(prefix + az.entity_key("refused_" + table))}) for table, state in states.items()}
3353
+ for row in az.sync_schedule(due_states, now):
3354
  table = row["table"]
3355
  tick = states.get(table) or {}
3356
  watermark = markers.get(prefix + az.entity_key(az.WATERMARK_PREFIX + table)) or {}
platform/harness/amazon_store.py CHANGED
@@ -498,6 +498,11 @@ SCHEDULED_FLOOR_GRACE_SECONDS = 0
498
  SCHEDULE_PHASE_GRACE_SECONDS = 60
499
  #: `_sync_state` marker: the scheduled first-load guard deferred this table; never a tick, so no card reads it.
500
  PHASE_HOLD_PREFIX = "phase_hold_"
 
 
 
 
 
501
  _SCHEDULE_OFFSET_READER = None
502
 
503
 
@@ -611,7 +616,9 @@ def sync_plan(states, tables=None, *, now=None, slot_pass=False):
611
  oldest = datetime.min.replace(tzinfo=timezone.utc)
612
  # A tick that did not finish sorts as oldest: a throttled table's stamp is its failed try, and sorting by it
613
  # sent `inventory` behind every other report into a spent createReport burst each pass (SDLC 87 QI13).
614
- finished = {table for table, state in states.items() if state and state.get("state") == "done"}
 
 
615
  selected = sorted(due, key=lambda table: (stamps.get(table, oldest) if table in finished else oldest,
616
  want.index(table))) if ready else []
617
  if not ready:
@@ -641,6 +648,15 @@ def scheduled_sync_plan(tenant_key, *, rt, now=None):
641
  for entity, phase, rows, at, detail in con.execute(
642
  "SELECT entity, phase, rows, updated_at, cursor_wd FROM _sync_state "
643
  "WHERE starts_with(entity, ?)", [prefix]).fetchall()}
 
 
 
 
 
 
 
 
 
644
  plan = sync_plan(ticks, tables, now=now)
645
  hold = _account_prefix(entry["connection_id"]) + entity_key(PHASE_HOLD_PREFIX)
646
  # The planner reads cadence rows through this one query shape only, never source data.
@@ -684,6 +700,11 @@ def _interval_wait(table, state, now, floor_s=None):
684
  seconds = max(int(vendor), int(floor_s or 0))
685
  phased = bool(floor_s and _SCHEDULE_OFFSET_READER is not None)
686
  earliest = now
 
 
 
 
 
687
  if state and state.get("state") == "throttled" and state.get("detail"):
688
  due = _utc(state["detail"])
689
  wait = (due - now).total_seconds()
@@ -716,12 +737,52 @@ def _interval_reason(table, state, now, floor_s=None):
716
  return None
717
  if state and state.get("state") == "throttled":
718
  return f"Amazon is limiting requests; next retry {_iso(due)}"
 
 
719
  if scheduled:
720
  return (f"This Amazon table refreshes every {_readable_duration(seconds)}; "
721
  f"next due {_iso(due)}")
722
  return (f"Amazon allows this report at most once every {_readable_duration(seconds)}; "
723
  f"next due {_iso(due)}")
724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
725
  #: Durable proof that the two non-report role operations actually ran. A report-backed table can
726
  #: contain rows while one of these role grants is still missing, so table presence alone is not
727
  #: evidence that Pricing or AWD was authorized.
@@ -5377,6 +5438,12 @@ def plain_refusal_reason(reason, *, status="", table="", operation=""):
5377
  return "Amazon refused this date range. Choose a start date within the past two years and retry sync."
5378
  if "reportperiod" in lower or "reporting period" in lower:
5379
  return "Amazon needs a reporting period for this report. Check the date range and retry sync."
 
 
 
 
 
 
5380
  if status == "CANCELLED" or "cancelled" in lower:
5381
  return "Amazon cancelled this report. Retry sync to request it again."
5382
  if status == "FATAL" or "fatal" in lower or "could not prepare" in lower:
@@ -5412,7 +5479,7 @@ def plain_refusal_reason(reason, *, status="", table="", operation=""):
5412
  def is_refusal_reason(reason):
5413
  """Recognize refusal facts in legacy status rows without first-load metadata."""
5414
  return bool(re.search(
5415
- r"REFUSED:|\b(?:FATAL|CANCELLED|NOT_OFFERED)\b|Amazon (?:refused|cancelled|could not (?:prepare|load)|"
5416
  r"has not granted access|does not offer|is limiting requests|needs a reporting period)|This connector cannot request",
5417
  str(reason or ""), re.I))
5418
 
@@ -10496,6 +10563,10 @@ def _sync_candidate(tenant_key="royal-imports", tables=None, since=None, log=pri
10496
  if (tick and tick["state"] == "done" and queued_resync(con, table) is not None
10497
  and read_watermark(con, table) and not _interval_reason(table, tick, end)):
10498
  ticks[table] = {**tick, "state": "resync"}
 
 
 
 
10499
  plan = sync_plan(ticks, want, now=end, slot_pass=slot_pass)
10500
  want = plan["tables"]
10501
  for table, reason in plan["deferred"].items():
@@ -11442,10 +11513,13 @@ def _sync_candidate(tenant_key="royal-imports", tables=None, since=None, log=pri
11442
  _record_state(con, entity_key(refused), problem["state"], 0, problem["reason"])
11443
  if problem["state"] == "refused":
11444
  attempts = prior_refusals.get(refused, {}).get("attempts", 0) + 1
11445
- _record_state(con, entity_key("refused_" + refused), "refused", detail=json.dumps({
11446
- "reason": problem["reason"][:500], "amazonStatus": problem["amazonStatus"],
11447
- "diagnostic": problem.get("diagnostic", "")[:500],
11448
- "error": problem.get("error", ""), "attempts": attempts}))
 
 
 
11449
  if problem["state"] == "throttled":
11450
  if refused != table:
11451
  _save_throttled_resume(con, refused, e, sibling_plan, completed_windows,
 
498
  SCHEDULE_PHASE_GRACE_SECONDS = 60
499
  #: `_sync_state` marker: the scheduled first-load guard deferred this table; never a tick, so no card reads it.
500
  PHASE_HOLD_PREFIX = "phase_hold_"
501
+ #: A report Amazon ends FATAL with no error document gave no reason, so it is asked again on its own
502
+ #: deadline: 10, 20, 40, then 80 minutes after each try, at most 4 retries a UTC day, then its daily phase.
503
+ NO_REASON_RETRY_STATE = "retry_no_reason"
504
+ NO_REASON_RETRY_FIRST_SECONDS = 600
505
+ NO_REASON_RETRIES_PER_DAY = 4
506
  _SCHEDULE_OFFSET_READER = None
507
 
508
 
 
616
  oldest = datetime.min.replace(tzinfo=timezone.utc)
617
  # A tick that did not finish sorts as oldest: a throttled table's stamp is its failed try, and sorting by it
618
  # sent `inventory` behind every other report into a spent createReport burst each pass (SDLC 87 QI13).
619
+ # A no-reason retry sorts by its failed try, so it never spends the createReport burst ahead of inventory.
620
+ finished = {table for table, state in states.items()
621
+ if state and state.get("state") in ("done", NO_REASON_RETRY_STATE)}
622
  selected = sorted(due, key=lambda table: (stamps.get(table, oldest) if table in finished else oldest,
623
  want.index(table))) if ready else []
624
  if not ready:
 
648
  for entity, phase, rows, at, detail in con.execute(
649
  "SELECT entity, phase, rows, updated_at, cursor_wd FROM _sync_state "
650
  "WHERE starts_with(entity, ?)", [prefix]).fetchall()}
651
+ account = _account_prefix(entry["connection_id"])
652
+ wanted = {account + entity_key(family + table) for table in ticks for family in ("", "refused_")}
653
+ # The same single query shape as the ticks: the planner reads cadence rows only.
654
+ marks = {entity: {"state": phase, "detail": detail} for entity, phase, _rows, _at, detail in con.execute(
655
+ "SELECT entity, phase, rows, updated_at, cursor_wd FROM _sync_state "
656
+ "WHERE starts_with(entity, ?)", [account]).fetchall() if entity in wanted} if ticks else {}
657
+ ticks = {table: _no_reason_retry_tick(tick, marks.get(account + entity_key(table)),
658
+ marks.get(account + entity_key("refused_" + table)))
659
+ for table, tick in ticks.items()}
660
  plan = sync_plan(ticks, tables, now=now)
661
  hold = _account_prefix(entry["connection_id"]) + entity_key(PHASE_HOLD_PREFIX)
662
  # The planner reads cadence rows through this one query shape only, never source data.
 
700
  seconds = max(int(vendor), int(floor_s or 0))
701
  phased = bool(floor_s and _SCHEDULE_OFFSET_READER is not None)
702
  earliest = now
703
+ if floor_s and state and state.get("state") == NO_REASON_RETRY_STATE and state.get("detail"):
704
+ # A no-reason FATAL is asked again at its own deadline, never on the daily phase or the success floor.
705
+ due = _utc(state["detail"])
706
+ wait = (due - now).total_seconds()
707
+ return (wait, due, int(wait), False) if wait > 0 else (0, None, seconds, False)
708
  if state and state.get("state") == "throttled" and state.get("detail"):
709
  due = _utc(state["detail"])
710
  wait = (due - now).total_seconds()
 
737
  return None
738
  if state and state.get("state") == "throttled":
739
  return f"Amazon is limiting requests; next retry {_iso(due)}"
740
+ if state and state.get("state") == NO_REASON_RETRY_STATE:
741
+ return f"Amazon ended the last report without a reason; next retry {_iso(due)}"
742
  if scheduled:
743
  return (f"This Amazon table refreshes every {_readable_duration(seconds)}; "
744
  f"next due {_iso(due)}")
745
  return (f"Amazon allows this report at most once every {_readable_duration(seconds)}; "
746
  f"next due {_iso(due)}")
747
 
748
+
749
+ def _no_reason_fatal(exc, table):
750
+ """Amazon ended the report FATAL and sent no error document, so it gave no reason."""
751
+ return (table != SQP_TABLE and getattr(exc, "status", None) == "FATAL"
752
+ and getattr(exc, "has_error_document", True) is False)
753
+
754
+
755
+ def _no_reason_retry_at(saved, detail, now=None):
756
+ """Count today's no-reason tries into `detail`. -> the next retry time, or None once today's retries are spent."""
757
+ now = _utc(now)
758
+ day = now.date().isoformat()
759
+ try:
760
+ prior = json.loads((saved or {}).get("detail") or "{}")
761
+ tries = int(prior.get("noReasonTries") or 0) if prior.get("noReasonDay") == day else 0
762
+ except (ValueError, TypeError, AttributeError):
763
+ tries = 0
764
+ tries += 1
765
+ detail.update(noReasonDay=day, noReasonTries=tries)
766
+ if tries > NO_REASON_RETRIES_PER_DAY:
767
+ return None
768
+ retry_at = now + timedelta(seconds=NO_REASON_RETRY_FIRST_SECONDS * 2 ** (tries - 1))
769
+ detail["retryAt"] = _iso(retry_at)
770
+ return retry_at
771
+
772
+
773
+ def _no_reason_retry_tick(tick, mark, refused):
774
+ """Read a closed tick as its retry deadline while a no-reason FATAL is still the table's latest answer."""
775
+ if (not tick or tick.get("state") not in ("done", "attempted") or not tick.get("updated_at")
776
+ or (mark or {}).get("state") != "refused"):
777
+ return tick
778
+ try:
779
+ retry_at = json.loads((refused or {}).get("detail") or "{}").get("retryAt")
780
+ if not retry_at or _utc(tick["updated_at"]) > _utc(retry_at):
781
+ return tick
782
+ except (ValueError, TypeError, AttributeError):
783
+ return tick
784
+ return {**tick, "state": NO_REASON_RETRY_STATE, "detail": retry_at}
785
+
786
  #: Durable proof that the two non-report role operations actually ran. A report-backed table can
787
  #: contain rows while one of these role grants is still missing, so table presence alone is not
788
  #: evidence that Pricing or AWD was authorized.
 
5438
  return "Amazon refused this date range. Choose a start date within the past two years and retry sync."
5439
  if "reportperiod" in lower or "reporting period" in lower:
5440
  return "Amazon needs a reporting period for this report. Check the date range and retry sync."
5441
+ if re.match(r"amazon ended (?:report \d+|this report) without giving a reason\.", lower):
5442
+ return text # already projected: the stored reason is re-read through this function
5443
+ if "no error document was supplied by amazon" in lower:
5444
+ report_id = re.search(r"\breportid (\d+)", lower)
5445
+ subject = f"report {report_id[1]}" if report_id else "this report"
5446
+ return f"Amazon ended {subject} without giving a reason. Sync asks again automatically."
5447
  if status == "CANCELLED" or "cancelled" in lower:
5448
  return "Amazon cancelled this report. Retry sync to request it again."
5449
  if status == "FATAL" or "fatal" in lower or "could not prepare" in lower:
 
5479
  def is_refusal_reason(reason):
5480
  """Recognize refusal facts in legacy status rows without first-load metadata."""
5481
  return bool(re.search(
5482
+ r"REFUSED:|\b(?:FATAL|CANCELLED|NOT_OFFERED)\b|Amazon (?:refused|cancelled|ended .{1,40} without giving a reason|could not (?:prepare|load)|"
5483
  r"has not granted access|does not offer|is limiting requests|needs a reporting period)|This connector cannot request",
5484
  str(reason or ""), re.I))
5485
 
 
10563
  if (tick and tick["state"] == "done" and queued_resync(con, table) is not None
10564
  and read_watermark(con, table) and not _interval_reason(table, tick, end)):
10565
  ticks[table] = {**tick, "state": "resync"}
10566
+ for table in want:
10567
+ # A no-reason FATAL is asked again at its retry deadline, not on the daily phase.
10568
+ ticks[table] = _no_reason_retry_tick(ticks.get(table), _read_state(con, entity_key(table)),
10569
+ _read_state(con, entity_key("refused_" + table)))
10570
  plan = sync_plan(ticks, want, now=end, slot_pass=slot_pass)
10571
  want = plan["tables"]
10572
  for table, reason in plan["deferred"].items():
 
11513
  _record_state(con, entity_key(refused), problem["state"], 0, problem["reason"])
11514
  if problem["state"] == "refused":
11515
  attempts = prior_refusals.get(refused, {}).get("attempts", 0) + 1
11516
+ refusal = {"reason": problem["reason"][:500], "amazonStatus": problem["amazonStatus"],
11517
+ "diagnostic": problem.get("diagnostic", "")[:500],
11518
+ "error": problem.get("error", ""), "attempts": attempts}
11519
+ if _no_reason_fatal(e, refused):
11520
+ # The planner reads `retryAt` back through `_no_reason_retry_tick`.
11521
+ _no_reason_retry_at(_read_state(con, entity_key("refused_" + refused)), refusal)
11522
+ _record_state(con, entity_key("refused_" + refused), "refused", detail=json.dumps(refusal))
11523
  if problem["state"] == "throttled":
11524
  if refused != table:
11525
  _save_throttled_resume(con, refused, e, sibling_plan, completed_windows,
web/public/AIOS_DEPLOY_RECEIPT CHANGED
@@ -1 +1 @@
1
- 11bc87441e5a07c0639ef14412b887871d73f0442dda63887db62695986e2ab7
 
1
+ c54488570a80aec1adda057034e2a653209ce6ea45309e01725d841d9c7bf6b3