diff --git "a/api/automation_engine.py" "b/api/automation_engine.py" --- "a/api/automation_engine.py" +++ "b/api/automation_engine.py" @@ -84,18 +84,44 @@ MAX_UT_TABLES = 40 MAX_UT_IG_ROWS = 200_000 IG_TABLE_PREFIX = "ut_ig_" -KINDS = ("scrape_db", "field_instagram") +#: ⚠ THE RAISED CEILING BELONGS TO THE **APPEND** TABLES, NOT TO A NAME PREFIX (wave 20). It was +#: keyed off `ut_ig_`, which was exactly right while every `ut_ig_*` table was an append table — +#: and stopped being right the moment discovery added `ut_ig_candidates`, which is UPSERTED BY +#: HANDLE and is bounded by how many accounts exist rather than by how often we look. It would +#: have inherited a 200,000-row ceiling, and with it the measured 35.8 MB single-bucket +#: serialisation cost, purely by an accident of naming. Naming the append tables is the version +#: that stays true when the next `ut_ig_*` table is not one. +APPEND_TABLES = frozenset({"ut_ig_snapshots", "ut_ig_post_snapshots"}) + +KINDS = ("scrape_db", "field_instagram", "discover_instagram") EXTRACTS = ("table", "jsonld") STATES = ("idle", "running", "ok", "error", "partial") #: Which capture rung a `field_instagram` automation is allowed to reach for (R1's hybrid). -#: `anonymous` = the $0 ladder only. `hiker` = the paid rung FIRST, then the ladder as a fallback -#: (unless the fallback is switched off — see `graph`'s `fallback` toggle). -TIERS = ("anonymous", "hiker") +#: `anonymous` = the $0 ladder only. `brightdata` = the paid rung FIRST, then the ladder as a +#: fallback (unless the fallback is switched off — see `graph`'s `fallback` toggle). +TIERS = ("anonymous", "brightdata") +#: ⚠ STORED CONFIGS SAY `hiker`, AND THEY MEAN "THE PAID RUNG" (wave-20 D-21). The vendor swap +#: must not silently answer that request with the free ladder: `clean_config` refuses an unknown +#: tier by falling back to `anonymous`, so without this alias every existing Instagram automation +#: would quietly stop reaching for exact counts and nothing would say so. Mapping FORWARD keeps +#: the user's expressed intent (they turned the paid step ON) at a cost of ~$0.0015 a profile. +TIER_ALIASES = {"hiker": "brightdata"} + + +def clean_tier(raw): + """A stored/posted tier → a tier this engine runs, or '' when it is neither.""" + t = str(raw or "").strip().lower() + t = TIER_ALIASES.get(t, t) + return t if t in TIERS else "" def row_cap(table_key): - """The row ceiling for ONE table. Per-table rather than global — see `MAX_UT_IG_ROWS`.""" - return MAX_UT_IG_ROWS if str(table_key or "").startswith(IG_TABLE_PREFIX) else MAX_UT_ROWS + """The row ceiling for ONE table. Per-table rather than global — see `MAX_UT_IG_ROWS`. + + An APPEND table (one row per subject per pull, forever) gets the raised ceiling; everything + else — including the `ut_ig_` table that is an UPSERT — keeps the list-table one. + """ + return MAX_UT_IG_ROWS if str(table_key or "") in APPEND_TABLES else MAX_UT_ROWS #: Schedule presets the editor offers. Kept here (not in the client) so the vocabulary the UI #: shows and the vocabulary the parser accepts cannot drift. @@ -119,14 +145,43 @@ def _stamp(dt=None): def _iso(dt=None): - return (dt or _now()).strftime("%Y-%m-%dT%H:%M:%S") + """An ISO stamp **WITH its UTC offset** — `2026-08-05T14:03:11+07:00` (DEBT D-18). + + ⚠ THE OFFSET IS NOT COSMETIC. These stamps are the time axis of the `ut_ig_*` append tables + and they are rendered by a browser, which can only subtract from an instant it can LOCATE. A + naive `2026-08-05T14:03:11` is read as the *reader's* local time, so a container running UTC + minted cells a Jakarta browser would place seven hours in the future — and "2 minutes ago" is + not expressible at all. With the offset the same string is an instant, and relative rendering + becomes possible without migrating a single stored row. + + ⚠ `_parse_iso` reads it BACK as naive local ON PURPOSE. Every cron / `is_due` comparison in + this module is against a naive `_now()`, and mixing aware and naive datetimes raises + `TypeError` — so the offset rides on the WIRE and never enters the arithmetic. + """ + dt = dt or _now() + if dt.tzinfo is None: + dt = dt.astimezone() # a naive stamp from this process IS local time + return dt.isoformat(timespec="seconds") def _parse_iso(s): + """A stamp → a NAIVE LOCAL datetime, with or without an offset. + + Both shapes exist in the store simultaneously and always will: every run committed before + D-18 wrote a naive stamp, and nothing rewrites history. A parser that understood only the new + shape would silently return None for them — and `is_due` reads None as "never ran", which + would re-fire every schedule once. Reading both is what makes the change additive. + """ + raw = str(s or "").strip().replace("Z", "+00:00") + dt = None try: - return _dt.datetime.strptime(str(s)[:19], "%Y-%m-%dT%H:%M:%S") - except Exception: - return None + dt = _dt.datetime.fromisoformat(raw) + except Exception: # noqa: BLE001 + try: + dt = _dt.datetime.strptime(raw[:19], "%Y-%m-%dT%H:%M:%S") + except Exception: # noqa: BLE001 + return None + return dt.astimezone().replace(tzinfo=None) if dt.tzinfo is not None else dt # --------------------------------------------------------------------------------------------- @@ -224,6 +279,30 @@ def fetch(url, timeout=20.0, max_kb=2048, allowed=(), max_hops=5, headers=None): raise Refused(f"more than {max_hops} redirects — refusing to follow further") +def fetch_json(url, body, timeout=60.0, max_kb=8192, headers=None): + """POST a JSON body through the SAME guard. Returns `(status, body_bytes)`. + + ⛔ NO REDIRECT FOLLOWING, AND THAT IS THE WHOLE DIFFERENCE FROM `fetch`. `fetch` walks hops by + hand because a redirected GET is ordinary. A redirected POST is not: re-sending a + credential-bearing body to a Location the *server* chose is precisely the hop the SSRF rail + exists to refuse, and `requests`' own `allow_redirects=True` would do it without ever + re-entering `guard`. So a 3xx here is a REFUSAL with the reason on it, never a second request. + (The vendor calls below are the only POSTs this module makes, and they carry the API key.) + """ + guard(url) + hdrs = {"User-Agent": UA, "Content-Type": "application/json", "Accept": "application/json"} + hdrs.update(headers or {}) + r = requests.post(url, timeout=timeout, headers=hdrs, allow_redirects=False, + data=json.dumps(body if body is not None else {}), stream=True) + try: + if r.status_code in (301, 302, 303, 307, 308): + raise Refused(f"the POST answered {r.status_code} — a redirected POST is refused, " + f"never re-sent to a location the server picked") + return r.status_code, (r.raw.read(max_kb * 1024, decode_content=True) or b"") + finally: + r.close() + + # --------------------------------------------------------------------------------------------- # EXTRACTION — vendored from scrape.py, unchanged in behaviour # --------------------------------------------------------------------------------------------- @@ -576,6 +655,12 @@ def ut_key_for(label, key=None): return k if k.startswith(UT_PREFIX) else UT_PREFIX + k +#: Machine names, mirrored from `core.user_tables.MACHINE_OWNERS`. A LOCAL literal for the same +#: reason `UT_FIELD_TYPES` is one over there — this module must stay importable without dragging +#: `core` into the API's boot path — and the two are held in step by a gate check. +MACHINE_OWNERS = ("automation", "scheduler") + + def ut_ensure(rt, label, fields, username="automation", key=None): """Create the table if it is missing; return its key. Idempotent — a re-run of an automation that owns a table must not spawn `ut_x_2`, so the key is DERIVED from the label (or given) @@ -583,18 +668,29 @@ def ut_ensure(rt, label, fields, username="automation", key=None): Fields are MERGED, never replaced: a user who added a column to an automation's table keeps it, and a new source column joins on the next run. + + ⛔ AND IT STAMPS A HUMAN OWNER, WHICH IT DID NOT (wave 20, item 3). `createdBy` was whoever + or WHATEVER ran the automation, so the same table belonged to a person if its first run was + manual and to `"scheduler"` if the schedule got there first — and `user_tables.may_open` + admits only the creator or an admin, so **whether you could open your own Instagram + snapshots depended on a race you never saw**. The owner is now the automation's creator, and + a table already stamped with a machine name is ADOPTED the next time a run knows a human + one. Adoption is a repair, not a widening: the automation's creator is the person who asked + for the table in the first place. """ key = ut_key_for(label, key) wanted = list(fields or []) created = _iso() + human = username if username and username not in MACHINE_OWNERS else "" # ⚠ SKIP THE WRITE WHEN NOTHING WOULD CHANGE. Without this, every re-run spends a store # commit re-writing an identical definition — against a 20 s flush floor and a 256/hr repo # budget, an idempotent helper that always writes is the same defect as a per-row insert. have = ut_get(rt, key) - if have is not None and not [f for f in wanted - if f.get("key") not in {g.get("key") - for g in (have.get("fields") or [])}]: + if (have is not None + and not [f for f in wanted + if f.get("key") not in {g.get("key") for g in (have.get("fields") or [])}] + and not (human and (have.get("createdBy") or "") in MACHINE_OWNERS)): return key def _up(cur): @@ -612,6 +708,9 @@ def ut_ensure(rt, label, fields, username="automation", key=None): if f.get("key") not in have: t.setdefault("fields", []).append(f) have.add(f.get("key")) + # ADOPTION: a machine name is not an owner. It never overwrites a human one. + if human and (t.get("createdBy") or "") in MACHINE_OWNERS: + t["createdBy"] = human # An automation's table SAYS an automation owns it — the nav badge reads from this. t["source"] = t.get("source") or "Automation" return cur @@ -708,17 +807,41 @@ def clean_config(kind, raw, previous=None): fkey = _s(raw.get("fieldKey"), 80).strip() if not fkey: return None, "pick the automation column this run writes into" + # ⚠ UNKNOWN TIERS FALL BACK TO `anonymous`, NOT to the paid rung. A typo must never be + # the thing that starts spending money. An ABSENT tier keeps the one already stored (see + # the `flag` note above), and a stored `hiker` is carried FORWARD to the new vendor + # rather than silently demoted — see `TIER_ALIASES`. + tier = clean_tier(raw["tier"]) if "tier" in raw else "" + if not tier and "tier" not in raw: + tier = clean_tier(prev.get("tier")) return {"targetTable": table, "fieldKey": fkey, "urlField": _s(raw.get("urlField"), 80).strip(), - # ⚠ UNKNOWN TIERS FALL BACK TO `anonymous`, NOT to the paid rung. A typo must - # never be the thing that starts spending money. An ABSENT tier keeps the one - # already stored (see the `flag` note above). - "tier": (raw["tier"] if raw.get("tier") in TIERS - else prev.get("tier") if "tier" not in raw and prev.get("tier") in TIERS - else "anonymous"), + "tier": tier or "anonymous", "noFallback": flag("noFallback"), + # ⛔ THE ONE FLAG THAT MULTIPLIES THE BILL BY THE POST COUNT. Off unless asked + # for: the Profiles row carries post IDENTITY for free but NO engagement + # (measured 2026-08-05), so likes/comments cost one extra vendor record PER POST. + "postMetrics": flag("postMetrics"), "dryRun": flag("dryRun"), "maxPosts": max(1, min(int(raw.get("maxPosts") or 24), 200))}, None + if kind == "discover_instagram": + limit = int(raw.get("recordsLimit") or 0) + if limit < 1: + return None, ("say how many profiles to fetch — an UNBOUNDED discovery query is the " + "one shape the vendor refuses outright (NOT_ENOUGH_FUNDS)") + if limit > BD_MAX_RECORDS: + return None, f"a single discovery run may ask for at most {BD_MAX_RECORDS} profiles" + preds, perr = clean_predicates(raw.get("predicates")) + if perr: + return None, perr + target = _s(raw.get("targetTable"), 60).strip() or DISCOVER_TABLE + if not target.startswith(UT_PREFIX): + target = UT_PREFIX + target + return {"recordsLimit": limit, "predicates": preds, + "operator": "or" if str(raw.get("operator") or "").lower() == "or" else "and", + "targetTable": target, + "targetLabel": _s(raw.get("targetLabel"), 60).strip() or "IG candidates", + "dryRun": flag("dryRun")}, None return None, f"unknown automation kind {kind!r}" @@ -761,11 +884,37 @@ def clean_definition(raw, previous=None, username=""): "name": name, "kind": kind, "config": config, "schedule": schedule, "status": prev.get("status") or {"state": "idle", "lastRunAt": "", "lastSummary": ""}, "runs": list(prev.get("runs") or [])[:MAX_RUNS], + # ⚠ ENGINE-OWNED CONTINUATION STATE, and it is NOT config. A discovery snapshot takes ~20 + # minutes to build, so a run persists its id here and the NEXT run collects it. It is + # carried through `patch` untouched because a user pressing Save must not silently orphan + # a set the vendor is already building (and already counting against the funds gate). + "state": dict(prev.get("state") or {}), "created": prev.get("created") or _iso(), "createdBy": prev.get("createdBy") or username, }, None +def set_state(rt, auto_id, patch_state): + """Merge into ONE automation's engine state. A key set to None is removed. + + Its own tiny store write rather than a field on `_commit_run`, because the handoff must + survive a run that ends in `error` — a snapshot the vendor is building does not stop existing + because the run that started it failed afterwards. + """ + def _up(cur): + cur = cur if isinstance(cur, dict) else {} + d = cur.get(str(auto_id)) + if d is None: + return cur + st = dict(d.get("state") or {}) + for k, v in (patch_state or {}).items(): + st.pop(k, None) if v is None else st.__setitem__(k, v) + d["state"] = st + return cur + + rt.update(STORE_KEY, _up, flush="sync") + + def all_definitions(rt): try: return dict(rt.get(STORE_KEY) or {}) @@ -893,9 +1042,9 @@ def _commit_run(rt, auto_id, state, summary, counts, ok, affected=None, steps=No # --------------------------------------------------------------------------------------------- # INSTAGRAM (R7, extended by R1) — PUBLIC DATA ONLY, NEVER AN INSTAGRAM LOGIN # --------------------------------------------------------------------------------------------- -# ⚠ AMENDED W19-C. This section read "ANONYMOUS PUBLIC ENDPOINTS ONLY" and that is no longer the -# whole truth: R1 added a paid VENDOR rung (HikerAPI, further down) which does authenticate — to -# the vendor. The rail that actually matters is unchanged and is the sharper statement of it: +# ⚠ AMENDED W19-C, vendor swapped W20. This section read "ANONYMOUS PUBLIC ENDPOINTS ONLY" and +# that is no longer the whole truth: R1 added a paid VENDOR rung (Bright Data, further down) +# which does authenticate — to the vendor. The rail that matters is unchanged and is sharper: # # **NOTHING HERE EVER AUTHENTICATES TO INSTAGRAM.** No login, no password, no session cookie, # no account to get banned, public data only. The vendor key is a key to a SUPPLIER, and the @@ -917,6 +1066,17 @@ PACE_SECONDS = float(os.environ.get("AIOS_IG_PACE_SECONDS") or 2.5) IG_APP_ID = "936619743392459" # the public web client id the browser itself sends IG_MAX_RETRIES = 2 +#: ⭐ MAP THE SCHEMA, NOT JUST WHAT WAS POPULATED ON THE PROBE — and the reason is this page's +#: own headline. **HISTORY IS UNBUYABLE.** No vendor sells "followers on 1 January"; every number +#: is a NOW value, so the series starts the day capture starts and a field we do not capture +#: TODAY is permanently lost for today. Dropping a column because it was null on two probe rows +#: has exactly the same cost as delaying capture — for that column — and is justified by exactly +#: the evidence (n=2) that was judged too thin to close D-25. Adding a column that turns out to +#: be usually-empty costs a blank cell; omitting one costs the months before somebody notices. +#: ⛔ THE ONLY EXCLUSIONS ARE RULINGS, NOT TASTE: contact PII (D-24) and third-party comment text +#: (R11), both enforced in `BD_NEVER_MAP`. +#: ⚠ A blank in any of these means NOT READ — never "they have none". The anonymous rungs expose +#: almost none of them, which is what the `source` column is for. SNAPSHOT_FIELDS = [ field_def("snapshot_key", "Snapshot"), field_def("influencer_key", "Influencer"), field_def("pulled_at", "Pulled at"), field_def("followers", "Followers"), @@ -925,14 +1085,32 @@ SNAPSHOT_FIELDS = [ field_def("verified", "Verified"), field_def("source", "Read via"), field_def("approx", "Counts are approximate"), # The link in bio — the paid rung's field, and commercially the most useful single string an - # influencer row can carry (it is the shop/affiliate destination). Blank on the anonymous - # rungs, which do not expose it; a blank here means "not read", never "they have none". + # influencer row can carry (it is the shop/affiliate destination). field_def("external_url", "Link in bio", "url"), + # --- the rest of the vendor's Profiles schema, minus the PII and the comment text. + field_def("ig_id", "Instagram id"), + field_def("profile_url", "Profile", "url"), + field_def("avg_engagement", "Avg engagement"), + field_def("category", "Category"), + field_def("business_category", "Business category"), + field_def("is_business", "Business account"), + field_def("is_professional", "Professional account"), + field_def("is_private", "Private"), + field_def("highlights_count", "Highlights"), + field_def("bio_hashtags", "Bio hashtags"), + field_def("post_hashtags", "Post hashtags"), + field_def("pronouns", "Pronouns"), ] POST_FIELDS = [ field_def("shortcode", "Shortcode"), field_def("influencer_key", "Influencer"), field_def("posted_at", "Posted at"), field_def("type", "Type"), field_def("caption", "Caption"), field_def("url", "URL", "url"), + # Sponsored-post detection — §2c called it one of the fields worth having that the anonymous + # ladder cannot reach, and it came back MEASURED-populated (`True`, with the brand attached). + field_def("paid_partnership", "Paid partnership"), + field_def("partner", "Partner brand"), + field_def("hashtags", "Hashtags"), + field_def("alt_text", "Alt text"), ] POST_SNAPSHOT_FIELDS = [ field_def("post_snapshot_key", "Snapshot"), field_def("shortcode", "Shortcode"), @@ -1044,95 +1222,162 @@ def _loose_count(txt): # --------------------------------------------------------------------------------------------- -# HIKERAPI — THE PAID RUNG (owner ruling R1, contract C4) +# BRIGHT DATA — THE PAID RUNG (owner ruling R1 / wave-20 D-21, contract C4) # --------------------------------------------------------------------------------------------- # WHY A VENDOR AT ALL, stated once so nobody re-opens it: the anonymous ladder above is honest but # it is ALSO geographically fenced — Instagram blocks datacenter egress, so from the HF Space or a # Lambda the ladder degrades to `blocked` and the whole automation becomes a thing that only works -# on the owner's desk. HikerAPI takes the egress risk, returns EXACT counts (not og:description's -# "204K") and reaches post-level data the anonymous surface has closed. ~$0.0006/req. +# on the owner's desk. The vendor takes the egress risk, returns EXACT counts (not +# og:description's "204K") and reaches post-level data the anonymous surface has closed. +# +# ⚠ WHY THIS VENDOR AND NOT THE PREVIOUS ONE. HikerAPI was crypto-only with no legal entity — +# no invoice, no counterparty, nothing that can go on a subprocessor list at the EU/enterprise +# gates. Bright Data is nameable, litigated Meta and won on logged-off public scraping, and runs +# KYC. That is a POSTURE purchase, not a feature one; the price is ~2.5× and it is the right +# trade. Full comparison: `.claude/wiki/research/instagram-capture.md` §2a. # -# ⛔ FOUR RAILS, and each one is a failure mode rather than a preference: -# 1. **FAIL-CLOSED on the key.** No `AIOS_HIKERAPI_KEY` ⇒ this rung refuses with an honest +# ⛔ THE FOUR RAILS TRANSFER UNCHANGED (contract C4 — they were written vendor-agnostic): +# 1. **FAIL-CLOSED on the key.** No `AIOS_BRIGHTDATA_KEY` ⇒ this rung refuses with an honest # blocked ATTEMPT and the anonymous ladder still runs. Never a crash, never a silent skip. # 2. **The key is never logged, never in a URL, never in an exception.** It travels in the -# `x-access-key` header only, and every error below quotes a STATUS, never the request. A -# secret that reaches a log line has leaked to everyone who can read logs. -# 3. **The base URL is guarded like any other.** `AIOS_HIKERAPI_BASE` is env-provided, so it +# `Authorization: Bearer` header only, and every error below quotes a STATUS, never the +# request. A secret that reaches a log line has leaked to everyone who can read logs. +# 3. **The base URL is guarded like any other.** `AIOS_BRIGHTDATA_BASE` is env-provided, so it # goes through the same SSRF rail — an env var pointed at the metadata endpoint would # otherwise be a credential-bearing request to it. -# 4. **A rung failure is a RUNG failure.** `hiker_get` swallows its own `Refused`/transport +# 4. **A rung failure is a RUNG failure.** `bd_call` swallows its own `Refused`/transport # errors, because `run_now` turns a `Refused` into a whole-run error — and a mistyped base # URL must not kill a run whose anonymous rung would have answered. +# 5. **Exact ⇒ NO `approx` TAG.** That tag is the anonymous rung's rounding disclosure. # # ⚠ THE KEY IS READ LAZILY, INSIDE THE CALL. A module-level snapshot would be taken at import, # which makes the "key absent ⇒ blocked, not crash" gate untestable (nothing could flip it between # checks) and would also mean a deploy that sets the secret after import silently has no key. +# +# ⛔ TWO SNAPSHOT NAMESPACES THAT 404 EACH OTHER (measured; the trap that costs an hour): +# the SCRAPER `/datasets/v3/trigger` + `/v3/scrape` -> `sd_…` read at `/datasets/v3/…` +# the CORPUS `/datasets/filter` (⚠ NO `/v3/`) -> `snap_…` read at `/datasets/…` +# Cross them and you get a flat "404 Snapshot does not exist" about a snapshot that is alive. -#: Pinned from the live OpenAPI spec (`https://api.hikerapi.com/openapi.json`, read 2026-08-04) — -#: see `.claude/wiki/research/instagram-capture.md` for the full mapping and its provenance tags. +#: Pinned from live probes against `api.brightdata.com` (2026-08-04 and 2026-08-05) — see +#: `.claude/wiki/research/instagram-capture.md` §2c/§2d for the recipe and its provenance tags. #: They live in ONE named block so a vendor rename is a one-line fix rather than a hunt. -HIKER_BASE_DEFAULT = "https://api.hikerapi.com" -HIKER_PATH_USER = "/v1/user/by/username" # -> exact counts + bio. param: username -HIKER_PATH_MEDIAS = "/v1/user/medias/chunk" # -> posts. params: user_id, end_cursor -HIKER_TIMEOUT = 30.0 -#: ⚠ NO PAGE-SIZE CONSTANT. The chunk endpoint takes `user_id` and `end_cursor` only — the page -#: size is the vendor's to choose. A `HIKER_PAGE = 50` sat here unused, which reads as a parameter -#: somebody forgot to send rather than one that does not exist. - - -def hiker_key(): +BD_BASE_DEFAULT = "https://api.brightdata.com" +BD_DS_PROFILES = "gd_l1vikfch901nx3by4" # Instagram – Profiles. 36 fields, 620M records +BD_DS_POSTS = "gd_lk5ns7kz21pck8jpis" # Instagram – Posts. 43 fields +BD_PATH_SCRAPE = "/datasets/v3/scrape" # SYNC: rows come back inline. param: dataset_id +BD_PATH_TRIGGER = "/datasets/v3/trigger" # ASYNC: -> {"snapshot_id": "sd_…"} +BD_PATH_SNAPSHOT = "/datasets/v3/snapshot" # /?format=json -> the rows +BD_PATH_FILTER = "/datasets/filter" # ⚠ NO /v3/ — the CORPUS query (discovery) +BD_PATH_FILTER_SNAPSHOT = "/datasets/snapshot" # / -> status +#: A sync scrape MEASURED at 15–23 s for one URL and ~40 s for two, so the timeout is generous; +#: it is a ceiling against a hung socket, not a latency budget. +BD_TIMEOUT = 300.0 +#: The READ ceiling for one vendor answer, in KB. `fetch` truncates SILENTLY at this size, so it +#: is load-bearing arithmetic rather than a round number: MEASURED `file_size` was 175,617 bytes +#: for 5 corpus rows ⇒ **~35 KB per profile row**, and `BD_MAX_RECORDS` is set from it with +#: headroom (500 × 35 KB ≈ 17 MB against 32 MB). A truncated body is REPORTED as truncated in +#: `bd_call` — never allowed to surface as "that is not JSON". +BD_MAX_KB = 32768 +#: How long a run waits on a scrape batch the vendor DEFERRED (see `_bd_deferral`). Much shorter +#: than the corpus filter's budget because a scrape snapshot is minutes, not tens of minutes — +#: and unlike the corpus path there is no handoff to a later run, so this is the whole wait. +BD_SCRAPE_WAIT = float(os.environ.get("AIOS_BD_SCRAPE_WAIT") or 180) +BD_SCRAPE_POLL = float(os.environ.get("AIOS_BD_SCRAPE_POLL") or 10) +#: ⚠ SPEC, NOT MEASURED — off the pricing page, never returned by the API (the funds gate fires +#: BEFORE a price is quoted, and `price: 0` means "not priced", not "free"). Every surface that +#: shows a number derived from this MUST say it is an estimate. `/customer/balance` answers 403 +#: for our token, so there is no way to check a balance or a spend from here either. +BD_RECORD_PRICE_SPEC = 0.0025 + + +def bd_key(): """The key, or ''. Read fresh every call — see the module note above on why.""" - return (os.environ.get("AIOS_HIKERAPI_KEY") or "").strip() + return (os.environ.get("AIOS_BRIGHTDATA_KEY") or "").strip() -def hiker_base(): - return (os.environ.get("AIOS_HIKERAPI_BASE") or HIKER_BASE_DEFAULT).strip().rstrip("/") +def bd_base(): + return (os.environ.get("AIOS_BRIGHTDATA_BASE") or BD_BASE_DEFAULT).strip().rstrip("/") -def hiker_ready(): +def bd_ready(): """Is the paid rung configured at all? The UI reads this to say so honestly.""" - return bool(hiker_key()) + return bool(bd_key()) -def hiker_get(path, params=None): - """One authenticated GET. Returns `(payload, note)`; a non-empty `note` means it did NOT - answer, and the note is safe to show a user and safe to write to a log. +def bd_call(path, params=None, body=None): + """One authenticated vendor call. GET when `body` is None, POST otherwise. - Never raises. Every refusal shape — no key, a guarded base, a 402 out of credit, a 429, a - transport error, unparseable JSON — comes back as a note so the caller can record the attempt - and drop to the next rung. + Returns `(payload, note)`; a non-empty `note` means it did NOT answer, and the note is safe to + show a user and safe to write to a log. + + Never raises. Every refusal shape — no key, a guarded base, a 402, a 429, a transport error, + unparseable JSON — comes back as a note so the caller can record the attempt and drop to the + next rung. """ - key = hiker_key() + key = bd_key() if not key: # ⛔ THE FAIL-CLOSED PATH (C4). Named precisely, because "blocked" with no reason sends # somebody to read Instagram's status page instead of setting an env var. - return None, "AIOS_HIKERAPI_KEY is not configured — the paid rung is closed" + return None, "AIOS_BRIGHTDATA_KEY is not configured — the paid rung is closed" qs = "&".join(f"{k}={requests.utils.quote(str(v))}" for k, v in (params or {}).items() if v not in (None, "")) - url = f"{hiker_base()}{path}" + (f"?{qs}" if qs else "") + url = f"{bd_base()}{path}" + (f"?{qs}" if qs else "") + hdrs = {"Authorization": f"Bearer {key}", "Accept": "application/json"} try: - status, _final, body = fetch(url, timeout=HIKER_TIMEOUT, max_kb=8192, - headers={"x-access-key": key, "Accept": "application/json"}) + if body is None: + status, _final, raw = fetch(url, timeout=BD_TIMEOUT, max_kb=BD_MAX_KB, headers=hdrs) + else: + status, raw = fetch_json(url, body, timeout=BD_TIMEOUT, max_kb=BD_MAX_KB, + headers=hdrs) except Refused as e: # The BASE was refused by the SSRF rail — a configuration fault, not a vendor outage. - return None, f"the HikerAPI base URL was refused by the URL rail: {e}" + return None, f"the Bright Data base URL was refused by the URL rail: {e}" except Exception as e: # noqa: BLE001 - # ⚠ `type(e).__name__` only. A requests exception's str() can carry the full URL, and one - # day somebody will move the key into a query param; this line must not be what leaks it. - return None, f"HikerAPI did not answer ({type(e).__name__})" + # ⚠ `type(e).__name__` only. A requests exception's str() can carry the full URL, and the + # Authorization header is one refactor away from being a query param; this line must not + # be what leaks it. + return None, f"Bright Data did not answer ({type(e).__name__})" if status == 402: - return None, "HikerAPI answered 402 — the account is out of credit" - if status == 401 or status == 403: - return None, f"HikerAPI refused the key ({status})" + return None, "Bright Data answered 402 — the account is out of credit" + if status in (401, 403): + return None, f"Bright Data refused the key ({status})" if status == 429: - return None, "HikerAPI answered 429 — rate limited" + # ⚠ MEASURED during the discovery probe: `too_many_parallel_jobs`. The filter API has a + # concurrency cap and the probe's most important test died on it — hence every caller + # below is SERIAL by construction. + return None, "Bright Data answered 429 — too many parallel jobs; the calls are serialised" if not (200 <= status < 300): - return None, f"HikerAPI answered {status}" + return None, f"Bright Data answered {status}" + # ⛔ A BODY THAT REACHED THE READ CEILING IS A TRUNCATION, AND IT MUST SAY SO. `fetch` reads + # at most `max_kb` and returns what it got — silently. A truncated JSON document then fails + # `json.loads`, falls through to the NDJSON branch, and comes back as "answered with + # something that is not JSON": a sentence that sends somebody to read the vendor's schema + # looking for a fault that is OUR byte ceiling — after a result set that has already been + # paid for. Naming it here is the same no-silent-caps rule the row and table ceilings follow. + if len(raw) >= BD_MAX_KB * 1024: + return None, (f"Bright Data's answer exceeded this client's {BD_MAX_KB // 1024} MB read " + f"ceiling and was TRUNCATED — ask for fewer records; nothing was parsed " + f"from a partial document") + text = raw.decode("utf-8", "replace").strip() + if not text: + return None, f"Bright Data answered {status} with an empty body" try: - return json.loads(body.decode("utf-8", "replace")), "" + return json.loads(text), "" except Exception: # noqa: BLE001 - return None, "HikerAPI answered with something that is not JSON" + pass + # NDJSON is the other shape this API uses for row sets. Tried SECOND, so a genuine JSON error + # is not silently reinterpreted as a one-line NDJSON document. + rows = [] + for line in text.splitlines(): + line = line.strip() + if not line: + continue + try: + rows.append(json.loads(line)) + except Exception: # noqa: BLE001 + return None, "Bright Data answered with something that is not JSON" + return (rows, "") if rows else (None, "Bright Data answered with something that is not JSON") def _first(node, *names, default=None): @@ -1154,168 +1399,593 @@ def _first(node, *names, default=None): return default -def _hiker_profile(node, handle): - """The vendor's user object → our snapshot shape. CONFIRMED names (vendor quick-start, - 2026-08-04): pk, username, full_name, is_private, is_verified, media_count, follower_count, - following_count, biography. `external_url` is RECALLED — hence the candidates.""" - return { - "username": _first(node, "username", default=handle), - "full_name": _first(node, "full_name", "fullname", default="") or "", - "bio": _first(node, "biography", "bio", default="") or "", - "followers": _ig_int(_first(node, "follower_count", "followers", "followers_count")), - "following": _ig_int(_first(node, "following_count", "following", "followings_count")), - "posts_count": _ig_int(_first(node, "media_count", "posts_count", "post_count")), - "verified": "1" if _first(node, "is_verified", default=False) else "", - "external_url": _first(node, "external_url", "external_link", default="") or "", - # ⛔ NO `approx` KEY. These counts are exact, and carrying the anonymous rung's rounding - # tag onto them would be a lie in the other direction (R1: "drop the approx tag when - # exact"). Its ABSENCE is what tells the snapshot row it is trustworthy. - } +#: ⛔ FIELDS THAT ARE NEVER MAPPED, WHATEVER THE VENDOR SENDS. Two separate reasons, one list, +#: because the enforcement is the same: a field never collected needs no erasure path (D-24). +#: PII (the vendor's own `pii` flag): contact details are a different ORDER of privacy exposure +#: than a follower count, and `email_address` + `phone_number` change the lawful-basis analysis +#: materially. `business_email`'s own description says it "no longer exists without login!". +#: R11 (owner ruling, wave 20): NO Instagram comment-text capture. ⚠ This is not merely "do not +#: buy the Comments dataset" — MEASURED 2026-08-05, a POSTS row arrives with `latest_comments` +#: as an array of 15 comment texts WITH their authors, whether we asked or not. The ruling is +#: enforced HERE, at the map, because that is the only place it can be. +BD_NEVER_MAP = frozenset({ + "email_address", "phone_number", "business_email", "profile_image_link", + "latest_comments", "comment_user", "post_user", +}) + +#: The vendor's content vocabulary → ours. MEASURED values: profiles' `posts[].content_type` is +#: `Image`/`Reel`/`Carousel`; the Posts dataset adds `product_type` `clips`/`carousel_container`. +_BD_TYPES = {"image": "image", "photo": "image", "video": "video", "reel": "video", + "reels": "video", "clips": "video", "igtv": "video", "carousel": "carousel", + "carousel_container": "carousel", "sidecar": "carousel", "posts": "image"} + + +def _bd_type(*raw): + """The first recognisable content type among `raw`, defaulting to `image`.""" + for v in raw: + hit = _BD_TYPES.get(str(v or "").strip().lower()) + if hit: + return hit + return "image" + + +def ig_shortcode(url): + """The shortcode out of a post/reel permalink. '' when it is not one. + + The `ut_ig_posts` identity key. The vendor gives a post URL (sometimes without its trailing + slash) and a numeric `pk`; the shortcode is what both datasets agree on and what a human can + paste into a browser, so it stays the key. + """ + raw = str(url or "").strip() + if not raw: + return "" + path = urlparse(raw if "//" in raw else "https://" + raw).path.strip("/").split("/") + if len(path) >= 2 and path[0] in ("p", "reel", "reels", "tv"): + return re.sub(r"[^A-Za-z0-9_-]", "", path[1])[:40] + return "" + + +def _bd_first_url(v): + """A link-in-bio value → one string. + + ⚠ MEASURED 2026-08-05: `external_url` is an **ARRAY** on the real row + (`["http://linktr.ee/utopianevents/"]`), not the string the previous vendor returned. A dict + (`external_url_title`) is also in the family. Read through the shape rather than assuming one. + """ + if isinstance(v, list): + v = next((x for x in v if x), "") + if isinstance(v, dict): + v = _first(v, "url", "link", default="") + return str(v or "") + +def _bd_posts_count(node): + """`posts_count`, or None — **and a vendor ZERO IS DISCARDED.** -def _hiker_user_id(node): - return str(_first(node, "pk", "id", "pk_id", default="") or "") + ⛔ MEASURED 2026-08-05: the Profiles dataset returned `posts_count: 0` for BOTH probe accounts + — `inayma` (203,800 followers, 12 posts returned in the same row) and `utopian_events` (20,924 + followers, 12 posts). The POSTS dataset carries the true value for the same two accounts + (1,215 and 751), so the zero is not the account being empty; it is a measurement failure + wearing a number. Writing it would be the invented measurement this module's honest-status + contract exists to forbid — and a `_first`-style candidate list cannot help, because the + vendor DID answer, with the wrong answer. + + ⚠ THE ASYMMETRY IS DELIBERATE AND IT COSTS SOMETHING: an account that genuinely has zero posts + also reads blank. "Not read" is honest about an unknown; "0" is a claim, and on the only + evidence we have that claim is wrong 2 times out of 2. + ⛔ `len(posts)` IS NOT A SUBSTITUTE. The profile row carries the TOP 12 — a cap, not a count. + """ + v = _ig_int(_first(node, "posts_count", "media_count", "post_count")) + return None if v == 0 else v -#: instagrapi-family media_type ints. `product_type == "clips"` is a reel, which is still a video. -_HIKER_MEDIA_TYPES = {1: "image", 2: "video", 8: "carousel"} +def _bd_flag(node, *names): + """A vendor boolean → `'1'` / `''` / None. **None when the key is ABSENT or null**, which is + the distinction that matters: `is_business_account: false` is a measurement and `''` records + it; a missing key is not, and must not arrive as "false".""" + for n in names: + v = node.get(n) if isinstance(node, dict) else None + if v is None: + continue + return "1" if v is True or str(v).strip().lower() in ("true", "1", "yes") else "" + return None -def _hiker_post(m): - """One vendor media object → our post shape (the same shape `_posts_from_edges` returns, so - everything downstream is rung-agnostic). Returns None when it has no shortcode — a post that - cannot be deduped cannot be appended to a time series.""" - code = _first(m, "code", "shortcode", default="") +def _bd_list(node, *names): + """An array field → a comma-joined string, or None when it is absent/empty.""" + for n in names: + v = node.get(n) if isinstance(node, dict) else None + if isinstance(v, list) and v: + return ", ".join(str(x) for x in v if x)[:400] + return None + + +def _bd_profile(node, handle): + """A Profiles row → our snapshot shape. Every name below is MEASURED off a real row + (2026-08-05, 35 keys); the candidates guard renames, not guesses. + + ⚠ Several of these were **null on both probe rows** (`avg_engagement`, `category_name`, + `business_category_name`, `is_professional_account`, `bio_hashtags`, `post_hashtags`). They + are mapped ANYWAY — see the note on `SNAPSHOT_FIELDS`: n=2 is not evidence enough to drop a + column permanently, and history is unbuyable, so a field omitted today is lost for today. + ⚠ They ARE populated on the CORPUS (`/datasets/filter`) rows, which is a different path with + a different population; that is a reason to capture them, not a licence to promise a + scrape-side feature before D-25 measures the fill rate. + """ + out = { + "username": str(_first(node, "account", "username", default=handle) or handle), + "full_name": str(_first(node, "full_name", "profile_name", default="") or ""), + "bio": str(_first(node, "biography", "bio", default="") or ""), + "followers": _ig_int(_first(node, "followers", "follower_count")), + "following": _ig_int(_first(node, "following", "following_count")), + "posts_count": _bd_posts_count(node), + "verified": "1" if _first(node, "is_verified", default=False) else "", + "external_url": _bd_first_url(_first(node, "external_url", "external_urls", + "external_url_title")), + # ⛔ NO `approx` KEY. These counts are exact, and carrying the anonymous rung's rounding + # tag onto them would be a lie in the other direction (R1: "drop the approx tag when + # exact"). Its ABSENCE is what tells the snapshot row it is trustworthy. + "ig_id": str(_first(node, "id", "fbid", default="") or ""), + "profile_url": str(_first(node, "profile_url", "url", default="") or ""), + "avg_engagement": _first(node, "avg_engagement"), + "category": str(_first(node, "category_name", default="") or ""), + "business_category": str(_first(node, "business_category_name", default="") or ""), + "is_business": _bd_flag(node, "is_business_account"), + "is_professional": _bd_flag(node, "is_professional_account"), + "is_private": _bd_flag(node, "is_private"), + "highlights_count": _ig_int(_first(node, "highlights_count")), + "bio_hashtags": _bd_list(node, "bio_hashtags"), + "post_hashtags": _bd_list(node, "post_hashtags"), + "pronouns": str(_first(node, "pronouns", default="") or ""), + } + # ⛔ THE PII RAIL, ENFORCED HERE RATHER THAN TRUSTED. Nothing above reads a `BD_NEVER_MAP` + # field, and this asserts it stays that way after the next edit — a map is exactly the kind + # of code somebody extends in a hurry. + return {k: v for k, v in out.items() if k not in BD_NEVER_MAP} + + +def _bd_post_identity(p): + """One entry of a Profiles row's `posts[]` → our post shape. None when it has no shortcode. + + ⚠ IDENTITY ONLY — AND THAT IS THE FINDING THIS WHOLE RUNG IS SHAPED AROUND. MEASURED + 2026-08-05 across 24 posts on two accounts: `caption`, `content_type`, `id`, `image_url`, + `url` are populated 24/24, and **`likes`, `comments` and `datetime` are `None` 24/24.** So the + profile scrape can fill `ut_ig_posts` and CANNOT fill `ut_ig_post_snapshots` — the engagement + time series §3's append law exists for needs the POSTS dataset, one record per post. That is + why `postMetrics` is a separate, opt-in, ~13×-cost rung rather than a free by-product. + ⚠ `is_pinned` was `True` on all 24 — a constant, not a measurement. Not mapped. + ⚠ Blank-valued keys are OMITTED rather than written, so a later engagement pull that DOES know + `posted_at` fills it in instead of being overwritten by this rung's silence. + """ + code = ig_shortcode(p.get("url")) if isinstance(p, dict) else "" if not code: return None - raw_type = _first(m, "media_type", "type") - kind = _HIKER_MEDIA_TYPES.get(raw_type) if isinstance(raw_type, int) else None - if kind is None: - kind = str(raw_type or "").lower() or "image" - if kind not in ("image", "video", "carousel"): - kind = "video" if kind in ("clips", "igtv", "reel", "reels") else "image" - taken = _first(m, "taken_at", "taken_at_timestamp", "device_timestamp") - if isinstance(taken, (int, float)): - try: - posted = _dt.datetime.fromtimestamp(taken).strftime("%Y-%m-%d %H:%M") - except Exception: # noqa: BLE001 - posted = "" - else: # an ISO string ("2026-01-01T00:00:00+00:00") - posted = str(taken or "").replace("T", " ")[:16] - caption = _first(m, "caption_text", "caption") + out = {"shortcode": code, "url": f"https://www.instagram.com/p/{code}/", + "type": _bd_type(p.get("content_type"), p.get("type"))} + caption = _first(p, "caption", "description", default="") if isinstance(caption, dict): caption = _first(caption, "text", default="") - return { - "shortcode": str(code), - "posted_at": posted, - "type": kind, - "caption": str(caption or ""), - "url": f"https://www.instagram.com/p/{code}/", - # ⚠ NO `like_and_view_counts_disabled` CANDIDATE, however like-shaped its name is: it is - # a BOOLEAN in this family of schemas, and `_ig_int(True)` is 1 — so a post with likes - # hidden would have reported "1 like". A candidate list must only ever contain fields of - # the same TYPE as the thing it is reading. - "likes": _ig_int(_first(m, "like_count", "likes")), - "comments": _ig_int(_first(m, "comment_count", "comments")), - "views": _ig_int(_first(m, "play_count", "view_count", "video_play_count", "views")), + if caption: + out["caption"] = str(caption) + return out + + +def _bd_post_metrics(row): + """One POSTS-dataset row → the engagement half. None when it has no shortcode. + + MEASURED 2026-08-05 on three real post rows: `likes` (308 / 3,736), `num_comments` (37 / 134) + and `date_posted` (`2026-05-04T17:51:58.000Z`) all populated. + ⚠ NO VIEW COUNT CAME BACK — `video_play_count` / `video_view_count` are declared in the schema + and the KEY WAS ABSENT from every row, including a Reel. So `views` reads None and the column + stays blank, which is the honest answer; it is not folded into likes and it is not zeroed. + ⚠ The candidates below are all COUNTS OF VIEWS in different vendor typings (`video_view_count` + is declared `text`, the others `number`). A candidate list may span types only when the + MEANING is identical — never the way `like_and_view_counts_disabled`, a boolean, would have + turned "likes are hidden" into "1 like". + ⛔ `latest_comments` IS PRESENT ON THESE ROWS AND IS NEVER READ (R11 / `BD_NEVER_MAP`). + """ + if not isinstance(row, dict): + return None + code = str(_first(row, "shortcode", "content_id", default="") or "") or \ + ig_shortcode(row.get("url")) + if not code: + return None + posted = str(_first(row, "date_posted", "taken_at", default="") or "") + partner = row.get("partnership_details") + out = { + "shortcode": code, + "url": str(_first(row, "url", default=f"https://www.instagram.com/p/{code}/")), + "influencer_key": str(_first(row, "user_posted", default="") or ""), + "posted_at": posted.replace("T", " ")[:16], + "type": _bd_type(row.get("content_type"), row.get("product_type")), + "caption": str(_first(row, "description", "caption", default="") or ""), + "likes": _ig_int(_first(row, "likes", "like_count")), + "comments": _ig_int(_first(row, "num_comments", "comment_count", "comments")), + "views": _ig_int(_first(row, "video_play_count", "video_view_count", + "engagement_score_view", "play_count")), + # Sponsored-post detection. MEASURED populated (`True`, with the brand alongside) — and + # it is the one field here that answers a commercial question the counts cannot. + "paid_partnership": _bd_flag(row, "is_paid_partnership"), + "partner": (str(_first(partner, "username", "profile_id", default="") or "") + if isinstance(partner, dict) else ""), + "hashtags": _bd_list(row, "hashtags"), + "alt_text": str(_first(row, "alt_text", default="") or ""), } + # ⛔ SAME RAIL AS THE PROFILE MAP — and it matters MORE here, because a Posts row genuinely + # arrives carrying `latest_comments`: fifteen third-party comment texts with their authors, + # sent whether we asked or not (R11). + return {k: v for k, v in out.items() if k not in BD_NEVER_MAP} -def _hiker_media_items(payload): - """Unwrap a chunk answer into `(items, cursor)`. +def _bd_rows(payload): + """A vendor answer → the list of row dicts inside it, whatever envelope it arrived in. - The chunk shape is RECALLED (see the digest), so all four plausible envelopes are accepted: - a bare list, `[items, cursor]`, `{"response": {"items": [...]}}`, and `{"items": [...]}`. + MEASURED shapes: a bare list (`/v3/scrape`), NDJSON (already listified by `bd_call`), and + `{"data": [...]}` / `{"results": [...]}` on the snapshot reads. An unreadable envelope yields + NOTHING rather than a guess. """ - cursor = "" if isinstance(payload, list): - # `[items, next_cursor]` — the instagrapi chunk convention — vs. a plain list of medias. - if (len(payload) == 2 and isinstance(payload[0], list) - and isinstance(payload[1], (str, type(None)))): - return [x for x in payload[0] if isinstance(x, dict)], str(payload[1] or "") - return [x for x in payload if isinstance(x, dict)], "" + return [x for x in payload if isinstance(x, dict)] if isinstance(payload, dict): - inner = payload.get("response") if isinstance(payload.get("response"), dict) else payload - items = _first(inner, "items", "medias", "data", default=[]) - # ⛔ LOOK FOR THE CURSOR AT BOTH LEVELS. It was read from `payload` only, so a - # `{"response": {"items": [...], "next_max_id": "..."}}` envelope — where the cursor sits - # NEXT TO the items, one level in — resolved to "", the caller's `if not cursor: break` - # fired, and a `maxPosts=200` pull returned ONE chunk and reported `ok`. A green run that - # silently fetched a quarter of what was asked for is precisely the failure this module's - # honest-status contract exists to prevent, and it arrives through the RECALLED half of - # the vendor schema — which is the half that has to be read defensively at every level. - for src in (inner, payload): - cursor = str(_first(src, "next_cursor", "end_cursor", "next_page_id", - "next_max_id", default="") or "") - if cursor: - break - if isinstance(items, list): - return [x for x in items if isinstance(x, dict)], cursor - return [], cursor - - -def pull_profile_hiker(url, max_posts=24, log=print): - """The paid rung: one profile, EXACT counts, and posts the anonymous surface will not give. + for k in ("data", "results", "records", "items"): + v = payload.get(k) + if isinstance(v, list): + return [x for x in v if isinstance(x, dict)] + return [payload] if payload else [] + return [] + + +def _bd_deferral(payload): + """The snapshot id when the 'sync' endpoint DEFERRED, else ''. + + ⛔ MEASURED 2026-08-05, AND IT IS THE TRAP OF THIS WHOLE RUNG. `/v3/scrape` is documented and + named as the synchronous call, and for a small batch it is — two profile URLs came back + inline. Give it more work and it answers **200** with no rows and a note instead: + + {"snapshot_id": "sd_…", "message": "Your request is still in progress and cannot be + retrieved in this call. Use the provided Snapshot ID to track progress…"} + + Read naively that is a 200 with a body, so a parser looking for "did it error?" sails past + it, `_bd_rows` wraps the envelope as ONE unusable row, and the caller reports that the vendor + returned nothing — **while a snapshot we have already been billed for sits on the account, + finishing, and is never collected.** That is the D-26 failure shape (paid work abandoned) + arriving through the success path. + ⚠ It is a TIME threshold, not a row count: 2 URLs answered inline, 6 and 10 deferred. + """ + if isinstance(payload, dict) and payload.get("snapshot_id") and not payload.get("account"): + return str(payload["snapshot_id"]) + return "" + + +def bd_scrape(dataset_id, urls, wait=None): + """Scrape a batch. `(rows, note)`; a note means it did not answer. + + Sends the SYNC call and, when the vendor defers it (see `_bd_deferral`), **collects the + snapshot it handed back** rather than discarding it. One call carries many URLs, which is + what keeps the per-profile pacing floor from turning a 20-profile run into an hour. + """ + payload, note = bd_call(BD_PATH_SCRAPE, {"dataset_id": dataset_id}, + body=[{"url": u} for u in urls if u]) + if note: + return [], note + sid = _bd_deferral(payload) + if not sid: + return _bd_rows(payload), "" + + # --- THE DEFERRED PATH. Poll the scraper namespace (`sd_…` at `/datasets/v3/…` — crossing it + # with the corpus namespace is a flat 404 about a snapshot that is alive). + budget = BD_SCRAPE_WAIT if wait is None else float(wait) + waited = 0.0 + while True: + got, gnote = bd_call(f"{BD_PATH_SNAPSHOT}/{sid}", {"format": "json"}) + if not gnote: + rows = _bd_rows(got) + # The status document is itself JSON, so "did it deliver?" is decided by whether + # what came back looks like ROWS — never by the HTTP code. + if rows and not _bd_deferral(got) and not ( + len(rows) == 1 and str(rows[0].get("status") or "") in + ("running", "building", "collecting")): + return rows, "" + if waited >= budget: + break + time.sleep(BD_SCRAPE_POLL) + waited += BD_SCRAPE_POLL + # ⛔ NAME THE SNAPSHOT. It has been paid for and it is still finishing; a note that said only + # "no rows" would throw away both the data and the way to get it. + return [], (f"Bright Data deferred this batch to snapshot {sid} and it was not ready within " + f"{int(budget)}s — the records are collected, not lost; ask for a smaller batch " + f"or collect {sid} from the control panel") + + +def pull_profile_bd(url, max_posts=24, post_metrics=False, log=print): + """The paid rung: one profile, EXACT counts, plus the top posts the anonymous surface hides. Same return contract as `pull_profile` (`{state, profile, posts, via, note}`) so the runner treats every rung identically. `blocked` here means the VENDOR rung did not answer — the caller decides whether to drop to the anonymous ladder. + + `post_metrics=True` adds the second, PAID-PER-POST call against the Posts dataset, which is + the ONLY source of likes/comments (see `_bd_post_identity`). It is off by default because it + multiplies the bill by roughly the post count. """ handle = ig_handle(url) if not handle: return {"state": "error", "note": f"{url!r} is not an Instagram profile URL", "profile": {}, "posts": [], "via": ""} - payload, note = hiker_get(HIKER_PATH_USER, {"username": handle}) + rows, note = bd_scrape(BD_DS_PROFILES, [f"https://www.instagram.com/{handle}/"]) if note: - return {"state": "blocked", "profile": {}, "posts": [], "via": "hikerapi", + return {"state": "blocked", "profile": {}, "posts": [], "via": "brightdata", "note": note} - node = payload if isinstance(payload, dict) else {} - node = node.get("user") if isinstance(node.get("user"), dict) else node - profile = _hiker_profile(node, handle) - if profile.get("followers") is None and profile.get("posts_count") is None: + node = rows[0] if rows else {} + profile = _bd_profile(node, handle) + if profile.get("followers") is None and profile.get("following") is None: # It answered 200 with something we could not read. Say THAT — not "0 followers". - return {"state": "blocked", "profile": {}, "posts": [], "via": "hikerapi", - "note": "HikerAPI answered, but no follower/post counts were readable in it " - "(the field names may have moved — see instagram-capture.md)"} - posts, cursor, pages = [], "", 0 - user_id = _hiker_user_id(node) - while user_id and len(posts) < max_posts and pages < 20: - pages += 1 - page, mnote = hiker_get(HIKER_PATH_MEDIAS, - {"user_id": user_id, "end_cursor": cursor}) - if mnote: - note = mnote - break - items, cursor = _hiker_media_items(page) - if not items: - break - for m in items: - p = _hiker_post(m) - if p: - posts.append(p) - if not cursor: - break + # ⚠ `posts_count` is deliberately NOT part of this test: it arrives as a fabricated 0 and + # is discarded, so a row where it is the only "readable" field is a row we cannot read. + return {"state": "blocked", "profile": {}, "posts": [], "via": "brightdata", + "note": "Bright Data answered, but no follower/following counts were readable in " + "it (the field names may have moved — see instagram-capture.md)"} + posts = [] + for p in (node.get("posts") or [])[:max_posts]: + got = _bd_post_identity(p) + if got: + posts.append(got) + + if post_metrics and posts: time.sleep(min(PACE_SECONDS, 1.0)) # the vendor is paid, but it is still someone's API - posts = posts[:max_posts] + rows2, note2 = bd_scrape(BD_DS_POSTS, [p["url"] for p in posts]) + if note2: + # The engagement half refusing does NOT lose the identity half — the profile and the + # post rows still land, and the run says which part was not readable. + note = f"post metrics unavailable: {note2}" + else: + by_code = {} + for r in rows2: + got = _bd_post_metrics(r) + if got: + by_code[got["shortcode"]] = got + for p in posts: + extra = by_code.get(p["shortcode"]) + if extra: + # The metrics row is RICHER (it knows posted_at); merge it over the identity + # row, dropping keys it could not read so a blank never overwrites a value. + p.update({k: v for k, v in extra.items() if v not in (None, "")}) + if not by_code: + note = "post metrics were requested but the Posts dataset returned no rows" + # IDENTITY WITHOUT MEDIA IS STILL `partial`, on the paid rung too. The rule does not soften # because we are paying: a run that wrote a follower count and no posts must not paint green # over a posts table that did not grow. return {"state": "ok" if posts else "partial", "profile": profile, "posts": posts, - "via": "hikerapi", - "note": note or ("" if posts else "profile read; HikerAPI returned no medias")} + "via": "brightdata", + "note": note or ("" if posts else "profile read; Bright Data returned no posts")} + + +# --------------------------------------------------------------------------------------------- +# DISCOVERY — sourcing handles we do NOT already know (owner ruling R7, DEBT D-23) +# --------------------------------------------------------------------------------------------- +# The engine until now only ENRICHED a profile set somebody typed in. This queries the vendor's +# **620,000,000-record pre-collected Profiles corpus** with a real query language and returns +# handles nobody here has ever seen. MEASURED end-to-end 2026-08-04: `followers 10k–200k AND +# biography includes "floral"` returned five real profiles, one of them a verified 20.8k-follower +# Georgia/Florida floral-design company — Fisch Floral's actual market. +# +# ⛔ FIVE PROPERTIES, EACH OF THEM A MEASURED FAILURE MODE RATHER THAN A PREFERENCE: +# +# 1. **A DIFFERENT ROUTE AND A DIFFERENT NAMESPACE.** `POST /datasets/filter` — ⚠ with NO `/v3/` +# segment; `/datasets/v3/filter` is a 404 that once got written down as "the corpus is +# unreachable". Its snapshots are `snap_…` and are read at `/datasets/snapshot/…`; the +# scraper's are `sd_…` at `/datasets/v3/snapshot/…`, and the two 404 each other. +# 2. **`records_limit` IS REQUIRED.** Unbounded queries die `NOT_ENOUGH_FUNDS` (code 104, +# `per_set` billing). ⚠ And bounding is NOT sufficient: **scan time tracks PREDICATE BREADTH, +# not row count** — a `records_limit:10` query on a bare `followers > 10000` was still +# `building` 50 minutes later. So the predicate is capped too, and the runner tolerates a +# snapshot that is not ready when it looks. +# 3. **IT IS SLOW, AND THE RUN HANDS OFF RATHER THAN HOLDING A THREAD.** MEASURED delivery +# latency on the narrow query: **19.6 minutes** (`created` 12:38:00 → `delivery_time` +# 12:57:42). Blocking a worker thread for twenty minutes on a free-tier container to poll is +# the wrong shape, so a run polls for a short budget and then PERSISTS the snapshot id; the +# next run collects it. A `partial` that says "still building, the next run collects it" is +# the honest report of exactly what happened. +# 4. **PROMOTION IS MANUAL, ALWAYS (R7).** The measured result set was ~40% on-target and +# included a hashtag-aggregator account that is not a person. Auto-promoting a candidate into +# the tracked profile set would silently multiply the enrichment bill AND pollute the +# snapshot series with rows nobody chose. The `tracked` column is NEVER written here. +# 5. **SERIAL.** `429 too_many_parallel_jobs` is real and the original probe's most important +# test died on it. +# +# ⚠ THE PRICE IS NOT MEASURED AND MAY NOT BE PRESENTED AS IF IT WERE. The funds gate fires BEFORE +# the API returns a number, `price: 0` means "not priced" rather than "free", and +# `/customer/balance` answers 403 for our token — so there is no balance to read and no spend to +# report. Every estimate below is derived from the PRICING PAGE and says so. + +#: The table a discovery run writes. Upsert by handle, so re-finding a profile is free. +DISCOVER_TABLE = "ut_ig_candidates" +#: A hard ceiling on one run's ask — and it is DERIVED, not chosen. A corpus row MEASURED at +#: ~35 KB (`file_size` 175,617 for 5 rows), so 1,000 records ≈ 33 MB would have crossed +#: `BD_MAX_KB` and come back as a truncated document **after being billed**. 500 leaves real +#: headroom. ⚠ If the row size grows, this number is the thing to re-derive. +BD_MAX_RECORDS = 500 +#: How long ONE run waits on a building snapshot before handing off to the next run (see 3 above). +BD_FILTER_WAIT = float(os.environ.get("AIOS_BD_FILTER_WAIT") or 120) +BD_FILTER_POLL = float(os.environ.get("AIOS_BD_FILTER_POLL") or 15) + +#: The operator set, enumerated BY REJECTION — send a bogus one and the API's own validation error +#: lists the legal set. The cheapest kind of measurement, and it makes this list a fact. +BD_FILTER_OPS = ("=", "!=", "<", "<=", ">", ">=", "in", "not_in", "includes", "not_includes", + "array_includes", "not_array_includes", "is_null", "is_not_null") +#: Operators that take NO value (everything else requires one). +BD_NULLARY_OPS = ("is_null", "is_not_null") + +#: Fields a predicate may name. MEASURED-accepted (24 of 25 probed; **`country_code` is REJECTED** +#: by the API and is therefore absent rather than offered-and-broken). +#: ⛔ `email_address`, `phone_number` and `business_email` ARE filterable and are DELIBERATELY +#: MISSING. Selecting people BY CONTACT DETAIL across 620M records is the materially heavier +#: privacy posture D-24 flags — a different licence question from per-URL enrichment, and one the +#: owner has not been asked. A vocabulary that cannot express it cannot be asked for it by +#: accident; adding them back is a decision, not a typo. +BD_FILTER_FIELDS = ("followers", "following", "posts_count", "avg_engagement", "biography", + "category_name", "business_category_name", "is_business_account", + "is_professional_account", "is_verified", "account", "full_name", + "external_url", "bio_hashtags", "post_hashtags", "profile_url", + "related_accounts", "profile_name", "id", "fbid", "highlights_count") +#: ⭐ The three the FIND SURFACE leads with, and the reason is measurement rather than taste: +#: these are the fields seen carrying values on real CORPUS rows. `category_name` and +#: `related_accounts` are filterable and were null/empty on every row we have looked at — a filter +#: on an unpopulated field returns nothing and looks exactly like "no such influencers exist". +BD_FILTER_LEAD = ("followers", "biography", "avg_engagement") + +CANDIDATE_FIELDS = [ + field_def("handle", "Handle"), field_def("profile_url", "Profile", "url"), + field_def("full_name", "Name"), field_def("followers", "Followers"), + field_def("following", "Following"), field_def("avg_engagement", "Avg engagement"), + field_def("bio", "Bio"), field_def("external_url", "Link in bio", "url"), + field_def("verified", "Verified"), field_def("category", "Category"), + field_def("found_count", "Times found"), field_def("first_found", "First found"), + field_def("last_found", "Last found"), + # ⛔ WRITTEN BY A HUMAN, NEVER BY THIS ENGINE (R7). It is declared here so the column exists + # and can be ticked; `_candidate_row` never emits the key, and `upsert_rows` only writes the + # keys it is given — so a re-find can never un-tick somebody's decision either. + field_def("tracked", "Tracked", "checkbox"), +] + + +def clean_predicates(raw): + """Validate a discovery filter into the vendor's shape. Returns `(predicates, error)`. + + Refuses rather than coerces: a predicate naming a field the API rejects comes back as a + 400 with the field named, because the alternative — dropping it — turns "find me verified + accounts in Georgia" into "find me any account" and bills for the difference. + """ + out = [] + for p in (raw or [])[:12]: + if not isinstance(p, dict): + continue + name = _s(p.get("name") or p.get("field"), 60).strip() + op = _s(p.get("operator") or p.get("op"), 20).strip() + if name not in BD_FILTER_FIELDS: + return None, (f"{name or 'that field'!r} cannot be used to search — the searchable " + f"fields are: {', '.join(BD_FILTER_FIELDS)}") + if op not in BD_FILTER_OPS: + return None, f"{op or 'that comparison'!r} is not one of: {', '.join(BD_FILTER_OPS)}" + entry = {"name": name, "operator": op} + if op not in BD_NULLARY_OPS: + v = p.get("value") + if v is None or (isinstance(v, str) and not v.strip()): + return None, f"give a value to compare {name!r} against" + entry["value"] = v.strip() if isinstance(v, str) else v + out.append(entry) + if not out: + return None, ("add at least one condition — an empty filter matches the whole 620-million" + "-record corpus, which is the query the vendor refuses") + return out, None + + +def discover_estimate(records_limit): + """The cost preview a Find node shows BEFORE it runs. **SPEC, never measured** — see the + section header. Returned as structured data so the UI cannot accidentally drop the caveat.""" + n = max(0, int(records_limit or 0)) + return {"records": n, "usd": round(n * BD_RECORD_PRICE_SPEC, 4), + "unitUsd": BD_RECORD_PRICE_SPEC, "basis": "SPEC", + "note": "estimated from Bright Data's published dataset rate — the API never returns " + "a price before a run, and this account's token cannot read a balance"} + + +def bd_filter_start(predicates, operator="and", records_limit=5, dataset_id=BD_DS_PROFILES): + """Start ONE corpus query. Returns `(snapshot_id, note)`. + + ⚠ ALWAYS THE COMPOUND `{operator, filters:[…]}` SHAPE, even for a single condition. A bare + `{name, operator, value}` is a plausible-looking second shape that has never been sent from + here, and a one-element `filters` list is a trivial extension of the three-element body that + HAS been measured end-to-end. One shape, and it is the tested one. + """ + body = {"dataset_id": dataset_id, "records_limit": int(records_limit), + "filter": {"operator": operator, "filters": list(predicates)}} + payload, note = bd_call(BD_PATH_FILTER, body=body) + if note: + return "", note + sid = str((payload or {}).get("snapshot_id") or "") if isinstance(payload, dict) else "" + if not sid: + return "", "Bright Data accepted the search but named no snapshot to collect it from" + return sid, "" + + +def bd_filter_status(snapshot_id): + """`(status, size, note)` for a corpus snapshot. `status` ∈ building | ready | failed | ''.""" + payload, note = bd_call(f"{BD_PATH_FILTER_SNAPSHOT}/{snapshot_id}") + if note: + return "", 0, note + d = payload if isinstance(payload, dict) else {} + status = str(d.get("status") or "") + err = str(d.get("error") or "") + if status == "failed" and err: + # NOT_ENOUGH_FUNDS is the one everybody will hit; say what it means, not just its name. + extra = (" — the matched set is too large for this account's balance; narrow the " + "conditions or lower the limit" if "FUNDS" in err.upper() else "") + return status, 0, f"the search failed: {err}{extra}" + return status, int(d.get("dataset_size") or 0), "" + + +def bd_filter_rows(snapshot_id): + """The rows of a READY corpus snapshot. `(rows, note)`. + + ⚠ `/download` answered *"Snapshot is building. Try again in a few minutes"* while the status + endpoint ALREADY said `ready` — delivery lags readiness by minutes. So a download that does + not parse as rows is reported as not-yet-collectable rather than as an error. + """ + payload, note = bd_call(f"{BD_PATH_FILTER_SNAPSHOT}/{snapshot_id}/download", + {"format": "json"}) + if note: + return [], note + rows = _bd_rows(payload) + if not rows: + return [], "the search is ready but its rows are not downloadable yet — the vendor's " \ + "delivery lags its own `ready` status by minutes" + return rows, "" -def pull_profile(url, max_posts=24, log=print, tier="anonymous", fallback=True): +def _candidate_row(row, stamp): + """One corpus row → a `ut_ig_candidates` row. None when it has no handle. + + ⛔ NEVER EMITS `tracked` OR `found_count`. `tracked` is the human's decision (R7) and + `found_count` is arithmetic the runner does against what is already stored — writing either + from here would overwrite a person's choice or reset a counter to 1 on every re-find. + """ + if not isinstance(row, dict): + return None + handle = str(_first(row, "account", "username", default="") or "").strip() + if not handle: + return None + return { + "handle": handle, + "profile_url": str(_first(row, "profile_url", "url", + default=f"https://www.instagram.com/{handle}/")), + "full_name": str(_first(row, "full_name", "profile_name", default="") or ""), + "followers": _s(_ig_int(_first(row, "followers"))), + "following": _s(_ig_int(_first(row, "following"))), + # ⭐ POPULATED ON CORPUS ROWS and null on scrape rows — the two paths differ, and this is + # the path where it carries values (measured on all five of the 2026-08-04 result set). + "avg_engagement": _s(_first(row, "avg_engagement", default="")), + "bio": _s(_first(row, "biography", "bio", default=""), 500), + "external_url": _s(_bd_first_url(_first(row, "external_url", "external_urls")), 300), + "verified": "1" if _first(row, "is_verified", default=False) else "", + "category": _s(_first(row, "category_name", "business_category_name", default="")), + "last_found": stamp, + } + + +def pull_profile(url, max_posts=24, log=print, tier="anonymous", fallback=True, + post_metrics=False): """Everything readable about one public profile, cheapest-honest rung last. Returns `{state, profile, posts, via, note}` with state ∈ ok | partial | blocked | error. `partial` means the identity was read but the media was not — which is the outcome the anonymous surface most often gives, and saying so is the point. - **RUNG 0 IS THE PAID ONE (R1's hybrid).** With `tier="hiker"` HikerAPI is tried FIRST and, - when it answers, this returns exact counts with no `approx` tag. When it does not answer the - attempt is RECORDED and the anonymous ladder runs underneath it — that is what "fail-closed - on the key, and the anonymous rung still works" means in C4. + **RUNG 0 IS THE PAID ONE (R1's hybrid).** With `tier="brightdata"` the vendor is tried FIRST + and, when it answers, this returns exact counts with no `approx` tag. When it does not answer + the attempt is RECORDED and the anonymous ladder runs underneath it — that is what + "fail-closed on the key, and the anonymous rung still works" means in C4. `fallback=False` turns that safety net off on purpose: it means *"exact numbers or nothing"*. An influencer table where some rows are exact and some are `og:description` roundings, with @@ -1329,13 +1999,13 @@ def pull_profile(url, max_posts=24, log=print, tier="anonymous", fallback=True): "profile": {}, "posts": [], "via": ""} attempts = [] - if tier == "hiker": - paid = pull_profile_hiker(url, max_posts=max_posts, log=log) + if clean_tier(tier) == "brightdata": + paid = pull_profile_bd(url, max_posts=max_posts, post_metrics=post_metrics, log=log) if paid["state"] in ("ok", "partial"): return paid - attempts.append(f"hikerapi:{_s(paid.get('note'), 90)}") + attempts.append(f"brightdata:{_s(paid.get('note'), 90)}") if not fallback: - return {"state": "blocked", "profile": {}, "posts": [], "via": "hikerapi", + return {"state": "blocked", "profile": {}, "posts": [], "via": "brightdata", "note": "the paid rung did not answer and the anonymous fallback is turned " f"off for this automation ({paid.get('note') or 'blocked'})"} time.sleep(PACE_SECONDS) @@ -1458,16 +2128,35 @@ def _paginate(user_id, cursor, want, log=print): # RUNNERS # --------------------------------------------------------------------------------------------- -def cap_note(capped): - """The sentence a cap breach adds to a run summary. `capped` = [(table_key, rows_lost), ...]. +def cap_note(capped, missing=()): + """The sentence(s) a cap breach adds to a run summary. + + `capped` = `[(table_key, rows_lost), …]` — the ROW ceiling was hit. + `missing` = `[table_key, …]` — the TABLE ceiling was hit: the database could not + be created at all. ⛔ IT NAMES THE TABLE. "142 rows skipped" sends somebody to look at the source page; "the ut_ig_post_snapshots database is FULL" sends them to the actual problem. A loud failure that does not say WHERE is only marginally better than a silent one. + + ⛔ AND THE TABLE CEILING IS NOW AS LOUD AS THE ROW ONE (closes DEBT D-11). `ut_ensure` refused + SILENTLY at `MAX_UT_TABLES`: it returned a key for a database it had not created, the + runners' `if tgt is not None` write guard then skipped that bucket, and the run reported + success over a database that does not exist. Exactly the silent-stop failure the row cap + already had, one level up — and harder to spot, because the table is not there to look at. """ - return "; ".join( - f"⚠ the {k} database is FULL ({row_cap(k):,} rows) — {n} row{'' if n == 1 else 's'} " - f"from this run were NOT written" for k, n in capped if n) + out = [f"⚠ the {k} database is FULL ({row_cap(k):,} rows) — {n} row{'' if n == 1 else 's'} " + f"from this run were NOT written" for k, n in (capped or []) if n] + out += [f"⚠ the {k} database could NOT BE CREATED — this workspace is at its " + f"{MAX_UT_TABLES}-database limit, so nothing from this run reached it" + for k in (missing or [])] + return "; ".join(out) + + +def ut_missing(rt, *keys): + """Which of `keys` do NOT exist after an `ut_ensure` — the table-ceiling detector (D-11).""" + have = ut_all(rt) + return [k for k in keys if k and k not in have] def run_scrape_db(rt, defn, username="automation", log=print): @@ -1537,7 +2226,9 @@ def run_scrape_db(rt, defn, username="automation", log=print): f"{counts['unchanged']} unchanged, {counts['orphans']} no longer on the page " f"(kept)") capped = [(table_key, counts.get("capped", 0))] - note = cap_note(capped) + missing = [] if dry else ut_missing(rt, table_key) + counts["missing_tables"] = len(missing) + note = cap_note(capped, missing) if note: summary += f" — {note}" steps["write"] = "partial" @@ -1546,7 +2237,8 @@ def run_scrape_db(rt, defn, username="automation", log=print): steps["write"] = "skipped" elif not note: steps["write"] = "ok" - state = "partial" if (counts.get("capped") or counts.get("skipped") or dry) else "ok" + state = "partial" if (counts.get("capped") or counts.get("skipped") or missing + or dry) else "ok" log(f"[aios-auto] scrape_db {defn.get('id')} -> {table_key}: {summary}") return (state, summary, counts, affected, steps) @@ -1558,12 +2250,15 @@ def run_field_instagram(rt, defn, username="automation", log=print): timestamped row to each of the three IG tables.""" cfg = defn.get("config") or {} table_key, fkey = cfg.get("targetTable"), cfg.get("fieldKey") - tier = cfg.get("tier") if cfg.get("tier") in TIERS else "anonymous" + tier = clean_tier(cfg.get("tier")) or "anonymous" + paid = tier == "brightdata" fallback = not cfg.get("noFallback") + post_metrics = bool(cfg.get("postMetrics")) dry = bool(cfg.get("dryRun")) steps = {"trigger": "ok", "source": "idle", "capture": "idle", - "capture_hiker": "idle" if tier == "hiker" else "skipped", - "capture_anon": "idle" if (tier != "hiker" or fallback) else "skipped", + "capture_paid": "idle" if paid else "skipped", + "capture_anon": "idle" if (not paid or fallback) else "skipped", + "capture_metrics": "idle" if post_metrics else "skipped", "write": "idle"} t = ut_get(rt, table_key) if not t: @@ -1584,19 +2279,21 @@ def run_field_instagram(rt, defn, username="automation", log=print): post_key = ut_ensure(rt, "IG posts", POST_FIELDS, username, key="ut_ig_posts") ps_key = ut_ensure(rt, "IG post snapshots", POST_SNAPSHOT_FIELDS, username, key="ut_ig_post_snapshots") + missing = [] if dry else ut_missing(rt, snap_key, post_key, ps_key) snaps = dict((ut_get(rt, snap_key) or {}).get("rows") or {}) posts = dict((ut_get(rt, post_key) or {}).get("rows") or {}) psnaps = dict((ut_get(rt, ps_key) or {}).get("rows") or {}) counts = {"profiles": 0, "ok": 0, "partial": 0, "blocked": 0, "error": 0, - "posts": 0, "new_posts": 0, "paid": 0, "capped": 0} + "posts": 0, "new_posts": 0, "paid": 0, "capped": 0, "metrics": 0, + "missing_tables": len(missing)} cells, affected, notes = {}, [], [] # ⛔ ACCUMULATE HERE, UPSERT ONCE PER TABLE AFTER THE LOOP. This used to call `upsert_rows` # once per POST, which is O(existing) per call — survivable only while the cap was 5000 rows. # `MAX_UT_IG_ROWS` makes the same loop hundreds of millions of dict copies, i.e. an automation # that no longer finishes. **Raising a cap and batching its writer are ONE change.** (W19-C.) in_snaps, in_posts, in_psnaps = [], [], [] - hiker_tried = hiker_answered = anon_tried = anon_answered = False + paid_tried = paid_answered = anon_tried = anon_answered = False targets = [(rid, str(r.get(url_field, "") or "").strip()) for rid, r in rows.items() if str(r.get(url_field, "") or "").strip()] for i, (rid, url) in enumerate(targets): @@ -1604,15 +2301,15 @@ def run_field_instagram(rt, defn, username="automation", log=print): time.sleep(PACE_SECONDS) # ≥2 s between profiles (R7) counts["profiles"] += 1 res = pull_profile(url, max_posts=cfg.get("maxPosts") or 24, log=log, - tier=tier, fallback=fallback) + tier=tier, fallback=fallback, post_metrics=post_metrics) pulled = _iso() via = res.get("via") or "" read_ok = res["state"] in ("ok", "partial") # WHICH RUNG ANSWERED — tracked per profile so the canvas's rung dots are a measurement. - if tier == "hiker": - hiker_tried = True - if via == "hikerapi" and read_ok: - hiker_answered = True + if paid: + paid_tried = True + if via == "brightdata" and read_ok: + paid_answered = True counts["paid"] += 1 elif fallback: anon_tried = True @@ -1623,25 +2320,50 @@ def run_field_instagram(rt, defn, username="automation", log=print): if read_ok: counts["ok" if res["state"] == "ok" else "partial"] += 1 prof = res["profile"] - in_snaps.append({ + # ⚠ A SNAPSHOT ROW IS APPEND-KEYED (`@`), so every key is written + # every time and a blank is unambiguous: it means THIS PULL did not read it. That is + # the opposite of the identity rows below, which are upserted and therefore omit + # blanks so a cheap rung cannot erase an expensive one's value. + snap_row = { "snapshot_key": f"{prof['username']}@{pulled}", "influencer_key": prof["username"], "pulled_at": pulled, - "followers": _s(prof.get("followers")), "following": _s(prof.get("following")), - "posts_count": _s(prof.get("posts_count")), - "full_name": _s(prof.get("full_name")), - "bio": _s(prof.get("bio"), 500), "verified": _s(prof.get("verified")), "source": _s(res.get("via")), "approx": _s(prof.get("approx")), - "external_url": _s(prof.get("external_url"), 300)}) + "bio": _s(prof.get("bio"), 500), + "external_url": _s(prof.get("external_url"), 300), + } + for fd in SNAPSHOT_FIELDS: + k = fd["key"] + if k not in snap_row: + snap_row[k] = _s(prof.get(k), 400) + in_snaps.append(snap_row) for p in res.get("posts") or []: - in_posts.append({ - "shortcode": p["shortcode"], "influencer_key": prof["username"], - "posted_at": _s(p.get("posted_at")), "type": _s(p.get("type")), - "caption": _s(p.get("caption"), 800), "url": _s(p.get("url"), 300)}) - in_psnaps.append({ - "post_snapshot_key": f"{p['shortcode']}@{pulled}", - "shortcode": p["shortcode"], "pulled_at": pulled, - "likes": _s(p.get("likes")), "comments": _s(p.get("comments")), - "views": _s(p.get("views"))}) + # ⚠ A BLANK IS OMITTED, NOT WRITTEN. `posted_at` / `caption` / `type` are + # readable on some rungs and not others — the Bright Data PROFILE row carries + # post identity with `datetime: None` (measured 24/24), while the engagement rung + # knows `date_posted`. `upsert_rows` writes exactly the keys it is handed, so + # sending "" would let a cheap run ERASE what an expensive one learned. + ident = {"shortcode": p["shortcode"], "influencer_key": prof["username"], + "url": _s(p.get("url"), 300)} + for k, n in (("posted_at", 200), ("type", 200), ("caption", 800), + ("paid_partnership", 8), ("partner", 120), ("hashtags", 400), + ("alt_text", 400)): + if p.get(k): + ident[k] = _s(p.get(k), n) + in_posts.append(ident) + # ⛔ AN ENGAGEMENT SNAPSHOT IS APPENDED ONLY WHEN SOMETHING WAS MEASURED. The + # post series is the append table that FILLS (maxPosts rows per profile per + # pull), and with the paid engagement rung OFF every one of those rows would + # carry three blanks — pure noise, eating a 200k ceiling and drawing a chart of + # nothing. A row in a time series should mean "this was true then"; a row that + # means "nobody looked" belongs nowhere. + metrics = {k: p.get(k) for k in ("likes", "comments", "views")} + if any(v is not None for v in metrics.values()): + in_psnaps.append({ + "post_snapshot_key": f"{p['shortcode']}@{pulled}", + "shortcode": p["shortcode"], "pulled_at": pulled, + "likes": _s(metrics["likes"]), "comments": _s(metrics["comments"]), + "views": _s(metrics["views"])}) + counts["metrics"] += 1 counts["posts"] += len(res.get("posts") or []) detail = f"{prof.get('followers') or '?'} followers" if prof.get("approx"): @@ -1706,20 +2428,35 @@ def run_field_instagram(rt, defn, username="automation", log=print): cap_state = "partial" if (counts["blocked"] or counts["error"] or counts["partial"]) else "ok" steps["capture"] = cap_state - steps["capture_hiker"] = ("ok" if hiker_answered - else "blocked" if hiker_tried else "skipped") + steps["capture_paid"] = ("ok" if paid_answered + else "blocked" if paid_tried else "skipped") steps["capture_anon"] = ("ok" if anon_answered else "blocked" if anon_tried else "skipped") + # ⚠ MEASURED, LIKE EVERY OTHER DOT: it is `ok` only if an engagement row was actually + # appended. "It was switched on" is not the same fact as "it answered", and painting the + # second from the first is the fabrication `node_status` refuses to make. + # ⚠ AND `blocked` IS A CLAIM ABOUT THE VENDOR, so it needs something to have been ASKED. A + # run that found no posts to enrich did not have a rung refuse it — nothing was requested — + # so that reads `skipped`, the same word an off switch earns. + steps["capture_metrics"] = ("ok" if counts["metrics"] + else "blocked" if (post_metrics and counts["posts"]) + else "skipped") summary = (f"{read}/{counts['profiles']} profiles read, {counts['posts']} posts " f"({counts['new_posts']} new)") if counts["paid"]: - summary += f", {counts['paid']} exact via HikerAPI" + summary += f", {counts['paid']} exact via Bright Data" + if counts["metrics"]: + summary += f", {counts['metrics']} post engagement snapshots" + elif post_metrics and counts["posts"]: + # ⚠ ASKED FOR AND NOT DELIVERED IS ITS OWN SENTENCE. Silence here would read as "there + # was no engagement", which is a claim about Instagram rather than about our run. + summary += ", no post engagement was readable" if counts["partial"]: summary += f", {counts['partial']} profile-only (posts not readable)" if counts["blocked"]: summary += f", {counts['blocked']} blocked" - note = cap_note(capped) + note = cap_note(capped, missing) if note: summary += f" — {note}" state = "partial" if state != "error" else state @@ -1749,7 +2486,207 @@ def _auto_url_field(table, fkey): return "" -RUNNERS = {"scrape_db": run_scrape_db, "field_instagram": run_field_instagram} +def run_discover_instagram(rt, defn, username="automation", log=print): + """Automation #3 (owner ruling R7 / D-23): FIND handles nobody here has typed in. + + Two-phase by construction — see the DISCOVERY section header. A run either STARTS a corpus + query and hands its snapshot id to the next run, or COLLECTS one a previous run started. + Every outcome is a sentence about what actually happened; none of them is a green zero. + """ + cfg = defn.get("config") or {} + dry = bool(cfg.get("dryRun")) + limit = int(cfg.get("recordsLimit") or 5) + preds = list(cfg.get("predicates") or []) + auto_id = str(defn.get("id") or "") + steps = {"trigger": "ok", "find": "idle", "collect": "idle", "write": "idle"} + counts = {"asked": limit, "found": 0, "new": 0, "seen_again": 0, "capped": 0, + "missing_tables": 0} + + if not bd_ready(): + # ⛔ THE FAIL-CLOSED PATH (C4). Discovery has NO anonymous rung to drop to — the corpus is + # the vendor's — so this is where the run stops, saying which env var is missing. + steps["find"] = "blocked" + return ("partial", "AIOS_BRIGHTDATA_KEY is not configured — profile search is closed " + "(nothing was searched and nothing was billed)", counts, [], steps) + + pending = str((defn.get("state") or {}).get("pendingSnapshot") or "") + if not pending: + if dry: + est = discover_estimate(limit) + steps["find"] = steps["write"] = "skipped" + return ("partial", + f"DRY RUN (the Write step is turned off) — would search for up to {limit} " + f"profile{'' if limit == 1 else 's'} matching " + f"{_predicate_sentence(preds, cfg.get('operator'))}. Estimated cost " + f"${est['usd']} (ESTIMATE — {est['note']})", counts, [], steps) + sid, note = bd_filter_start(preds, cfg.get("operator") or "and", limit) + if note: + steps["find"] = "blocked" + return ("error", f"the search was not started — {note}", counts, [], steps) + pending = sid + # ⛔ LOG THE ID *BEFORE* PERSISTING IT, and the order is the whole point. `set_state` goes + # through `rt.update`, which can RAISE on an unavailable store — and that exception + # becomes an error run, so a `log()` placed after it never executes. The snapshot would + # then exist, be billed, and have its id in neither the store nor the logs. Logging first + # means the worst case is still recoverable by a human reading the Space output. + log(f"[aios-auto] discover {auto_id}: started {sid}") + # PERSIST BEFORE POLLING. A snapshot the vendor is already building does not stop + # existing because this process dies thirty seconds later, and a lost id is a set we + # paid attention to and can never collect. + set_state(rt, auto_id, {"pendingSnapshot": sid, "pendingSince": _iso()}) + steps["find"] = "ok" + + waited, status, size, note = 0.0, "", 0, "" + while True: + status, size, note = bd_filter_status(pending) + if note: + steps["collect"] = "error" + set_state(rt, auto_id, {"pendingSnapshot": None, "pendingSince": None}) + return ("error", note, counts, [], steps) + if status != "building" or waited >= BD_FILTER_WAIT: + break + time.sleep(BD_FILTER_POLL) + waited += BD_FILTER_POLL + + if status == "building": + # ⚠ THE HANDOFF, AND IT IS A SUCCESSFUL OUTCOME OF A SORT. Measured build latency is ~20 + # minutes; holding a worker thread that long on a free-tier container to poll would be + # the wrong shape. Say plainly that it is still running and who collects it. + steps["collect"] = "partial" + return ("partial", + f"the search is still running at Bright Data ({pending}) — searches take about " + f"20 minutes, and the NEXT run of this automation collects it. Nothing is lost " + f"and nothing is re-billed", counts, [], steps) + if status != "ready": + steps["collect"] = "error" + set_state(rt, auto_id, {"pendingSnapshot": None, "pendingSince": None}) + return ("error", f"the search ended as {status or 'unreadable'} and returned nothing", + counts, [], steps) + + rows, dnote = bd_filter_rows(pending) + if dnote: + # Delivery lags `ready` by minutes (measured). Keep the id; the next run collects it. + steps["collect"] = "partial" + return ("partial", f"the search finished with {size} match" + f"{'' if size == 1 else 'es'} but {dnote}", counts, [], steps) + set_state(rt, auto_id, {"pendingSnapshot": None, "pendingSince": None}) + steps["collect"] = "ok" + + stamp = _iso() + incoming = [c for c in (_candidate_row(r, stamp) for r in rows) if c] + counts["found"] = len(incoming) + # ⚠ COUNT THE ROWS WE COULD NOT USE. A corpus row with no handle cannot be a candidate, and + # dropping it silently means "the vendor delivered 50 and we kept 3" reads identically to + # "the vendor delivered 3". It also catches the shape where an error document comes back + # down the rows path and parses as one unusable row instead of an error. + counts["dropped"] = max(0, len(rows) - len(incoming)) + label = cfg.get("targetLabel") or "IG candidates" + table_key = (ut_key_for(label, cfg.get("targetTable") or DISCOVER_TABLE) if dry + else ut_ensure(rt, label, CANDIDATE_FIELDS, username, + key=cfg.get("targetTable") or DISCOVER_TABLE)) + existing = dict((ut_get(rt, table_key) or {}).get("rows") or {}) + # `found_count` is ARITHMETIC OVER WHAT IS STORED, not a value from the vendor — re-finding a + # profile is the signal that it keeps matching, so the counter grows instead of resetting. + # `first_found` is written only when the handle is new, so it never moves. + seen = {str((r or {}).get("handle") or "").strip(): r for r in existing.values()} + for c in incoming: + prev_row = seen.get(c["handle"]) + if prev_row: + counts["seen_again"] += 1 + c["found_count"] = str((_ig_int(prev_row.get("found_count")) or 0) + 1) + else: + counts["new"] += 1 + c["found_count"] = "1" + c["first_found"] = stamp + merged, mc = upsert_rows(existing, incoming, "handle", cap=row_cap(table_key)) + counts["capped"] = mc["capped"] + missing = [] if dry else ut_missing(rt, table_key) + counts["missing_tables"] = len(missing) + if not dry and not missing: + ut_write_rows(rt, table_key, merged) + steps["write"] = "ok" + elif dry: + steps["write"] = "skipped" + + affected = [rid for rid, r in merged.items() + if str(r.get("handle")) in {c["handle"] for c in incoming}][:200] + est = discover_estimate(counts["found"]) + summary = (f"{counts['found']} profile{'' if counts['found'] == 1 else 's'} found — " + f"{counts['new']} new, {counts['seen_again']} seen before. Est. cost " + f"${est['usd']} (ESTIMATE, not a billed figure). None is tracked until somebody " + f"ticks it") + if counts["dropped"]: + summary += (f". ⚠ {counts['dropped']} row{'' if counts['dropped'] == 1 else 's'} the " + f"search returned had no handle and could not be used") + cnote = cap_note([(table_key, counts["capped"])], missing) + if cnote: + summary += f" — {cnote}" + steps["write"] = "partial" + if dry: + summary = f"DRY RUN (the Write step is turned off) — would have written: {summary}" + state = "partial" if (dry or counts["capped"] or missing or not counts["found"]) else "ok" + log(f"[aios-auto] discover {auto_id} -> {table_key}: {summary}") + return (state, summary, counts, affected, steps) + + +def _predicate_sentence(preds, operator="and"): + """A predicate list as something a person can read back. Used in summaries and the canvas.""" + joiner = " or " if str(operator or "").lower() == "or" else " and " + parts = [] + for p in preds or []: + v = p.get("value") + parts.append(f"{p.get('name')} {p.get('operator')}" + + ("" if v is None else f" {v}")) + return joiner.join(parts) or "no conditions" + + +RUNNERS = {"scrape_db": run_scrape_db, "field_instagram": run_field_instagram, + "discover_instagram": run_discover_instagram} + + +# --------------------------------------------------------------------------------------------- +# THE SOURCE REGISTRY (DEBT D-9's seam, wave-20 item 6b) +# --------------------------------------------------------------------------------------------- +# WHY THIS EXISTS BEFORE THERE IS A SECOND SOURCE. The vendor swap that produced it (HikerAPI → +# Bright Data) touched a dozen places: a tier name, two node ids, a config flag, a readiness +# boolean on the wire, four client strings and two gate sections. That is what a hard-coded +# vendor costs, and TikTok (D-9) would have paid it again from scratch. +# +# So a SOURCE is declared once — what it is called, which vendor answers it, and which of the +# three verbs it can do — and the surfaces read the declaration instead of naming a vendor: +# +# probe "is this configured?" -> the honest readiness bit the UI shows +# capture enrich a handle we know -> `pull_profile`-shaped +# discover find handles we do not -> the corpus query +# +# ⚠ A SOURCE DECLARES ONLY WHAT IT CAN ACTUALLY DO. `discover: None` is not a gap to fill in +# later; it is the honest statement that this source has no discovery route, and a surface that +# offers one anyway is offering a button that must refuse. +SOURCES = { + "instagram": { + "key": "instagram", "label": "Instagram", "vendor": "Bright Data", + "probe": bd_ready, + "capture": pull_profile, + "discover": bd_filter_start, + "captureKind": "field_instagram", + "discoverKind": "discover_instagram", + "tiers": TIERS, + }, + # D-9 (TikTok) lands here as one more entry: a new field map and a new `capture`, with the + # canvas, the append tables, the caps and the honest-status contract already in place. +} + + +def source_status(): + """`[{key,label,vendor,ready,canDiscover}]` — what the surface says about each source. + + ⚠ A BOOLEAN, NEVER THE KEY (the wire rule the `hikerReady` bit already followed): a surface + needs exactly one bit to say "the paid rung is not configured" honestly, and shipping the + credential to a browser would put a billable secret in every user's devtools. + """ + return [{"key": s["key"], "label": s["label"], "vendor": s["vendor"], + "ready": bool(s["probe"]()), "canDiscover": bool(s.get("discover"))} + for s in SOURCES.values()] # --------------------------------------------------------------------------------------------- @@ -1775,13 +2712,17 @@ NODE_STATES = ("idle", "ok", "partial", "error", "blocked", "skipped") #: deliberate answer rather than an omission: a "Fetch the page" step that can be turned off is #: not an automation with a disabled step, it is a broken automation with a lie on it. The ones #: here are all REAL — each changes what the next run does: -#: schedule the trigger fires on its cron, or only by hand -#: hiker the paid rung is reached for, or it is not (this is the one that spends money) -#: fallback the anonymous ladder catches a refused paid rung, or the run says `blocked` -#: instead of quietly writing an approximate number -#: write DRY RUN — read everything, compute the counts, write nothing anywhere -NODE_TOGGLES = {"trigger": "schedule", "capture_hiker": "hiker", - "capture_anon": "fallback", "write": "write"} +#: schedule the trigger fires on its cron, or only by hand +#: paid the paid rung is reached for, or it is not (this is the one that spends money) +#: fallback the anonymous ladder catches a refused paid rung, or the run says `blocked` +#: instead of quietly writing an approximate number +#: postMetrics likes/comments per post are bought, or the engagement series does not grow — +#: the expensive one, because it costs a vendor record PER POST rather than per +#: profile (measured: the profile row carries post identity and no engagement) +#: write DRY RUN — read everything, compute the counts, write nothing anywhere +NODE_TOGGLES = {"trigger": "schedule", "capture_paid": "paid", + "capture_anon": "fallback", "capture_metrics": "postMetrics", + "write": "write"} def _cron_label(cron): @@ -1823,43 +2764,79 @@ def graph(defn): edges = [] if defn.get("kind") == "field_instagram": - tier = cfg.get("tier") if cfg.get("tier") in TIERS else "anonymous" - paid = tier == "hiker" + paid = clean_tier(cfg.get("tier")) == "brightdata" fb = not cfg.get("noFallback") anon_on = (not paid) or fb + metrics_on = bool(cfg.get("postMetrics")) + max_posts = cfg.get("maxPosts") or 24 nodes += [ node("source", "source", "Profile set", cfg.get("targetTable") or "No database", 1, panel="source", detail=f"URL column: {cfg.get('urlField')}" if cfg.get("urlField") else "URL column: the one the field is bound to"), node("capture", "branch", "Capture", - "HikerAPI, then anonymous" if paid else "Anonymous only", 2, panel="capture", - detail=f"Up to {cfg.get('maxPosts') or 24} posts per profile"), - node("capture_hiker", "capture", "HikerAPI", - "Exact counts, full posts" if paid else "Off — the paid rung is not used", + "Bright Data, then anonymous" if paid else "Anonymous only", 2, panel="capture", + detail=f"Up to {max_posts} posts per profile"), + node("capture_paid", "capture", "Bright Data", + "Exact counts, top posts" if paid else "Off — the paid rung is not used", 3, row=-1, panel="capture", on=paid, - detail="" if hiker_ready() else "No AIOS_HIKERAPI_KEY is configured"), + detail="" if bd_ready() else "No AIOS_BRIGHTDATA_KEY is configured"), node("capture_anon", "capture", "Anonymous", "Approximate counts, $0" if anon_on else "Off — exact numbers or nothing", 3, row=1, panel="capture", on=anon_on, detail="Local egress only — Instagram blocks datacenters"), + # ⚠ ITS OWN NODE BECAUSE IT IS ITS OWN BILL. The profile row carries post IDENTITY + # and no engagement (measured), so likes/comments are a SECOND vendor call per post. + # A switch that multiplies a run's cost by the post count deserves to be visible on + # the canvas rather than buried in a config panel. + node("capture_metrics", "capture", "Post engagement", + "Likes and comments per post" if metrics_on + else "Off — no likes/comments are bought", + 4, panel="capture", on=metrics_on, + detail=(f"~{max_posts}x the records of a profile-only run" + if metrics_on else + "ut_ig_post_snapshots only grows while this is on")), node("write", "write", "Write", - cfg.get("targetTable") or "No database", 4, panel="write", + cfg.get("targetTable") or "No database", 5, panel="write", on=not cfg.get("dryRun"), detail="+ ut_ig_snapshots · ut_ig_posts · ut_ig_post_snapshots"), ] edges = [{"from": "trigger", "to": "source", "label": ""}, {"from": "source", "to": "capture", "label": ""}, - {"from": "capture", "to": "capture_hiker", "label": "paid"}, + {"from": "capture", "to": "capture_paid", "label": "paid"}, {"from": "capture", "to": "capture_anon", "label": "fallback"}, - {"from": "capture_hiker", "to": "write", "label": ""}, - {"from": "capture_anon", "to": "write", "label": ""}] + {"from": "capture_paid", "to": "capture_metrics", "label": ""}, + {"from": "capture_anon", "to": "capture_metrics", "label": ""}, + {"from": "capture_metrics", "to": "write", "label": ""}] # When there is no paid rung the anonymous one is the ONLY rung, so it must not carry a # switch that would leave the automation with nothing to run. if not paid: for n in nodes: if n["id"] == "capture_anon": n["toggle"] = "" + elif defn.get("kind") == "discover_instagram": + limit = int(cfg.get("recordsLimit") or 0) + est = discover_estimate(limit) + pending = str((defn.get("state") or {}).get("pendingSnapshot") or "") + nodes += [ + node("find", "source", "Find profiles", + _predicate_sentence(cfg.get("predicates"), cfg.get("operator"))[:60], 1, + panel="find", + detail=(f"Up to {limit} profiles · est. ${est['usd']} (ESTIMATE)" + if bd_ready() + else "No AIOS_BRIGHTDATA_KEY is configured — search is closed")), + node("collect", "capture", "Collect results", + f"Building: {pending}" if pending else "Searches take about 20 minutes", 2, + panel="find", + detail="A run that finds it still building hands off to the next run"), + node("write", "write", "Write candidates", + cfg.get("targetTable") or DISCOVER_TABLE, 3, panel="write", + on=not cfg.get("dryRun"), + detail="Nothing is tracked until somebody ticks it"), + ] + edges = [{"from": "trigger", "to": "find", "label": ""}, + {"from": "find", "to": "collect", "label": ""}, + {"from": "collect", "to": "write", "label": ""}] else: url = str(cfg.get("url") or "") host = (urlparse(url).hostname or url or "No URL") if url else "No URL" @@ -1901,10 +2878,13 @@ def toggle_node(rt, auto_id, node_id): which = target["toggle"] if which == "schedule": sched["enabled"] = not sched.get("enabled") - elif which == "hiker": - cfg["tier"] = "anonymous" if cfg.get("tier") == "hiker" else "hiker" + elif which == "paid": + cfg["tier"] = ("anonymous" if clean_tier(cfg.get("tier")) == "brightdata" + else "brightdata") elif which == "fallback": cfg["noFallback"] = not cfg.get("noFallback") + elif which == "postMetrics": + cfg["postMetrics"] = not cfg.get("postMetrics") elif which == "write": cfg["dryRun"] = not cfg.get("dryRun") return patch(rt, auto_id, {"config": cfg, "schedule": sched}) @@ -1918,6 +2898,13 @@ def run_now(rt, tenant, auto_id, username="automation", log=print): return None if not _claim(tenant, auto_id): return None + # ⛔ THE TABLES AN AUTOMATION MAKES BELONG TO THE AUTOMATION'S CREATOR, not to whoever + # happened to press Run — and above all not to the scheduler, which is not a person and + # cannot own anything (see `ut_ensure`). Without this the owner of a database was decided by + # whether a human or a cron got to the first run first. + owner = str(defn.get("createdBy") or "").strip() + if owner and username in MACHINE_OWNERS: + username = owner try: _step(tenant, auto_id, "running") runner = RUNNERS.get(defn.get("kind"))