# Meta API Call Reduction Plan

## Goal

Reduce repeated Meta requests without changing campaign steps, choices, approvals,
or live validation before publishing. Use the existing database-backed Laravel cache;
no Redis, new dependencies, or schema changes are required.

## Baseline

Audit-log sample inspected on 2026-10-16, covering the preceding seven days:

- 846 Meta calls; 695 were reads.
- 139 interest searches for 71 distinct account/normalized-term combinations.
- 81 Page-list calls and 41 ad-account-list calls.
- 12 recorded rate-limit failures, all on ad-account listing.

Repeated terms are an opportunity, not a guaranteed savings estimate: reuse depends
on timing, credentials, account, API version, and cache expiry.

## Existing Protections

- CallLogger deduplicates successful identical reads within a request.
- Hourly quota refusals are not immediately retried.
- Location discovery already caches searches for one day.
- Audience sizing already caches results for ten minutes.
- Local hourly budgets are separate from Meta's actual quota.

## Cache Storage

The current environment uses `CACHE_STORE=database`. Laravel's database cache
store uses the application's default database connection and the `cache` table:
`key` identifies an entry, `value` holds its serialized response, and `expiration`
is a Unix timestamp. Discovery keys start with `platform-discovery:` (after the
application cache prefix). Quota pauses use `meta-quota-cooldown:` keys in the
same store. Neither feature stores cache entries in `allowed_ad_accounts`.

Each lookup checks current account authorization, then request-local memory,
then persistent cache. Eligible Graph misses acquire a shared cache lock and
recheck authorization and cache before cooldown/budget checks and HTTP.
Successful discovery responses are saved with the endpoint's configured TTL.
Expired entries are not served; a later successful lookup replaces them.

Interest discovery now lasts seven days. Selection and publish-time interest
validation are not persistently cached, so old search suggestions cannot bypass
Meta's current validity check.

## Allowed Ad Accounts

`allowed_ad_accounts` already contributes active platform-specific account IDs to
the guardrail, together with configured IDs. These checks also run before cached
account-scoped responses are returned. Disabling a database row does not revoke
an account that remains explicitly allowed by configuration.

The draft account chooser now uses active explicit Meta rows for IDs and stored
names, marked unverified until normal selection verification succeeds. A wholly
database-managed explicit list requires no Meta discovery calls. Mixed lists still
discover config-only accounts, and wildcard permissions still require provider
discovery. Other platforms and inactive rows do not supply local Meta choices.
If the table is unavailable, a warning is logged and config-only discovery remains
available, preserving the guardrail's existing bootstrap fallback.

The table does not prove token access, remote account status, currency, or
publishing permission. Those checks remain live on account selection. No account
is attached to the campaign just by displaying it. Stored names are display
metadata, not a generic API cache. Disable this optimization with
`META_DB_FIRST_ACCOUNT_CHOOSER=false` to restore provider-backed discovery.

## Rollout

### 1. Discovery Cache (Implemented)

The original discovery cache opts in these successful Graph responses:

| Endpoint | Initial TTL |
| --- | --- |
| Account interest search (`targetingsearch`) | 7 days |
| Ad-account discovery (`me/adaccounts`) | 5 minutes |
| Page discovery (`me/accounts`) | 5 minutes |

Normalize interest-search whitespace and casing. Include a hashed token identity,
API version, endpoint, account, and complete query in cache keys. Never put raw
tokens in cache keys or log cache hits as remote calls. Enforce the current account
allowlist even when a response is cached. Failed calls must not populate the cache.
Credential rotation naturally selects a new cache namespace.

Keep account permission details, interest validation, publish verification, writes,
activation, deletion, signed asset URLs, and processing-status polling outside this
persistent discovery cache. Cached discovery does not prove publishing permission.

### 2. Shared Quota Cooldown (Implemented for Graph)

When Graph returns a known Meta quota refusal, persist a short cooldown across
requests. Scope account limits to that account, and broader limits to the token
identity. Reuse safe cached discovery during cooldown, but refuse fresh requests
without HTTP calls. Do not cache permission failures as empty lists or automatically
retry writes. Expiry allows a new attempt; it is not a promise that Meta quota reset.
Rollback/deletion must remain possible.

Implemented classification uses Graph error codes 4, 17, 32, 613, and 80004.
Code 80004 and subcode 2446079 use an account-specific scope when the request
identifies an account; otherwise the current token is paused. Other recognized
limits use token scope. The default cooldown is five minutes. Changing API version
does not bypass the cooldown; changing the token creates a separate scope.

This does not coordinate different tokens belonging to the same Meta app, nor
apply cooldowns to MCP: that needs reliable app identity and structured MCP quota
diagnostics. Existing MCP retry behavior is unchanged.

### Configuration

| Environment variable | Default | Purpose |
| --- | --- | --- |
| `META_INTEREST_CACHE_SECONDS` | `604800` | Account interest discovery |
| `META_DISCOVERY_CACHE_SECONDS` | `300` | Ad-account and Page discovery |
| `META_RESOURCE_CACHE_SECONDS` | `300` | Account/business pixels and saved audiences |
| `META_TARGETING_CATALOG_CACHE_SECONDS` | `3600` | Detailed-targeting browse and demographics catalog pages |
| `META_QUOTA_COOLDOWN_SECONDS` | `300` | Known Graph quota refusals |
| `META_DISCOVERY_COALESCING` | `true` | Lock eligible Graph discovery misses |
| `META_DB_FIRST_ACCOUNT_CHOOSER` | `true` | Offer active explicit database accounts as unverified choices |

Set TTL/cooldown values to zero, or boolean flags to false, to disable a feature.
These values are read through `config/platforms.php`. The cache uses the
application's existing default store.

Interest searches reuse the existing interest-search cache TTL. Other
detailed-targeting searches, related suggestions, browse and demographics
catalog pages use the separate one-hour TTL.
They use CallLogger's credential-, API-version-, account-, and query-scoped
cache, so current account permission is still checked on cache hits, empty
results are not persisted, and cache hits do not create remote-call audit rows.
The browse/catalog data is discovery metadata only; selection validation and
delivery estimates remain live.

### 3. Pixel and Saved-Audience Discovery (Implemented)

Account pixel lists, business-owned pixel lists, and all pages of saved-audience
discovery share the existing credential-, version-, account-, and query-scoped
cache. Successful empty lists are cached; failed reads are not. The account
details used to find a pixel's parent business remain outside persistent caching.

Pixel/audience creation changes that resource's cache generation for the current
credential/API-version scope. Object updates and deletion conservatively change
both resource generations because an object ID alone does not identify its type.
This also invalidates request-local reads and every pagination variant. In-flight
reads can only populate an old generation. Invalidation runs even if a write
throws, since a lost response does not prove that the provider rejected the write.
Other credentials/API versions refresh on their own TTL or explicit fresh read.

Pixel selection, duplicate-pixel prevention, website-audience creation checks, and
replacement-pixel checks bypass both cache layers. Publishing verifies the selected
pixel and saved audiences live before creating provider objects. Audience-size
reports also stay live so cached counts are not presented as fresh measurements.
Discovery suggestions do not prove current access or publishing eligibility.
Page selection also bypasses both cache layers; only the Page chooser uses cached
discovery. Account and business pixel discovery follows each next-page cursor,
deduplicates shared pixels, and refuses repeated cursors or more than 20 pages
rather than silently returning an incomplete account list.

### 4. Usage Telemetry (Implemented)

Graph responses expose allowlisted numeric metrics from `X-App-Usage`,
`X-Ad-Account-Usage`, and `X-Business-Use-Case-Usage` through structured application
logs. `Retry-After` seconds or HTTP dates become `retry_after_seconds`. Provider
field units remain unchanged: in particular, `estimated_time_to_regain_access`
is in minutes, not seconds. Failures also retain usage and HTTP status in the
remote-call audit diagnostics. Successful response bodies remain unchanged.

Raw headers, tokens, arbitrary keys, and nonnumeric metric values are not logged.
Malformed headers produce a warning without exposing their content or failing an
otherwise valid response. Cache hits generate neither synthetic telemetry nor
remote-call audit rows. This is observability only: usage headers do not yet
change cooldown duration, retries, or throttling decisions.

### 5. Discovery-Miss Coalescing (Implemented)

Only persistent-cache-eligible Meta Graph discovery misses are locked. The shared
lock uses the same credential/version/account/query/resource-generation namespace
as the cache entry. After acquisition, permissions and cache are rechecked, so a
waiting caller can reuse the completed result without HTTP. Expired entries are
never served. Locks release on success and exceptions; failures are not cached.

Callers wait at most five seconds before an explicit retry-later error, with no
duplicate provider call. The 240-second lease covers the normal three 60-second
read attempts and retry backoff. Fresh validation, uncached reads, writes, reports,
and rollback deletion are not coalesced. Database storage uses the existing
`cache_locks` table; no migration or new cache dependency is required. Set
`META_DISCOVERY_COALESCING=false` to disable locking while retaining discovery
caching. Tests exercise overlapping-request interleavings and timeouts with both
array and database cache drivers; production concurrency savings remain to be
measured.

### 6. AI Terms and Display Metadata (Implemented / Verified)

The merged application already stores successful audience phrases on the brief
as `audience_phrases`, reusing them on later turns without a second model call.
Replacing page analysis removes the old terms, including when reanalyzing the same
URL. Added regression coverage verifies regeneration and reuse without changing
suggested interests or the visible audience-choice flow. No duplicate AI cache
was introduced.

Short-lived display/discovery metadata reuse is covered by account, Page, pixel,
and saved-audience caches and the unverified DB-first account chooser.
**Reports remain live by explicit scope choice.** No report cache or adaptive
throttling is added. Batch requests are not treated as free Meta quota, and local
limits are not increased as a quota workaround.

## Verification

- Separate API instances share successful discovery results.
- TTL expiry, credential rotation, version changes, and account changes miss cache.
- Revoked local account permission is denied even with a cached result.
- Live validation and writes still reach Meta; failures do not enter cache.
- A quota refusal blocks subsequent fresh calls only within the matching scope.
- Cached discovery works during cooldown; expiry permits recovery.
- Existing audience selection, budget, Page, and publish tests continue to pass.

## Rollback and Measurement

Set discovery TTLs and cooldown duration to zero, and both boolean optimization
flags to false, to disable these features.
Expire existing entries rather than flushing unrelated application caches. Compare
actual api_calls counts and throttle errors per account before and after rollout;
do not write synthetic remote-call audit rows for local cache hits.

## Implementation Evidence

- Implemented in GraphApi, CallContext, and CallLogger; no campaign tool signatures
  or campaign steps changed. Environment overrides are listed in `.env.example`.
- GuardrailBudgetTest covers cross-instance reuse, normalized interests, expiry,
  token/version/account isolation, current authorization, live interest validation,
  failure handling, pagination, exhausted local budgets, scoped cooldowns, cached
  discovery during cooldown, credential rotation, and rollback exemptions.
- Initial neighboring regression run: 144 tests passed, 464 assertions.
- Focused final behavior run: 21 tests passed, 62 assertions.
- Final regression run after formatting: 196 tests passed, 667 assertions, covering
  targeting, Page/account discovery, publishing, retries, fresh readback, error
  messages, and audit logging. `git diff --check` passed.
- The original cache rollout used no live Meta API requests for validation.
- Resource-cache follow-up: 242 focused tests passed, 892 assertions, covering
  caching, pagination invalidation, expiry, isolation, failed reads, in-flight
  invalidation, pixel/audience creation, duplication, and fresh publish refusal.
- Full suite after the resource-cache follow-up: 3,803 tests, 3,782 passed,
  20 failures and one error. The failing/erroring test identities match the
  pre-change run exactly; all 23 added tests pass. This is a comparison against
  the current merged checkout, not proof that master itself is green.
- An intermediate full run exposed two previously offline ad-set-builder tests
  reaching Graph with a dummy token. Meta rejected both reads; no write was
  attempted. Fresh pixel verification now runs at publish entry points, and
  those builder tests reject stray HTTP requests.
- All 20 original failures and the original error are now repaired. Tests retain
  the newer pause readback, six performance windows, delivery-aware ROI health,
  current recommendation UI, full creative titles, and video previews. A real
  targeting-provenance bug was fixed: country and placement source tracking now
  checks whether those fields were offered instead of treating their names as
  truthy booleans.
- Before the remaining roadmap changes: 3,803 tests passed, 14,666 assertions.
- Added 22 roadmap test cases covering sanitized quota telemetry and recovery,
  unchanged response bodies, cache-hit telemetry suppression, lock contention,
  bounded waits and release on failure on array/database stores, AI term
  invalidation/reuse, DB-first account choices, wildcard/config-only discovery,
  missing-table fallback, live selection refusal, and local account revocation.
- Final focused roadmap run: 109 tests passed, 476 assertions.
- Final full suite: **3,825 tests passed, 14,781 assertions, zero failures/errors**.
  Pint and `git diff --check` passed. HTTP-dependent additions use fakes; no live
  Meta writes were used. This verifies the merged working checkout, not a
  separately tested master baseline or production performance improvement.

## Older Review Recheck and Actions (2026-10-22)

Status: follow-ups implemented and validated after discussion. The cooldown
policy was explicitly approved for retention rather than silently narrowed.

### Confirmed Checks

- Rechecked current source and the registered scheduler, rather than relying on
  the old PR's line numbers or file count.
- Empty interest responses are not persistently cached; previously cached empty
  results are ignored. Successful empty account/Page/resource lists deliberately
  retain their short discovery TTLs.
- Database cache pruning exists and is scheduled daily at 03:10.
- Concurrent eligible discovery misses have shared locks and bounded waits.
- The old three-title-term cap is absent from the current keyword fallback.
- Current authorization still precedes cached responses, and cache keys retain
  account and credential isolation. Preserve both.
- A focused run of cache, pruning, analyzer and keyword tests passed:
  87 tests, 330 assertions.
- Separately reproduced the form-wrapper defect using the current removal
  expression: zero headings remained and body text became "Contact us".
  Existing passing tests do not cover that layout.

### Original Action List

1. **Preserve meaningful content inside form wrappers (highest priority).**
   Avoid deleting whole forms or structural fieldsets that may contain the page's
   hero. Continue excluding control options, labels and validation noise.
   Decide the exact extraction rule from representative fixtures before editing;
   simply capturing all pre-strip text would restore the original keyword noise.
   Add fixtures for form-wrapped heroes, fieldset-wrapped content, and ordinary
   signup forms. Assert headings, copy/review text and useful keywords survive
   without reintroducing form-only terms.
2. **Review quota cooldown scope before changing behavior.**
   Current codes 4, 17, 32 and 613 pause the token, including writes; 80004 or
   subcode 2446079 narrows to the account when available. Verify current official
   Meta documentation and structured diagnostics for each code. Record the
   scope and unknown-scope policy, then agree the behavior before implementing.
   Do not automatically classify every failure as account-local or exempt writes
   from a genuinely shared quota. Preserve cached discovery and rollback access.
   Add cross-account read/write tests for any approved policy changes.
3. **Clarify the audit contract.**
   Document that api_calls records attempted remote requests, not every user
   lookup. Do not add cache-hit rows that distort call budgets or provider-call
   counts. Separate cache-access auditing would be a new requirement.
4. **Document interest query normalization.**
   State that whitespace normalization and lowercasing affect both the outbound
   Meta query and cache identity. Preserve existing behavior.
5. **Explain price versus review extraction.**
   Resolve form-wrapper handling first; then document why price extraction uses
   pre-strip text while review/copy extraction excludes control noise, if that
   distinction remains.
7. **Make test cache isolation explicit.**
   Pin the guardrail fixture's initial cache store to array before any flush.
   Keep database-lock tests on the isolated test database; do not flush shared
   application cache stores.

### Scope and Validation

- Keep reports and final selection/publish checks live.
- Preserve newer master behavior; do not reopen already-resolved findings.
- The Graph client resolves a shared PlatformConnection token with configured
  fallback, not a token selected for the current user. Cache scope follows that
  actual token and API version. Per-user credential redesign is not proposed.
- Run affected analyzer/keyword, guardrail/cooldown, phrase-reuse and pruning
  tests as relevant, then Pint and the full suite after code changes.
- No application code was changed during this recheck/action-recording step.

### Completed Follow-Ups

- Preserved form and fieldset wrappers during extraction. Controls and marked
  validation messages are removed without deleting the offer's ancestors.
  Product-choice labels containing radio/checkbox controls or structured offer
  content are preserved; ordinary field labels remain excluded.
  Common unmarked signup validation spans are filtered within those wrappers;
  this is not a universal classifier for every site's custom validation markup.
  Form/fieldset fixtures now verify surviving headings, subheadings, body/review
  copy, keywords, CTAs and prices while excluding control/validation noise.
- Retained pre-strip price extraction deliberately: a select option can carry a
  real plan price, even though its label must not enter the review/copy text.
  Tests assert that distinction explicitly.
- Verified the official [Meta rate-limit reference](https://developers.facebook.com/docs/graph-api/overview/rate-limiting/):
  code 4 is app-level; 17 is user-level; 32 concerns Pages user/app limits;
  613 is API-specific/custom (1996 describes inconsistent app request volume).
  None of these code values alone proves an ad-account-local limit.
- The user selected **keep current conservative scopes; document and test them**.
  Consequently, 4/17/32/613 retain token-wide cooldowns including writes, while
  80004 and the existing legacy 2446079 classification retain account scoping
  when an account is known. Seven new cases exercise cross-account writes,
  including generic and legacy 17, 613/1996 and 80004/2446079.
- Scope limitations remain explicit: token-wide storage does not coordinate all
  tokens for one app/user, and Page/custom limits may pause unrelated operations
  on that token. Meta documents 17/2446079 for Ads API v3.3 and older; retaining
  that compatibility branch is not proof that modern generic code 17 is local.
  Finer Page/API buckets and cross-token app identity require a separate design.
  Cached discovery and rollback deletion remain available as before.
- Clarified CallLogger's class contract: api_calls counts remote attempts, not
  cache accesses; no synthetic cache-hit audit rows were introduced.
- Remove the old audience_phrases key when saving generated phrases or reusing
  current v2 phrases. Tests cover both legacy-only and legacy-plus-v2 briefs,
  preserving unrelated metadata without extra AI calls. No bulk data rewrite.
- Documented outbound interest-query normalization and pinned the guardrail
  test fixture to array storage before flushing. Database-lock cases continue
  using the isolated test database.
- Final targeted run: **137 tests passed, 608 assertions**.
- Final full suite: **3,835 tests passed, 14,859 assertions**. Pint and
  `git diff --check` passed. No live Meta writes were used; changes are uncommitted.