# Shared DataForSEO datasets: implementation plan

Status: first rollout implemented and verified on 2026-10-30. Later migrations
below remain pending. No paid provider calls were made.

## Summary and scope

Introduce persistent, website-scoped DFS datasets shared by Top Pages and Site
Explorer. Start with Relevant Pages, keeping the existing provider client and
module caches. Migrate incrementally; do not introduce a global HTTP cache,
cross-customer sharing, new credit rules, or automatic paid refreshes.

The first rollout covers shared storage, precise request identity, refresh
coordination, Relevant Pages integration, source-aware Top Pages history, and
validation. Later endpoint migrations are listed separately and are not enabled
implicitly. This is a standalone implementation plan derived from the discussion,
not a completed migration-workflow specification or quality-gate assessment.

## Current implementation and problems

| Surface | Current source/storage | Problem |
|---|---|---|
| Top Pages | `TopPagesService`, `wc_site_overview_cache`, `top_pages` | Aggregates up to 1,000 keyword observations; page counts/metrics are partial |
| Site Explorer | `SiteOverviewService`, section-specific cache | Relevant Pages fetched twice with limit 1 for content-pillar totals |
| Keyword Research | `KeywordResearchService`, application cache | Separate key and expiration rules |
| Keyword SERP | `SharedKeywordSerpService`, `wc_serp_snapshots` | Already has reusable context/date snapshots; preserve this investment |
| AI Overview citations | `ai_overview_citations` section | Up to 30 keyword observations; not complete cited-page coverage |
| AI Visibility | Saved response/citation rows | Different observation population; never equate with organic or Google AI Overview data |
| DFS diagnostics | `wc_dataforseo_logs` | Optional logging, not an authoritative serving cache |

## Requirements

| ID | Requirement |
|---|---|
| REQ-001 | One reusable dataset can serve multiple modules for the same authorized website |
| REQ-002 | Exact request identity includes account namespace, website, endpoint, effective task parameters and schema version |
| REQ-003 | Normal Top Pages/Site Explorer reads never contact DFS, including missing/stale data |
| REQ-004 | Explicit refresh reuses fresh matching datasets for 24 hours; no duplicate concurrent calls |
| REQ-005 | Retain last successful data on failure; expose errors and temporarily block ambiguous immediate retries |
| REQ-006 | Preserve raw response, fetch/provider dates, task ID, reported cost, count/coverage, requesting actor and consuming module |
| REQ-007 | Relevant Pages becomes the primary Top Pages source; no extra ranked-keyword purchase for enrichment |
| REQ-008 | Existing keyword-sample reports remain readable; incompatible sources/coverage are not compared as growth/loss |
| REQ-009 | Site Explorer reuses the same unfiltered Relevant Pages request; filtered totals remain separate exact requests |
| REQ-010 | Keep access checks, billing rules, two-screen UX, CSV and missing-data behavior intact |
| REQ-011 | Verify identity, reuse, concurrency, failure preservation, persistence and source transitions without paid requests |
| REQ-012 | Document deployment, limitations, safe expansion and rollback; track completed work accurately |

## Technical decisions

1. Keep `DataForSeo` as transport/provider wrapper.
2. Add `DfsDatasetService` and `DfsDatasetModel`; use the existing MySQL database.
3. Use a single `wc_dfs_datasets` row per exact request, retaining the latest
   successful raw envelope and a separate last-attempt state. Existing module
   snapshots retain immutable report history; do not duplicate unbounded raw
   envelopes per refresh.
4. Canonicalize associative keys recursively, preserving list order and scalar
   types. Include all effective parameters, including defaults and limit. Domain
   normalization is provider-specific; never lowercase an exact URL path/query.
5. Scope sharing by website ID and a non-secret hash of provider account identity.
   Controllers still authorize active/team-visible websites on every request.
   Cache identity is not authorization. Do not expose credentials or global
   cross-account data.
6. Use a MySQL named lock per request fingerprint, zero wait, released in `finally`.
   Hold no database transaction across a network call. A conflicting caller receives
   HTTP 409 rather than starting another fetch. Recheck freshness inside the lock.
7. Record an attempt before dispatch. A failure/abandoned attempt blocks immediate
   retry for five minutes. Do not automatically retry billable live requests.
   This is a retry guard, not provider-side idempotency; an uncertain provider
   outcome can still require operator investigation using the task/log records.
8. Use 24-hour dataset freshness, distinct from module report dates and cooldowns.
   Copy the dataset fetch time into derived reports; viewing cached data must not
   manufacture a new observation time. Persisting a newly encountered saved
   observation into module history is allowed on a cache-only read.
9. Standardize the initial unfiltered Relevant Pages request at 100 traffic-sorted
   organic pages, English, selected location. This replaces Top Pages' existing
   refresh call; it does not fetch another 1,000 keywords. Site Explorer uses the
   same request for its total count. Its >=20-keyword filter remains limit 1,
   with its own key.
10. Report returned-page traffic/keywords as sums of returned page metrics. Display
    the provider total ranking-page count separately from returned-row count.
    Never imply the first 100 pages represent complete domain traffic.
11. Keep absent keyword detail/backlink/AI fields null/N/A. Retain the old direct
    keyword-based `search()` helper for existing internal callers/tests, but move
    the saved-website endpoint to the shared Relevant Pages source.
12. Shared datasets are latest-only. Retain 36 existing module snapshots. No log
    import or cleanup job is enabled until account provenance, access and retention
    are explicitly established. No Redis, new queue, or dependency is required.

## Implementation steps and tasks

### Phase 1: Foundation [Plan:1]

- [x] T001 [Plan:1.1] Inspect `DataForSeo`, `SiteOverviewService`, `TopPagesService`, existing cache/snapshot models, migrations and validation tooling. Map current behavior above. (REQ-001, REQ-010)
- [x] T002 [Plan:1.2] Add `app/Database/Migrations/2026-10-30-000041_CreateDfsDatasets.php` and `app/Models/DfsDatasetModel.php`: exact-key storage, checked writes, named-lock lifecycle, attempt metadata. Depends on T001. (REQ-002, REQ-004, REQ-005, REQ-006)
- [x] T003 [Plan:1.3] Add `app/Libraries/DfsDatasetService.php` and a non-secret account namespace accessor in `app/Libraries/DataForSeo.php`: canonical fingerprints, cache-only reads, fresh reuse, refresh guard, validated responses. Depends on T002. (REQ-001 through REQ-006)

### Phase 2: Top Pages pilot [Plan:2]

- [x] T004 [Plan:2.1] Adapt `app/Libraries/TopPagesService.php#getReport` to consume shared Relevant Pages on read and explicit refresh. Persist raw response/report with dataset timestamp and source metadata. Do not buy keyword enrichment. Depends on T003. (REQ-003, REQ-007, REQ-010)
- [x] T005 [Plan:2.2] Update `TopPagesService#presentSnapshots` to compare only compatible source/request versions. Preserve legacy snapshots; mark transition boundaries. Depends on T004. (REQ-008)
- [x] T006 [Plan:2.3] Update `public/assets/js/top-pages.js` and `app/Views/dashboard/top-pages.php` for returned-page totals/traffic labels, missing keyword details, current coverage and source-boundary chart behavior. Preserve both entry screens and CSV. Depends on T005. (REQ-007, REQ-008, REQ-010)

### Phase 3: Second consumer [Plan:3]

- [x] T007 [Plan:3.1] Pass authorized website/actor context into `app/Libraries/SiteOverviewService.php#fetchContentPillarData`. Use shared unfiltered Relevant Pages and a distinct filtered request. Preserve other refreshes/credit rules. Depends on T003. (REQ-001, REQ-009, REQ-010)

### Phase 4: Verification and deployment [Plan:4]

- [x] T008 [Plan:4.1] Add controlled regression coverage in `tests/unit/DfsDatasetServiceTest.php` for identity, freshness, concurrency, failures, coverage and consumer reuse. Adapt `tests/unit/TopPagesCacheTest.php` for the injected shared dataset source, preserving legacy keyword tests. Depends on T004, T005, T007. (REQ-011)
- [x] T009 [Plan:4.2] Run PHP 8.5 lint, JS syntax checks, focused available tests, and `git diff --check`. If PHPUnit is unavailable, state that explicitly and run an independent no-network regression harness. Depends on T006, T008. (REQ-011)
- [x] T010 [Plan:4.3] Inspect pending migrations; apply only the new additive migration using the standard runner if no unrelated migrations are pending. Verify persistent reuse and lock contention using controlled responses and remove test rows. Verify cached browser read; never click paid Refresh. Depends on T009. (REQ-004, REQ-011)
- [x] T011 [Plan:4.4] Update `README.md`, `schema.md`, and this plan with actual completed results/limitations. Depends on T010. (REQ-012)

## Execution evidence

- Applied only `2026-10-30-000041_CreateDfsDatasets`, standard migration batch 37.
  All earlier discovered migrations were already applied.
- `php8.5 tests/standalone/dfs-datasets.php`: 42 checks passed, covering canonical
  identity, coverage/isolation, cache-only reads, cross-module reuse, exact URLs,
  genuine zeros, missing values, stale reads, failed refresh preservation, retry
  guarding, concurrent dispatch, setup failures, malformed results, retention and
  source-aware comparisons.
- `php8.5 tests/standalone/dfs-datasets-database.php`: 11 checks passed against
  MySQL, including committed visibility on another connection, lock contention,
  release, metadata/TTL persistence and the actual Site Explorer content-pillar
  consumer. Only controlled provider responses were used; all test rows removed.
- Browser: real authenticated legacy cached report still loads without an error.
  Controlled Relevant Pages report displayed returned/total coverage, an unchanged
  exact URL, and two single-observation chart dots after a source boundary.
  Zero paid refresh requests were observed; browser interception was removed.
- PHP 8.5 syntax, JavaScript syntax and patch whitespace checks passed.
- PHPUnit could not run: `vendor/bin/phpunit` is absent. PHPUnit regression files
  were added/updated, but only the independent checks above are claimed as run.
- No production Relevant Pages response has been fetched for Top Pages as part
  of this execution. Existing legacy reports remain until a matching saved
  dataset exists or the user explicitly performs an eligible paid refresh.
- No commit or push was made. Existing unrelated working-tree changes were
  preserved.
- Added an exact `.gitignore` exception for the plan (now `docs/DFS-plan.md`), because the existing
  repository rule ignores all new Markdown files. The requested plan can now be
  versioned without unignoring unrelated documents.

## Acceptance evidence

| Check | Expected result |
|---|---|
| Same request, different associative key order | Same fingerprint |
| Different website/account/location/filter/sort/limit | Different fingerprint |
| Missing or expired ordinary read | No DFS call |
| Explicit refresh of fresh data from another module | Zero extra DFS calls |
| Two simultaneous refreshes | At most one provider dispatch |
| Successful empty result | Cached as real empty data |
| Malformed/provider failure or transport timeout | Error surfaced; previous response/timestamp preserved |
| Retry during failure guard | No DFS call |
| Refresh succeeds but DB persistence fails | Explicit error; not success-shaped |
| Legacy keyword cache | Still readable without a paid request |
| Keyword-sample to Relevant Pages transition | No cross-source diff/New/Lost or connecting trend line |
| Relevant Pages total_count > returned count | Coverage displayed; no claim of complete traffic |
| Missing top keyword/referring domains | N/A, not fabricated |
| Failed migration/table unavailable | Explicit setup failure before any provider dispatch |

## Requirement mapping

| Requirement | Plan items | Implementation evidence |
|---|---|---|
| REQ-001 | 1.1, 1.3, 3.1 | Shared service plus two consumers |
| REQ-002 | 1.2, 1.3 | Canonical fingerprint and unique key |
| REQ-003 | 1.3, 2.1 | Read-only path and provider-call-count checks |
| REQ-004 | 1.2, 1.3, 4.3 | Fresh reuse and two-connection lock check |
| REQ-005 | 1.2, 1.3 | Separate attempt state and last-good response |
| REQ-006 | 1.2, 1.3 | Dataset columns and response metadata |
| REQ-007 | 2.1, 2.3 | Relevant Pages parser and coverage labels |
| REQ-008 | 2.2, 2.3 | Snapshot identity boundaries |
| REQ-009 | 3.1 | Content-pillar shared requests |
| REQ-010 | 1.1, 2.1, 2.3, 3.1 | Existing auth/cooldown and UI paths |
| REQ-011 | 4.1, 4.2, 4.3 | Controlled tests and persistence evidence |
| REQ-012 | 4.4 | README, schema and rollout results |

## Second rollout: saved enrichment and endpoint reuse

Implemented on 2026-10-30. These additions preserve the existing read/refresh API
contracts, do not introduce new credit charges, and never initiate paid requests
on ordinary page loads.

| Requirement | Acceptance criterion | Tasks / evidence |
|---|---|---|
| REQ-013 | Reuse saved citations with exact URL identity, source dates and explicit missing/error states | T012-T015; `TopPagesEnrichmentService`, `PageUrl` |
| REQ-014 | Reuse exact ranked-keyword and domain-overview datasets without conflating different coverage | T016; `DfsDatasetService`, `SiteOverviewService` |
| REQ-015 | Display current enrichment separately from saved organic history; preserve old report snapshots | T014-T015; Top Pages payload/view/JS |
| REQ-016 | Preview paid-refresh intent and require confirmation when a new provider call is expected | T017; additive `refresh_preview`, browser confirmation |
| REQ-017 | Expose basic freshness/failure/cost diagnostics without representing latest-response cost as lifetime spend | T018; `dfs:datasets`, info-level dataset events |
| REQ-018 | Preserve existing pages and keep this renamed plan in Git | T019-T020; regression/browser checks, staged plan |

- [x] T012 [Plan:5.1] Add `PageUrl` to normalize scheme/host and remove fragments
  without lowercasing paths/queries. Apply it to AI Visibility cited-page grouping.
  Reject unsafe links; do not merge schemes, www aliases, or arbitrary query strings.
- [x] T013 [Plan:5.2] Add `AiVisibilityResponseModel#latestCitationSample`, selecting
  the latest completed non-simulated run for the authorized website's matching
  country/language/project location. Limit to 1,000 successful responses and report
  truncation. Never use simulator output or competitor-domain citations.
- [x] T014 [Plan:5.3] Add `TopPagesEnrichmentService`: read saved Google citation
  keyword samples, AI Visibility response citations, domain overview and organic
  keyword details. Deduplicate Google URL/keyword pairs, AI URL/response pairs,
  prompts across platforms and repeated links within a response.
- [x] T015 [Plan:5.4] Add current source/freshness/citation panel, current scanned
  prompt counts, and saved keyword/backlink details to Top Pages. Missing data stays
  N/A. Current enrichment is returned separately, never written into old organic
  snapshots or used to create citation trend points. Older selected reports do not
  receive current per-row enrichment. The separate current-source panel stays
  explicitly labeled as current.
- [x] T016 [Plan:5.5] Add exact-key ranked-keyword and domain-overview methods to
  the shared layer. Migrate Site Explorer's domain metrics, 50-organic-keyword,
  50-paid-keyword and 30-AI-Overview-keyword refresh requests without changing their
  request shapes. Top Pages reads the saved organic sample for keyword/backlink
  fields without buying it. Other Site Explorer requests remain unchanged.
- [x] T017 [Plan:5.6] Add non-billable Top Pages refresh preview, reuse/fetch
  explanation and confirmation for anticipated paid calls. Do not invent a
  monetary estimate. Saved enrichment makes no additional provider calls.
- [x] T018 [Plan:5.7] Add the read-only `php8.5 spark dfs:datasets` command for
  dataset freshness, failed attempts and latest stored response cost. Add info
  events for read/miss, dispatch, fresh-refresh reuse and lock conflicts. These
  events require info logging to be enabled; they are not persistent analytics
  counters or a lifetime-spend dashboard.
- [x] T019 [Plan:5.8] Add saved-enrichment and endpoint-reuse regression checks.
  Keep the existing shared-cache/persistence checks and verify affected pages.
- [x] T020 [Plan:5.9] Stage `docs/DFS-plan.md`, retain the exact `.gitignore`
  exception, and update the README. No commit/push is made without a request.

### Compatibility and missing-data rules

- Google legacy empty citation caches are `unverified` unless they have an
  explicit successful-fetch marker. They are not confirmed zeros. Provider errors
  during citation refresh no longer overwrite the previous successful payload.
- Optional-source exceptions are logged and surfaced per source; they do not
  take down the main Top Pages report.
- Cited Pages counts the union of own-site URLs in the available saved citation
  samples, including URLs outside the organic top-page sample. It is not a
  web-wide count. Google and AI Visibility details stay separate.
- Scanned prompt counts mean distinct configured query IDs (or exact prompt text
  when no ID exists) citing that URL in the selected completed run. Repeated links
  and multiple platforms do not inflate that prompt count.
- Source dates, sample coverage and staleness are visible. Domain traffic is
  displayed separately and never added to returned-page traffic.
- Keyword/backlink detail is supplemental and dated by its saved source; it
  cannot override Relevant Pages traffic or keyword counts.
- AI Visibility historical run records do not snapshot country/language/domain.
  Eligibility is checked against the current project context. If project context
  editing is added, run-level context snapshots are needed before reusing old runs
  across context changes.
- The cost preview is advisory: another module can refresh between preview and
  execution. Server-side freshness rechecking still determines reuse.

### Second-rollout verification

- `tests/standalone/top-pages-enrichment.php`: controlled saved-source tests cover
  URL case, unsafe/external URLs, deduplication, real zeros vs missing data, source
  dates, failure isolation, saved keyword/backlink detail, shared domain overview,
  no history rewrites and no provider calls during reads.
- Existing shared dataset and real-MySQL locking/persistence regressions retained.
- PHPUnit regression files added, but PHPUnit remains unavailable locally.
- Read-only monitoring command verified against the migrated database.
- Authenticated Top Pages read returns HTTP 200; an actual legacy empty Google
  cache appears as unverified, domain metrics show their own older date, and
  missing AI Visibility data is not fabricated.
- 36 saved-enrichment checks, six citation-refresh compatibility checks, 42 shared
  dataset checks and 11 MySQL persistence/locking checks passed without paid calls.
- Authenticated navigation to Site Explorer, AI Visibility/Visibility, Keyword
  Research, Keywords and Top Pages returned HTTP 200 with no JavaScript page errors.
- Controlled browser data verified citation/platform display, saved keyword/zero
  backlink enrichment, historical-row isolation and cancelling a paid-refresh
  confirmation with zero refresh requests. Browser interception was removed.

### Follow-up cached-report review (2026-10-30)

- Fixed repeated Analyze/site-switch loading: clearing search/filter previously
  redrew old table rows after report data was reset, causing a null-data exception.
  Clear rows first and guard missing enrichment data. Added executable regression
  `node tests/standalone/top-pages-reload.js`.
- Browser-verified initial load, repeated Analyze, switching stockprices.com to
  webcrawlers.com, analyzing again and switching back: five HTTP 200 cached-search
  responses, correct website IDs/titles, no page errors or refresh requests.
  Analyze reloads saved data; changing the report website loads it immediately.
- Re-ran all four standalone enrichment/shared-dataset suites: 95 checks passed.
- Reviewed the authenticated stockprices.com report against the supplied newer
  Top Pages design. Navigation, breadcrumbs, report actions, saved-date selector,
  device disclosure, summary, chart and table are present. Unsupported provider
  capabilities remain explicitly unavailable rather than copying mock data.
- Verified 390/768/1440 viewport widths in light and dark themes. No document
  overflow after responsive layout settled; an initial measurement during the
  viewport transition was transient and did not require a CSS change.
- A non-matching URL filter shows an empty table; clearing it restores the data.
  Verified the CSV payload contains 13 columns and all 116 matching saved rows.
- The report is still a legacy ranked-keyword sample with one saved observation.
  Its chart shows observed dots, not fabricated historical trends.
- Its Refresh action is correctly disabled during the existing 24-hour cooldown.
  No cooldown bypass, paid refresh, commit or push was performed. End-to-end
  validation with a new live Relevant Pages response remains pending an eligible,
  explicitly approved refresh.

### Citation refresh wiring correction (2026-10-30)

The saved-only rollout did not provide a usable caller for
`fetchAndStoreAiOverviewCitations`. Site Explorer overview Refresh does not call
it; earlier instructions to refresh citations there were incorrect. Saved-source
reuse alone did not satisfy the requested citation-fetching workflow.

- Added **Refresh Google citations** in the Top Pages source panel, separate from
  organic Refresh data and its cooldown.
- Added authenticated `POST /api/v1/top-pages/citations/refresh`, reusing the
  existing website authorization and country validation. Calls the existing
  citation-fetching service, then returns the report with updated enrichment.
- Confirms potential paid intent before dispatch. Reuses fresh exact-context
  30-keyword AI Overview samples for 24 hours; otherwise may purchase one DFS
  request. Shared locks, retry guards and last-good preservation remain in force.
- Ordinary reads remain cache-only. No AI Visibility scan, organic-page purchase,
  domain/keyword enrichment purchase or historical organic rewrite is triggered.
- Expanded standalone citation coverage from six to 16 checks: the actual Top
  Pages service entry, displayed citation evidence, exact request, fresh reuse,
  failure preservation and no invented organic history. All 16 pass; the 36
  enrichment checks and JavaScript reload regression also pass.
- Runtime invalid-input probe returns 422 before any provider request. Controlled
  browser test verifies cancellation sends zero requests, confirmation sends one
  intercepted request and its citation displays without JavaScript page errors.
  Interception was removed and the real cached report restored. No paid calls
  were made during implementation/testing.

### Site Explorer request reduction (2026-10-30)

- Default refresh now updates only the core summary: at most two DFS requests
  (domain overview and domain backlinks summary), or one if the matching domain
  overview is already fresh. Cached page loads and fresh repeat refreshes make
  zero provider requests.
- Added explicit scopes for signals, content pillars, history, countries, SERP
  features, organic, paid and backlinks. All expired sections remains available
  as an explicitly confirmed, potentially expensive action.
- Enforced independent existing 24-hour section cooldowns in the overview
  orchestration. Existing reports, response fields and cache rows remain readable.
  New `metric_signals` and `content_pillar` section values use the existing table,
  with no schema migration. Legacy embedded enrichment dates are preserved.
- Added per-section dates/refresh metadata and UI scope disclosure. Missing
  optional metric signals are not displayed as zero. Section refresh failures
  that leave data expired are disclosed rather than announced as updated.
- Country distribution now reads/refreshed shared exact-context domain datasets,
  avoiding a duplicate selected-country overview purchase.
- AI Overview counts in signals/SERP features now use the same limit-30,
  traffic-sorted AI Overview dataset as Top Pages citations. No separate limit-1
  count purchase is required when that dataset is fresh.
- Do not merge the two domain backlink summaries: their status/rank/options
  differ. Likewise competitor requests with differing coverage remain distinct.
- Corrected the earlier request estimate: `domainRankOverviewBatch` dispatches
  one HTTP request per country. The old full-refresh path was approximately 33,
  not 24, with ten countries and the usual competitor/baseline branches. The new
  controlled equivalent is 31; the important saving is making those optional
  calls explicit instead of attaching them to every summary refresh.
- `tests/standalone/site-overview-refresh.php`: 23 controlled checks cover exact
  counts (core 2 / full 31 / fresh repeat 0), independent scopes, preserved
  unrelated timestamps, country/AI dataset reuse, failed-source preservation and
  invalid-scope rejection. No network calls.
- Authenticated cached API returned 200 with all nine section metadata entries;
  invalid refresh scope returned 422 before any provider call. Browser-controlled
  refresh verified cancel = zero requests, confirmed history/all scopes, cooldown
  updates and no JavaScript page errors. Interception removed, real cache
  restored. No overflow at settled 390/768/1440 widths.
- No paid refresh, commit, push or credit-policy change was performed.

### Third rollout: Backlink Gap, tiered TTLs, and spend counters (2026-11-04)

- **Backlinks & Competitor Datasets:** Integrated `backlinks/domain_intersection/live`, `backlinks/bulk_pages_summary/live`, `backlinks/summary/live`, `backlinks/history/live`, and `backlinks/referring_domains/live` into `DfsDatasetService`.
- **Tiered Volatility TTL Policy:**
  - Backlinks and domain intersections: 14 days
  - Competitors and relevant pages: 7 days
  - Domain overview and historical rankings: 3 days
  - Ranked keywords: 2 days
  - Default fallback: 24 hours
- **Live Spend & Activity Counter:** Implemented `spendSummary()` on `DfsDatasetModel` and `getSpendSummary()` on `DfsDatasetService`. Added daily (UTC), monthly (UTC), and total stored envelope cost counters directly into `php8.5 spark dfs:datasets`. No artificial spend limits are enforced on outgoing calls, ensuring uninhibited operations while maintaining complete financial transparency.
- **Top Pages Device UI Disclosure:** Hidden the placeholder device dropdown from Top Pages since DataForSEO Labs Competitor Research endpoints (`relevant_pages/live`) combine device metrics across desktop and mobile.

## Remaining increments: not automatically enabled

1. Extend shared datasets to remaining ranked-keyword/domain-overview callers,
   after inventorying effective options. Existing SERP-feature count and extra
   metric requests are not migrated yet. Never conflate 30/50/1,000-result samples.
2. Expand enrichment only where a compatible saved source exists; do not buy
   automatic keyword/backlink/AI enrichment on a page read.
3. Adapt Keyword Research without silently changing existing billable actions,
   limits or plan-credit charging. Agree whether a cache hit consumes a credit.
4. Reuse existing SERP snapshots by compatible date/location/device/depth; do not
   replace their time-series schema with a latest-response cache.
5. Consider importing validated log responses with known request/account/user
   provenance. Do not search arbitrary logs on interactive page loads.

## Deployment and rollback

- Deploy/apply the additive migration before enabling the new consumers.
- Do not delete the old `top_pages` section or existing snapshots.
- Reverting the consumer code leaves old caches intact; the new table may remain
  unused. Drop it only after confirming no consumers need it.
- Cached reads are free; explicit Refresh may incur normal provider cost.
- MySQL named-lock availability is a deployment prerequisite. A lock/setup failure
  must not silently bypass coordination and call DFS.
- No commit, push, paid refresh, cross-customer sharing, or credit-policy change is
  part of this execution.
