Skip to content
MSO CloudDocumentation

ADR 0061 — Shared trend feed: SocialTrend as a platform connector, read by orgs and family apps

On this page
  • Status: Accepted (operator, 2026-11-12). Build status sits in the plan.
  • Date: 2026-11-12
  • Owners: Platform / data (packages/connectors/socialtrend, packages/schema, apps/worker, packages/metrics, packages/platform-contract, apps/web/src/app/api/platform, apps/web/src/server/chat).
  • Related: ADR 0002 (plugin registry), ADR 0013 (org credentials; platform credentials were out of its scope), ADR 0014 (sheet-fed SocialTrend, superseded for this feed by D8), ADR 0020, ADR 0058 (D10 Platform API v1, D15 data ownership; D15's source_key is amended by D7).
  • Plan: docs/plans/shared-trend-feed-2026-11.md — work packages, cutover order, verification, rollback.

Context#

Facts read on 2026-11-12:

  • ContentHeat (repo content-engine) syncs the SocialTrend vendor API itself into four platform-global tables (trend_cache_items, trend_history, trend_review_decisions, connector_runs) and reads them through one reader. Its production database held 446 current trends, 5,414 history rows since 2026-10-14 and 0 review decisions.
  • MSO Cloud has SocialTrend only as a per-org, sheet-fed stream (social_trend_rankings, social_trend_posts, org_id NOT NULL, RLS org_only). Production held 2,370 ranking rows for one org, last snapshot 2026-07-20. No table in MSO holds data shared by every org; the only org-less tables are control-plane (site_settings, platform_ai_connections).
  • Platform API v1 already has GET /orgs/{id}/social/trends under scope platform:social.read, with a row of keyword / mentions / engagement per hourly snapshot. ContentHeat needs rank per window, buzz, movement, topic, keywords and sample posts, so that row cannot feed it.
  • A platform access token names exactly one org (resource=…/orgs/<org_id>), and the issuer allows it only when the satellite plugin is enabled for that org.
  • The vendor invalidates the older session when the same account logs in again, serves one account at 300 calls per 60 s, and updates about every 12 h.
  • Vendor terms on storing and redistributing the data are still open (ContentHeat research note of 2026-10-13, section 7). The operator decided on 2026-10-13 to cache once at platform level and feed every org, and on 2026-11-12 to move that cache into MSO.

The trend data is the same for every org; an org differs only in whether it has the feed and which extra topics it was assigned. One sync per org would multiply vendor calls and stored rows by the org count for identical data.

Decisions#

D1 — A shared plane: org-less dataset tables, written by the worker only

A fourth kind of table joins the three org-scoped data planes: a shared dataset, synced once by a platform connector and read by any entitled org. Its tables carry no org_id and no is_sample, and hold no tenant data. Names start with shared_; sync state starts with platform_connector_.

Table Key Holds
shared_trend_items PK (connector, vendor_id) The current snapshot, one row per trend: name, passion_point, status, is_new, detected_at, roll_out_days, buzz, engagements, posts, unique_audience, sentiment, ranking_date, periods jsonb, sample_posts jsonb, keywords jsonb, vendor_topic_id (the id the detail calls need), slices text[] (the lists the row was in: general, or a topic), origin (live/fixture), review_state (auto_ok/pending/approved/rejected), flags jsonb, first_seen_at, last_seen_at, detailed_at, updated_at.
shared_trend_history PK (connector, window, cycle_at, vendor_id) Rank and figures of the usable general-list rows ranked in a window (24h/7d/30d), per stored cycle, at most 1,000 rows a cycle. Topic lists have no history.
shared_trend_review_decisions PK (connector, vendor_id, title_key) A super admin's approve/reject of a row the spam screen held; survives snapshot replacement.
platform_connector_runs PK id; partial unique (connector) WHERE status='running' One row per sync run: trigger, status, calls, counts, fingerprint, error code, heartbeat. The partial unique index is the single-flight lock.
platform_connector_state PK connector Non-secret settings, the stored fingerprint, revision, announced_revision, last_check_at, last_full_at.

Retention keeps 30 days of 24h cycles and the newest 15 7d and 12 30d cycles (settings defaults); a cycle is one Ho Chi Minh calendar day, ISO week or month. The vendor's raw payload is not stored. Column shapes follow ContentHeat's tables so the import of D9 is a column copy plus two derived columns.

Revision. platform_connector_state.revision is a counter raised in the same transaction as any change a reader can see: an item upserted, deleted or enriched, a history cycle written or pruned, a review decision. It is the dataset's only version; nothing is ordered by a clock.

Access is by runtime ACL, not RLS: the web role has SELECT on the three shared_trend_* tables and on platform_connector_state/platform_connector_runs; the worker role has the writes. Review decisions are written by the web role through a super-admin procedure only, with column-level UPDATE on shared_trend_items (review_state, updated_at) and platform_connector_state (revision, updated_at). Because RLS cannot gate an org-less table, the org gate is D3.

D2 — The platform connector: one sync, low frequency, single flight

@yng/connector-socialtrend becomes the vendor API connector, ported from ContentHeat: session client, rate-limit handling, the fingerprint check, the full fetch, the deterministic spam screen. It stays DB-free; the worker owns the sinks.

  • Cadence. An hourly check makes the three general-list calls and fingerprints them. A full fetch runs when the fingerprint changed and the last full fetch is at least full_sync_min_interval_hours old (default 12, the operator's choice of 2026-11-12, so at most two a day; the vendor's ranking moves every hour and a full fetch is about 800 paced calls), when the topic set changed, or when the last full fetch is older than 24 h. A check inside the interval ends unchanged after its three calls. A manual run from the super-admin panel forces a full fetch.
  • Topics. The full fetch covers the general lists plus the union of the topics assigned to any org (D3). A topic nobody was assigned is not fetched.
  • Session. The vendor session is kept in Redis, encrypted, with the token's own lifetime as TTL and a key namespaced by a hash of the credential. Login and refresh run under one lock: the holder rereads the stored session first and replaces it only if its generation is the one it saw fail. Several worker processes and the web runtime therefore share one session instead of invalidating each other's.
  • Call budget. One Redis limiter counts every vendor call of the account. The keyword search of D4 may use at most a tenth of the vendor's window (30 calls per 60 s) and two calls at once (a slot held until the search releases it, expiring after 20 s); the rest is the sync's.
  • Fencing. A run whose heartbeat is older than its expiry (600 s) is closed by the next run, which takes over. Every sink transaction checks that its own run row is still running, so a worker that resumes after a takeover writes nothing.
  • Credential. The vendor account (email and password) is set by a super admin on the Shared trends page and stored in the org-less table platform_connector_credentials: one envelope over { email, password } sealed with @yng/crypto under the AAD platform_connector_credentials:<connector>, with a masked email as the only display hint. The web role writes and reads it, the worker only reads it. Each runtime resolves it at the start of every run or request, never cached for the process: the stored credential first, then the env pair SOCIALTREND_EMAIL/SOCIALTREND_PASSWORD (kept as the fallback, precedent: KALODATA_COMPANY_KEY), else the connector reports not_configured and syncs nothing. The Redis session key is namespaced by a hash of the account email, so a changed account never reuses the old session. No procedure returns the password or the full email.
  • Failure classes. Auth and permission errors are permanent; vendor 5xx, timeouts and the rate floor are transient and end the run partial with a retry.
  • Empty answers never wipe the snapshot. Rows absent from a complete fetch are deleted; an empty or partial fetch deletes nothing.

D3 — Entitlement is a plugin row; the reader takes a proof

A new plugin social-trend-feed (third-party data, off by default, no dependency: an org may hold the feed for a family app without the in-app social pages) is the per-org switch. Its config is { topics: string[] }; empty means the general ranking only. An org sees the general lists plus the topic lists of its assigned topics.

Every read of the shared dataset goes through one module, packages/metrics/src/shared-trends-read.ts. Its functions take a TrendFeedScope value that only resolveTrendFeedScope produces. That function takes an authenticated org context, not a bare id: the org of a verified platform token after the route checked it equals the path org, or the org of the signed-in session. It reads the plugin gate. A caller cannot read without an authenticated org whose entitlement was resolved, and a static audit forbids any other import of the shared_trend_* tables outside the schema package, the worker, this module, the super-admin router and the import script. Apps and the assistant are served usable rows only (auto_ok or approved).

D4 — Platform API v1, contract 0.5.0: the trend feed

Four routes, all under scope platform:social.read, all bound to the token's org:

Route Answer
GET /orgs/{id}/social/trend-feed Entitlement and dataset state: enabled, topics, offered_topics, the slices the org may read, and dataset { revision, as_of, last_check_at, origin }. enabled: false answers 200 with no slices.
GET /orgs/{id}/social/trend-feed/items?slice= Every usable row of one slice (general, or one assigned topic) in one response, with the revision it was read at. 403 feed_not_enabled or slice_not_assigned otherwise.
GET /orgs/{id}/social/trend-feed/history?window= Every retained history row of one window (general list only) in one response, with its revision.
GET /orgs/{id}/social/trend-feed/search?keyword= The vendor's keyword search, proxied. Hits pass the spam screen and the stored review decisions. Cached 6 h in Redis, identical in-flight searches coalesced, the vendor call cancelled at the timeout, limited to 10 cache-missing searches per org per 60 s (a proposal pending the operator) and by D2's account budget.

A slice and a window are small and bounded (hundreds of rows; history is bounded by retention), so each is one consistent read with no pagination: a reader never holds a mix of two revisions. The ETag of items and history is the revision. The route authorizes first (token org, entitlement, slice) and only then evaluates If-None-Match; a 304 is never an authorization. Responses stay Cache-Control: no-store.

trends.updated gains an optional feed_revision. Whenever revision is ahead of announced_revision, the worker writes one event per org that has the feed enabled, each in that org's transaction, then sets announced_revision; a crash between the two is repaired by the next hourly check.

The older GET /orgs/{id}/social/trends and /counts are deprecated in 0.5.0 and keep answering from the per-org rows until 1.0.

D5 — A family app keeps a projection and pulls on change

An app does not query MSO on a user request. It holds a local projection and refreshes it in one single-flight job:

  1. per linked org, read /trend-feed and store that org's grant (enabled, slices) with the time MSO confirmed it;
  2. for each slice any org was granted, fetch it once with If-None-Match through an org that holds it, and replace the slice's rows in one transaction, only when the answer's revision is higher than the stored one;
  3. replace each history window the same way.

A failed or partial pull changes nothing. Triggers are the trends.updated webhook and an hourly reconciliation cron; the cron alone is sufficient, so a lost webhook delays an update by at most an hour.

A page view, a render or a matcher run reads the local projection, so the two systems can run on different clouds, and MSO sees a handful of conditional requests per hour per app instead of user traffic.

Content may be stale; authorization may not. Every local read is scoped by the org's stored grant. A grant MSO denied (enabled: false, 403, or the app's token refused for that org) is removed at once. A grant MSO has not confirmed for three hours (three missed reconciliations) stops being honored until the next confirmation. An org that is not linked to MSO has no grant and no feed; borrowing another org's projection would bypass the recipient list MSO keeps.

D6 — The assistant reads the feed behind the same gate

Two chat tools, getSocialTrends (ranked list by window, optional topic and movement) and getSocialTrendDetail (figures, keywords, sample posts), read through D3's module. They are registered and their intent prompt is appended only when the org has the plugin; otherwise the disabled-guard prompt covers trend questions. The tool names are mirrored in the agent-eval tool surface, with cases for "asked and enabled", "asked and disabled" and "not asked". They are excluded from the MCP tool list like the other third-party tools.

D7 — The dataset keeps its source key in the app

ContentHeat keeps source_key = 'socialtrend' for trend signals and its projection tables. ADR 0058 D15 named a new key mso-social; the dataset is the same one, only its transport changed, and a new key would rewrite stored signals for no reader's benefit.

D8 — The sheet-fed SocialTrend stream is replaced

The social-trend-feed plugin owns its own in-app surface: the menu item social_trends and the trends page are gated by it, so an org that holds only this plugin reaches the page (operator decision 2026-11-12: the feed is a plugin of its own with its own menu, not a part of the social listening plugin). The socialTrends router (feedBoard, feedHistory, feedDetail) answers the page from the shared dataset. The dashboard datasets trend_ranking_board, trend_daily_top and trend_topic_posts belong to the plugin too and read only the shared dataset: the general 24 h ranking, its stored daily cycles and the leading trend's sample posts, through D3's module. The metric social_trend_buzz keeps its place in the social pillar's catalogue, is gated by the feed plugin (operator decision 2026-11-12) and reads only the shared dataset. Dashboard reads have no session (a shared or exported dashboard), so the reader accepts a third proof, org_context: the read runs inside the RLS pin of the org it asks for. The vendor API has no comment, like or share split, so those cells are empty. The per-org sheet rows (one org, 2026-07-01 to 2026-07-20, the vendor's detail-id space, no day in common with the API rows that start 2026-10-13) stay stored and are no longer shown on the page or in these datasets for a feed org. The operator enables social-trend-feed per org (plan step 4); no migration and no blueprint does it. The sheet stream bindings stay available for uploads; no new sheet-fed SocialTrend sync is configured.

The pattern for the next global connector

A vendor dataset that is the same for every org (this feed first; market estimates of a category are the likely next) follows the same five parts: (1) one platform-level sync into org-less shared_* tables with a revision counter, written by the worker only; (2) one plugin of kind shared_feed per dataset, whose per-org config narrows what the org sees and which owns the dataset's own menu item and page; (3) one reader module that issues a scope from an authenticated org context and is the only code that selects from the tables (rule §218 and its audit); (4) Platform API routes under the org path for satellite apps, with the revision as ETag; (5) chat tools registered only when the org holds the plugin. Other plugins consume the dataset through the reader, never through their own copy.

D9 — History moves once, by import

ContentHeat's trend_cache_items, trend_history and trend_review_decisions are exported as NDJSON after its sync is switched off and no run is in flight, and imported into the shared_trend_* tables by an idempotent maintenance script: history inserts skip existing keys, an item keeps the row with the newer last_seen_at. slices is derived (general when the row ranks in a window, plus its topic) and vendor_topic_id is read from the source's raw payload; the first full sync in MSO rewrites both. The script compares a digest of the keyed content on both sides, besides row counts and date ranges; the cutover proceeds only when they match. The script does not touch plugin rows: the orgs' topic assignments are entered on the super-admin page in the next cutover step.

Consequences#

  • One vendor sync serves every org and app; vendor calls no longer grow with the org count.
  • The org boundary for this dataset is enforced in code (D3) and by a static audit rather than by RLS. This is the accepted cost of a table without org_id.
  • ContentHeat loses the vendor credential, the spam-review write path and the vendor client; review moves to MSO's super-admin panel.
  • A ContentHeat org that is not linked to MSO loses the feed at cutover until it is linked and given the plugin.
  • The vendor's redistribution terms remain an open contract question. The feed is served only to orgs with the plugin, which keeps the list of recipients a written fact.
  • Future ecosystem connectors reuse platform_connector_runs, platform_connector_state, the plugin-row entitlement and the proof-carrying reader pattern; each adds its own shared_* tables and Platform API routes.

After cutover#

Production cutover on 2026-11-12 (record in the plan) found two contract-conformance defects on the satellite's first live pull. The lesson: vendor values are not trusted to fit the contract, so the reader normalises what the contract cannot carry. A sentiment outside [-1, 1] is served as null, and sample-post text and keywords are cut on code points, not UTF-16 units. A new field added to the feed gets the same treatment at the reader, not in each consumer.

Known limits: super-admin actions on the Shared trends page are written to the audit log of the first organisation, because the platform page has no console organisation; a stored credential that cannot be decrypted is treated as absent; the social-pillar dashboard widgets still read per-organisation sheet rows.

Rejected#

  • One connector row and one data copy per org (the Kalodata shape): N times the vendor calls and rows for identical data, and one vendor account cannot hold N sessions.
  • Apps query MSO per request: couples app latency and uptime to a cross-cloud call.
  • RLS policy keyed on the plugin row: duplicates the entitlement rule in SQL, where plan, status and validity already live in the plugin gate.
  • Keep the sync in ContentHeat and push to MSO: the warehouse would depend on a satellite's uptime and credentials.

Review#

An independent review of the first draft (Codex, 2026-11-12, 25 findings) changed: the bound org context in D3; stored slice membership, vendor_topic_id and the revision counter in D1; the shared lock, call budget and fencing in D2; unpaginated, authorize-first routes in D4; atomic slice replacement, grant leases and the unlinked-org rule in D5; the quiesced export and digest comparison in D9.