Skip to content
MSO CloudDocumentation

ADR 0065 — Collector ingest: signed batch delivery from remote collectors into the market-intel plane

On this page
  • Status: Accepted (2026-11-28) for slices 1 and 2: the two roles, the host name ingest.msocloud.net (Cloudflare-proxied) and the archive-worker pool cut from 20 to 15 are operator decisions of 2026-11-28. Every number marked "proposal" has no source yet and is the operator's to set. Both processes ship with their flags off.
  • Date: 2026-11-28
  • Owners: Platform / data (packages/collector-contract, scripts/collector, apps/worker/src/collector, packages/schema, packages/metrics, packages/connectors/core; the admin page is slice 3).
  • Related: ADR 0003, ADR 0006, ADR 0008 (planes never mix), ADR 0010 (runtime roles, outbox), ADR 0054, ADR 0061 (platform-level sync, "pattern for the next global connector").
  • Runbook: Remote collectors. Extend guide: Add a collector feed.

Context#

Facts read on 2026-11-28 at eb66406cc:

  • Third-party market rankings with no API are captured on remote machines by browser automation (skills kalodata-market-data, kalodata-category-crawl, weekly-market-topup): top 500 rows per dataset (product, shop, creator, video, livestream, category) per closed window, weekly Mon-Sun for one category and monthly for wider categories. The capture is human-paced and can run several threads.
  • A capture is one JSON file per (dataset, window): { platform, source, dataset, scope, scopeCategoryName, rangeStart, rangeEnd, capturedAt, rowCount, rows }, rows verbatim from the vendor list API.
  • It reaches MSO three ways, all manual: tRPC marketIntel.ingestExport / ingestShopeeJson (base64 in the request body, cap 14,000,000 characters, runs in the web process as yng_app); scripts/market-intel/ingest-kalodata-json.ts run on the production host from a data/ directory; scripts/market-intel/load-kalodata-industry-handoff.ts for bulk deliveries with a spec, a manifest and market_intel_load_receipts.
  • market_intel_* is org-scoped and brand-partitioned under FORCE RLS. One writer exists: persistMarketIntelSnapshot (packages/metrics/src/market-intel-persist.ts). It takes pg_advisory_xact_lock on the snapshot's natural key (org, brand, source, platform, dataset, scope, window), deletes the predecessor and inserts in one transaction. market_intel_snapshots already carries transport, ingest_batch, coverage_top_n, source_sha256, captured_at.
  • Vendor list rows are mapped by mapTiktokRows (packages/connectors/core/src/kalodata-tiktok-list.ts); file sources dispatch through PARSERS in market-data-registry.ts, keyed by providerId, which equals market_intel_snapshots.source.
  • Platform API tokens come from apps/idp: clients are static configuration (apps/idp/src/clients.ts), every access token names exactly one org (resource=.../orgs/<org_id>), is a bearer token valid up to 600 s, and scopes are one per plane (§179).
  • job_outbox.org_id is NOT NULL. An org-less job cannot use it.
  • The object store (RustFS) is on the internal network, which has no route to the internet. @yng/storage has putObjectStream, getObjectStream, headObject, getPresignedUrl (TTL cap 15 min).
  • Postgres runs with max_connections 100. Pools: web 25 + 5 per replica (60 during a rollout), worker 20, archive-worker 20. A rollout already reaches 100.
  • Redis is one instance, 512 MB, noeviction, and holds every tenant queue.
  • A separate process on the worker image with its own command exists (the watchdog); a runtime role created NOLOGIN in a migration and enabled by ops exists (yng_idp, migration 0235).

The manual upload does not scale past one category and puts a file decode on the web request path. The requirement: remote collectors deliver continuously, authenticated per machine, least privilege, revocable, idempotent, resumable, with no load on the web request path, the tenant queues or the DB hot paths.

Decisions#

D1 — Ingress is a separate gateway process, not a web route and not a public object store

collector-gateway is a small HTTP server in apps/worker/src/collector/gateway/, started from the worker image with its own command (the watchdog precedent), as its own compose service on its own host name (COLLECTOR_HOST, a generic name such as ingest.<domain>). It is on balancer and internal, not on egress.

  • It holds no Redis credential, no session secret, no encryption key and no tenant grant. Its database role yng_collector_gw can read collectors, collector_keys, collector_feeds, collector_feed_grants and write collector_batches, collector_batch_parts, collector_batch_chunks, collector_events. Nothing else.
  • It never parses or inflates a payload. It authenticates, streams the compressed chunk to the object store while hashing and counting bytes, and records the chunk row.
  • Container limits (proposal): 256 MiB, 0.5 CPU, DB pool 2, at most 4 chunk uploads in flight.

API, version in the path:

Call Purpose
GET /v1/feeds Feeds this collector may deliver, with the newest promoted window per dataset kind (the server-side high-water mark). No org data.
POST /v1/batches Open a batch: feed, window, idempotency_key, contract_version. Returns batch_id, limits and, per planned chunk, the upload URL and required headers. Re-opening with the same key returns the same batch.
PUT <upload URL> One chunk. Today the URL is /v1/batches/{id}/parts/{kind}/chunks/{seq} on the gateway.
POST /v1/batches/{id}/seal The manifest (D3). The gateway compares it with the chunks received; a mismatch answers 409 with the missing or differing chunks.
GET /v1/batches/{id} State, received chunks, outcome code per part.

The client always uploads to the URL the server returned. When the object store becomes reachable from outside (the multi-node target in docs/architecture/deployment.md), POST /v1/batches returns presigned URLs and no client changes.

Edge: the host is proxied by Cloudflare like the main host; Traefik labels on the service set buffering.maxRequestBodyBytes (9 MiB), inFlightReq (8) and rateLimit (proposal: average 20/s, burst 40 per source IP); every response is Cache-Control: no-store (§176 adds no cached path). An optional CIDR allow-list per collector is checked in the gateway against the client address resolved by the existing rule (resolveClientIp).

Rejected:

  • Route in apps/web: upload streams share the single web replica's event loop and the yng_app role, which can write every tenant table.
  • Presigned PUT straight to the object store now: needs RustFS published on the edge; the same store holds tenant exports and backups.
  • A request body per row batch (JSON POST to tRPC): the current shape; decode cost on the receiver, no resume, 8 MiB inline cap.
  • A new image and app for the gateway: one more image to build and deploy for 300 lines of server; the worker image already carries the dependencies.

D2 — Authentication: an Ed25519 key pair per collector machine, every request signed

Each collector machine generates its key pair locally (mso-collect keygen). A super admin registers the public key on the Collectors admin page. The server stores public keys only (collector_keys: key_id, collector_id, public_key, not_after, revoked_at, last_used_at), so a database or backup leak yields nothing that can sign.

Request headers: X-MSO-Collector-Key: <key_id>, X-MSO-Timestamp: <unix seconds>, X-MSO-Content-SHA256: <hex>, X-MSO-Signature: ed25519=<base64> over

MSO-COLLECTOR-V1\n<METHOD>\n<path?query>\n<timestamp>\n<content sha256>\n<key_id>
  • Verification order: key lookup (active, not expired, collector enabled, CIDR if set), timestamp within 300 s, signature, then the body is read. The body hash and size are checked while streaming; a mismatch deletes the object and answers 422.
  • Replay: every mutating call is idempotent by construction (open by idempotency_key, chunk by (batch, kind, seq, sha256), seal by manifest hash) and the signature binds the body hash, so a replay inside the 300 s window changes nothing. No nonce store is needed, which is why the gateway needs no Redis.
  • Least privilege: a collector may deliver only the feeds granted to it (collector_feed_grants). It never names or learns an org.
  • Rotation: a collector may hold two active keys; add the new one, switch, revoke the old. not_after is mandatory (proposal: at most 180 days). Revocation is one row update, read on the next request; the gateway does not cache keys.
  • Rate and quota, enforced in the gateway process (one replica) and from collector_batch_chunks: requests per key per minute (proposal 300), bytes per collector per day (proposal 2 GiB), open plus unprocessed batches per collector (proposal 20). Over quota answers 429 with Retry-After.

Rejected:

  • OAuth client credentials through apps/idp with a new platform scope: clients are static config (adding or revoking a machine is an idp redeploy), a token must name one org and collectors must not know orgs, and a stolen bearer token replays for up to 10 minutes with any body.
  • HMAC with a shared secret: the server must keep the secret recoverable; a DB leak lets the reader forge deliveries.
  • mTLS: TLS terminates at Cloudflare, then Traefik, which is a shared stack outside this repository.

D3 — The collector batch contract, @yng/collector-contract v1

A new private package packages/collector-contract holds the Zod schemas, the signature canonicalisation and the window helpers. It is not packages/platform-contract: that package is published to satellites and must not carry vendor source keys.

A batch is one feed and one window. Its parts are dataset kinds; each part becomes one snapshot lineage.

Manifest (collectorManifestSchema, sent at seal):

Field Rule
contract_version 1. A breaking change is a new number; the gateway accepts the versions listed in SUPPORTED_CONTRACT_VERSIONS.
feed Feed key from GET /v1/feeds. The feed fixes source, platform, market, category scope, grain and allowed kinds; the manifest repeats none of them.
window `{ grain: 'week'
captured_at Instant the capture finished, ISO 8601 with offset.
collector_run_id The idempotency_key of the batch.
parts[] { kind, row_schema, coverage_top_n, universe_exhausted, rows, captured_at, chunks: [{ seq, sha256, bytes, rows }] }. kind is `product
client { name, version } of the sending tool. Free of host names, user names and credentials by schema: fixed keys, bounded lengths, strict().

The manifest carries no org, no brand, no vendor credential, no cookie and no account name. strict() rejects unknown keys.

Chunk format: gzip NDJSON, one vendor row per line, verbatim (§44). Caps: 8 MiB compressed per chunk (gateway), 64 MiB inflated and 1 MiB per line and 50,000 lines per chunk (promoter; the inflated cap equals the existing workbook budget). Object key: collector/v1/<feed_id>/<batch_id>/<kind>/<seq>.ndjson.gz.

Row schemas: row_schema is <kind>@<n>. For each (source, platform, kind, n) the server holds a minimum Zod schema (identity and measure fields required, the rest passed through) and a mapper to the canonical MarketIntelSnapshotRows shape. The registry is PARSERS in market-data-registry.ts, extended with an optional mapRows(kind, rows, context); the first entry wraps the existing mapTiktokRows. Mapping stays on the server so a mapper fix replays the stored objects without a new crawl.

Vendor identity: source is the existing internal provider id, stored on the feed and on market_intel_snapshots.source as today. It appears in the collector contract, object keys, super-admin screens and platform alerts. It never appears in the gateway host name, in a response to an unauthenticated caller, or in tenant copy; tenants keep seeing the existing source badge (§62).

Rejected:

  • Canonical (already mapped) rows from the collector: every mapper fix would need a re-crawl, and the vendor's display-format quirks would be reimplemented in each collector.
  • Parquet: rows are drifting vendor JSON, parts are about 500 rows; a columnar schema buys nothing and breaks on every vendor field change.
  • CSV/Excel: 19-digit ids and locale number formats are the known failure of the current path.

D4 — Processing: a dedicated promoter process that claims batches from the table

collector-promoter is a second process on the worker image (apps/worker/src/collector/promoter/), its own compose service, concurrency 1, role yng_collector.

  • Queue. The batch row is the queue: the promoter claims sealed batches with FOR UPDATE SKIP LOCKED and a lease, oldest first. No BullMQ queue and no Redis key is used, so tenant queues and Redis memory are untouched. The seal and the "ready" state commit in one transaction, which gives the outbox guarantee without job_outbox (whose org_id is NOT NULL).
  • Staging. The stored objects are the staging layer and the replay source. Rows are validated while streaming from the object store; nothing is written to Postgres before the gate passes.
  • Quality gate, per part. Any failure moves the batch to quarantined with a code; nothing reaches market_intel_*.
    1. Integrity: chunk sha256 and byte counts match the manifest; inflate caps hold.
    2. Schema: every line parses against row_schema; mapper rejects at most 1 % (proposal); identity fields never missing.
    3. Counts: lines equal manifest rows; distinct ids equal rows; rows at most coverage_top_n; rows at least half of the previous promoted window's count unless universe_exhausted (proposal).
    4. Window: grain alignment and closed window in Asia/Ho_Chi_Minh; captured_at after the window end and not in the future; the category kind only when captured on the Monday after the window (the vendor's list is rolling).
    5. Scope: a row that carries a category id must sit under the feed's category.
    6. Drift against the previous promoted window of the same feed and kind, using statistics the promoter stored on collector_batch_parts.quality (never a read of tenant tables): revenue sum ratio within 0.4 to 2.5, top-50 id overlap at least 30 % (both proposals).
  • Quarantine. A super admin releases or rejects on the admin page; the decision is an insert into collector_batch_decisions, consumed by the promoter. The promoter is the only writer of batch state after seal.
  • Promote. For each target org and brand of the feed (D5), one call to persistMarketIntelSnapshot per part, each in its own RLS-pinned transaction. That function already takes the advisory lock on (scope, window) as required by §206 and stays the only writer of the snapshot tables. transport stays inpage (the capture method is unchanged); ingest_batch is the batch id, source_sha256 the part digest, captured_at and coverage_top_n come from the manifest. One market_intel_load_receipts row per part and target table records manifest, parsed and written counts.
  • Idempotent re-delivery. Under the same lock the persister gains two checks: a live snapshot with the same source_sha256 is left as is (no delete, no insert); a live snapshot with a newer captured_at is kept and the part ends stale. A re-sent batch therefore writes nothing, and an old capture cannot overwrite a newer one.
  • Order inside a batch. shop before creator (the creator mapper reads the same window's shop seller types), then the rest.
  • Planes. The promoter writes only the snapshot-scoped market_intel_* tables and market_intel_load_receipts. It has no grant on orders, rollups, marketing or signal tables (§57, §60d).

Rejected:

  • A BullMQ queue in the existing worker (materialize pool): shares Redis memory, the worker's 20 connections and 4 GiB with tenant jobs.
  • COPY into Postgres staging tables: WAL and bloat on the primary for rows that are validated in a stream; a part is about 500 rows and the persister already chunks inserts at 500. Revisit when one snapshot exceeds 50,000 rows.
  • Promotion inside the gateway: the internet-facing process would need tenant write grants.

D5 — Org scoping: deliver once at platform level, promote per subscribed org

A delivery is org-less: feeds, batches, chunks and stored objects carry no org_id. Which orgs receive a feed is tenant configuration: the market-data connector row of an org and brand (connector_credentials.config) lists feed keys in feeds. The promoter resolves targets through a SECURITY DEFINER helper, app_collector_list_feed_targets(feed_key), which returns (org_id, brand_id) for active connectors whose org has the Market Intelligence plugin enabled, and nothing else from the row.

Category data used by two tenants is uploaded and validated once and written once per subscribed org. No collector, key or manifest can address an org, so no delivery can choose where it lands.

market_intel_* stays org-scoped in this ADR. Moving category estimates to org-less shared_* tables (ADR 0061's pattern) removes the per-org copies but rewrites every reader of the plane; it is a separate decision, due when one feed has more than a few subscribers. The staging side built here is already org-less and would feed that store unchanged.

Rejected:

  • The collector names the target org: the collector would hold a tenant list, and a stolen key could write to any org it can name.
  • Shared market_intel tables now: a reader migration across the whole plane is not needed to remove the manual upload.

D6 — Isolation and performance budget

Resource Rule
Web No route, no code path. The admin page reads collector_* tables with indexed, limited queries.
Redis / BullMQ Not used by gateway or promoter.
Postgres connections Gateway 2, promoter 3. The rollout peak is already 100 of 100, so 5 connections must come from somewhere: proposal, lower the archive-worker pool from 20 to 15 (it runs one pool). Operator decision.
Postgres load One part per transaction, 500-row inserts, statement_timeout 60 s, lock_timeout 5 s, a pause between transactions (proposal 200 ms). Batches whose feed class is bulk (monthly, backfill) promote only between 22:00 and 06:00 Asia/Ho_Chi_Minh (proposal); weekly promotes on arrival (about 3,000 rows).
Roles yng_collector_gw and yng_collector, created NOLOGIN NOBYPASSRLS in the migration, grants in packages/schema/src/runtime-acl.ts; yng_collector joins RLS_CONTEXT_ROLES. yng_app gets SELECT on collector_* and insert/update only on the registry tables and collector_batch_decisions. yng_worker gets nothing.
Memory / CPU Gateway 256 MiB, 0.5 CPU; promoter 1 GiB, 1 CPU (proposals). Streams, never whole files in memory.
Object store Own bucket for collector objects. Raw objects are deleted 90 days after promotion, 14 days after rejection (proposals). Uploads are refused with 507 when the bucket quota is reached (proposal 20 GiB). Whether RustFS can scope an access key to one bucket is unverified; if it can, the gateway and promoter get such a key.
Backpressure Gateway answers 429 when a collector exceeds its unprocessed-batch or byte quota; the client backs off and resumes.

Observability: /metrics on both processes (requests by outcome, auth failures by reason, bytes, batches by state, gate failures by code, promote duration, oldest sealed batch age), both added as watchdog targets. collector_events is an append-only platform audit table (key registered or revoked, batch opened, sealed, quarantined, released, rejected, promoted, auth failure). Alarms in apps/worker/src/watchdog/alarms.ts, audience platform (§79): gateway or promoter down, a sealed batch older than 2 h, any quarantined batch, signature failures above 20 in 5 min for one source address, a feed with no promoted window for its last closed period by Tuesday 12:00 (weekly) or the 5th (monthly). Thresholds are proposals. The admin page (slice 3, beside the shared-trends admin page) shows collectors and keys, feeds with subscribers and freshness, and batches with state, counts, gate results and the release or reject action.

D7 — The collector client

scripts/collector/mso-collect.ts is the CLI mso-collect, bundled to one file so a remote machine needs Node and that file, not the repository.

  • keygen writes the private key with mode 600 and prints the public key.
  • feeds prints the server high-water mark per feed and kind; the skills compute "what to pull" from it.
  • push --feed <key> --run <id> <files...> converts the existing capture wrapper files to gzip NDJSON chunks and uploads them, 4 at a time, with a local journal so an interrupted run resumes with the missing chunks only. Parallel capture threads call push as each window file completes.
  • seal --run <id> sends the manifest; status --run <id> waits for promoted, quarantined or rejected and exits non-zero on the last two.

The CLI refuses to send a file whose wrapper has keys outside the known set, so cookies or session dumps written by a capture script cannot ride along.

scripts/market-intel/ingest-kalodata-json.ts stays as the break-glass path on the host.

Threat model#

Threat Control
Stolen collector private key It can deliver only that collector's granted feeds, never read data, never name an org; quality gate and quarantine stand between it and tenants; revoke is one row; mandatory expiry; optional CIDR allow-list; signature-failure and unusual-volume alarms.
Poisoned or wrong data from a valid collector Gates 2 to 6; quarantine needs a super-admin release; supersede is per window, so a release mistake is undone by re-delivering or by the existing deleteSnapshot; data stays in the labelled estimate plane and outside first-party KPIs.
Oversized body, zip bomb 9 MiB at Traefik and 8 MiB in the gateway, enforced while reading; the gateway never inflates; the promoter inflates in a stream with 64 MiB, 1 MiB per line and 50,000 line caps inside a 1 GiB container.
Replay Timestamp window 300 s, signature binds method, path, body hash and key id; all mutations idempotent; an older capture cannot supersede a newer one.
Cross-tenant write No org in the contract; targets come from each tenant's own connector config through one SECURITY DEFINER helper; every write goes through persistMarketIntelSnapshot inside runWithRlsContext as a non-bypass role; verify:rls gains a leg for the two roles.
Gateway compromise No tenant grants, no Redis, no egress network, no encryption keys; it can write collector tables and one bucket.
Log or payload leakage Manifest schema is strict() and has no free-form field; logs carry key id, batch id, codes and counts, never headers or bodies; errors to the caller are codes; no private key ever reaches the server.
Vendor name reaching tenants Source key confined to contract, admin and platform alerts; no new tenant copy; no-ai-slop-copy.py already guards tenant strings.
Denial of service on the ingest host Separate process, CPU and memory caps, Traefik rate and in-flight limits, auth before body read; the web host and its router are untouched.
Disk exhaustion Per-collector daily byte quota, bucket quota with 507, retention sweep.

Consequences#

  • Weekly and monthly market data arrives without a person uploading a file and without a request on the web path.
  • Two new processes, two new database roles and one new host name to operate. The roles and the connection budget change need operator approval (runtime DB identity is an ask-first boundary in AGENTS.md).
  • The org boundary for a delivery is the helper plus the existing persister, not the collector. A collector key is not a tenant credential.
  • Per-org copies of the same category data remain until the shared-store decision.
  • The manual upload procedures and ingest-kalodata-json.ts remain; they are removed from the skills' normal path, not from the code.
  • Detail captures (365-day creator and shop detail) and the creator-type sidecar are not in contract v1; they keep the handoff loader until a later version adds their kinds.

Implementation notes (slices 1 and 2, 2026-11-28)#

Where the build differs from the decisions above, the code wins and is listed here.

  • Chunk upload. The gateway reads a chunk of at most 8 MiB into memory while hashing it and stores it only after the digest matches the signed header, so a refused body leaves no object (apps/worker/src/collector/gateway/routes.ts). The object key carries the digest, collector/v1/<feed_id>/<batch_id>/<kind>/<seq>.<sha256>.ndjson.gz, so a chunk object is never overwritten.
  • Bucket. COLLECTOR_S3_BUCKET is passed to @yng/storage as an env override; the storage package is unchanged.
  • Database pools. Both processes use the shared @yng/schema/client pool sized by DB_POOL_MAX (2 and 3). The gateway never opens an RLS scope and gets no RLS_CONTEXT_HMAC_KEY. Statement and lock timeouts are set per role in migration 0278.
  • Subscriptions. A connector of the feed's source subscribes by listing the feed key in connector_credentials.config.feeds (open question 4, provisional). app_collector_list_feed_targets reads the market-intelligence plugin row the way installBlockReason in packages/plugin-host/src/resolve.ts does.
  • Scope gate. A vendor list files a product under every category it belongs to: 2 to 4 of 500 rows per week carry another top category in the 38 weekly product captures of 2026-03-02 to 2026-11-22. The gate therefore allows up to 2 % such rows (proposal) instead of none. In the same captures the top-50 overlap with the previous week was 21 to 36 of 50, and one week (2026-06-08) fell to 7 and quarantines.
  • Capture wrapper. Files in the wild carry note, scope as an object, numeric cateIds, no grain or rowCount, and since August the platform name tiktok. The client's strict schema lists these keys and maps tiktok to tiktok-shop; anything else is refused (scripts/collector/capture-core.ts).
  • Parallel collectors. A batch belongs to one collector key and one window. Each machine of a multi-browser crawl registers as its own collector and opens its own batch per window, with a run id that is stable for that machine, feed and window, so a re-run resumes instead of opening a second batch. A part is all or nothing and a batch seals only when every declared chunk has arrived. Two collectors delivering the same window converge in the persister: the same bytes write nothing, an older capture keeps the newer snapshot.
  • One writer. scripts/market-intel/ingest-kalodata-json.ts still deletes and inserts on its own, outside the persister's advisory lock. It can race a promote of the same window (§206); it stays break-glass only.
  • Re-delivery and mapper fixes. The part digest covers the kind, the row schema and the chunk digests, not the mapper. Re-delivering the same bytes after a mapper fix therefore ends unchanged; replaying a fix needs the live snapshot removed first or a new row_schema number. keepIfNewer compares only against live snapshots that carry a source_sha256: a manual or Open API row's captured_at is the time it was written, so a collector delivery supersedes it. A bulk handoff row carries a digest and a write-time captured_at, so a later delivery of an older capture of that window ends stale.
  • Retries. A promote that throws leaves the batch promoting; after the lease it is claimed again, and the sixth claim quarantines it with promote_failed (cap 5, proposal).
  • Audit trail. An authentication failure for a known key writes a collector_events row within that key's request budget; one for an unknown key is logged only, so an anonymous caller cannot add rows.
  • Not yet built. Release and reject of a quarantined batch, the admin page, the other kinds, retention and alarms (slices 3 to 5).

Open questions for the operator#

  1. Answered 2026-11-28: the two roles are approved and the archive-worker pool goes from 20 to 15.
  2. Answered 2026-11-28: ingest.msocloud.net, Cloudflare-proxied.
  3. Every value marked proposal: quotas, gate thresholds, retention, off-peak window, key lifetime (limits and budgets).
  4. Whether feeds stays in connector_credentials.config (operational key) or moves to the plugin installation config.