Shopper personalization¶
Shopper personalization is an additive, default-off serving capability. It never changes a Recommendation Snapshot or queries a merchant data source while serving. The integrating Commerce Property supplies an authenticated principal, a signed property-scoped Shopper context, and ordered interactions.
Runtime boundaries¶
AuthorizationAndAbusePolicyvalidates the authenticated principal, property scope, role, and purpose-specific authorization assertion before Shopper state is read or written.ShopperInteractionServicecommits the idempotency record, retained ledger entry, lifecycle barrier, and compact Shopper Profile projection in one control-database transaction. Only then does it issue an Interaction Acknowledgement and causal token.ShopperStateRepositoryowns retention, deterministic rebuild, suppression, deletion receipts, and full(data source, Commerce Property, Catalog, Shopper)isolation.PersonalizedRecommendationServicereads a bounded profile and reranks at most 100 eligible candidates from the current Snapshot by default. When a scope has a published opt-in ANN artifact, For You may instead retrieve eligible Catalog Items from that same generation. It preserves each retrieved candidate's Product ID, representation-specific score, low confidence, and ANN provenance while reranking; only rank changes.PersonalizationCapabilityRegistrygates every enabled scope and API version. No configured capability preserves ordinary serving of the registered trained strategies (currently eleven).- The worker runs bounded expiry, checkpointed rebuild, and deletion reconciliation independently of Training Runs.
The Serving API delegates candidate loading and fallback decisions to
RecommendationServingService. SnapshotLaneLoader preserves lane-local candidates;
ForYouCandidateLoader obtains its global union and Best Sellers fallback from one joined
repository read of the serving head. Publication or retention between calls cannot mix their
snapshot identities. An absent fallback is a classified failure; a valid empty fallback remains
insufficient evidence. The composition
root chooses AuthorizedPersonalization only when the complete authorization/reranking runtime is
available; otherwise UnavailablePersonalization supplies the ordinary fallback. HTTP status and
telemetry translation remain in the API adapter. This changes code ownership without changing the
authorization, capability negotiation, causal, or response contracts below.
HTTP contract¶
POST /v1/personalization/interactions accepts a strict payload containing catalog_id, opaque
shopper_id, interaction_id, type, occurred_at, expected_sequence, and item_ids.
The Interaction API enforces an actual wire-byte cap before JSON parsing, defaulting to 2 MiB through
request_body_limits.interaction_bytes. Purchase Item counts have no independent schema maximum;
the transport cap bounds their input. Oversize input returns 413 request_body_too_large without
appending an interaction. Property authentication still precedes body reads and size rejection.
The closed V1 interaction vocabulary is viewed, cart_added, cart_removed, purchased,
authorization_changed, opted_out, and deletion_requested.
The authenticated property is derived from Authorization: Bearer …; it cannot be supplied in the
body. Personalization-Context is a short-lived signed value binding the same property and Catalog
to the opaque Shopper ID and authorization assertion. Personalization-Version negotiates the
enabled capability.
An accepted write returns its committed sequence, profile version, and a short-lived causal_token.
An exact retry returns the original acknowledgement. Reusing the interaction ID with different
content, or sending anything other than the exact next sequence, returns a typed 409 with the last
committed watermark. A failed transaction never returns an acknowledgement.
A valid authorized business interaction whose occurrence is at or before the current scope's history boundary still advances the exact next sequence and profile version. It adds no retained ledger payload, affinity, recent Item, negative signal, or interaction count. Its minimal idempotency acknowledgement expires relative to commit time. Exact retries recover that original acknowledgement within its retention window. Opt-out, authorization changes, and deletion take effect immediately at commit even when their occurrence timestamp is old.
Existing Serving API paths remain unchanged. Existing strategies opt in with personalize=true;
the new global for-you strategy implies a personalization attempt. Personalized reads accept the
same trusted context plus an optional Causal-Token. A valid causal token either observes at least
its profile version within 100 ms or returns causal_not_observed; the service never silently serves
a stale personalized order.
The additive personalization response member exposes only applied, not_requested, or
fallback, an optional bounded fallback reason, and whether the causal requirement was observed.
It never exposes a raw Shopper identifier, authorization details, profile features, versions, or
score contributions. Unknown, unauthorized, opted-out, deleted, and missing-history cases retain a
uniform recommendation response shape.
Candidate and profile behavior¶
Without ANN opt-in, existing strategies only reorder their own Snapshot candidates. for-you uses a deterministic,
deduplicated union of Best Sellers, Most Viewed, and Trending from one serving-head Snapshot. Its
ordinary fallback is Best Sellers, not the personalized union. Snapshot-scoped category and brand
features have an additive companion table and repository contract; serving never reads the source
Catalog. Training publishes Product ID, category, brand, and Recommendation Eligibility from the
same consistent Catalog read as the recommendation results, including ineligible Items. Feature
rows are staged in bounded batches before the serving head is activated; a failed publication
preserves the previous head and removes staged features. Snapshot retention removes the associated
features. Older snapshots without companion rows and Items with missing metadata still omit those
terms safely. Category and brand concentration limits can use the published metadata; affinity
terms additionally require populated Shopper Profile affinities, which the current interaction
projection does not yet derive from Item interactions.
An opt-in ANN scope is an exception to the candidate-union limit for for-you: the worker builds
one metadata or learned representation and eligible HNSW index from its consistent source read, then atomically
stores it with the Recommendation Snapshot. The authorized bounded Shopper Profile supplies positive
Item affinities for a normalized query; the existing projection weights purchases above views.
Recent and negative Items cannot be returned. Missing, corrupt, or unusable ANN evidence falls back
to the current bounded Snapshot path. The index never reads raw interactions and is not changed by
acknowledged interactions between Training Runs; those interactions can change the request query.
The same artifact can supply opt-in Similar Items retrieval. ANN distance is not calibrated
recommendation confidence. An explicit ann.model = "two_tower" selects aggregate-pair-trained
query/Item encoders instead of the default metadata SVD representation. Learned retrieval carries
learned_retrieval evidence and ann_two_tower provenance; metadata retrieval carries
metadata_similarity and ann_metadata. Both receive low confidence. The query encoder is exported
for NumPy serving; no PyTorch training occurs in the API. Read the
ANN engineering explanation for
training bounds, cold-load behavior, and qualification limits.
Configured contextual Swimlanes also consume authorized typed recent-view and recent-purchase projections separately from For You. Recent-purchase neighborhoods use at most ten seeds, while a step requesting purchase exclusion checks the complete retained purchase tuple (up to 100 Items). Purchases beyond the tenth seed remain excluded even without seed metadata or a published neighborhood. Steps without that exclusion retain their configured behavior, and exclusions can leave truthful unfilled quota. They use bounded published co-view/co-purchase neighborhoods as candidate sources and reserve eligible recent-view history for the terminal fill step. They preserve configured step order instead of applying the personalized lane scorer across steps. See Swimlane resolution.
The deterministic scorer combines normalized Snapshot rank with bounded item, category, and brand affinities, then applies seen, negative, and recent-item penalties and concentration limits. Product ID is the final tie-breaker. Missing feature rows are safe and simply omit those feature terms.
Shopper History defaults to a maximum of 90 days; deployment configuration may shorten it separately for each full Commerce Scope. API and worker compose the same immutable retention policy from all configured capabilities, including disabled ones. Interaction history expires relative to occurrence time; ordinary idempotency records expire relative to commit time. Unconfigured legacy state uses the explicit 90-day fallback. Injected application stores must agree with configured scope bounds. Maintenance and rebuild apply the earlier of stored expiry and the current policy deadline, so shortening a window does not wait for older 90-day timestamps. Increasing a window cannot restore already erased history. Serving reads hide a projection's features when its earliest signal has expired, its policy has shortened, or its dirty marker is set. The acknowledged sequence/version remains observable, and the existing insufficient-history fallback applies until a safe rebuild. The Shopper Profile's features are disposable and rebuildable from retained ledger entries. Its minimal scoped sequence/version header remains authoritative after feature expiry: maintenance never rolls an acknowledgement backward, and rebuilding publishes a newer profile version. When all history expires, recent Items, affinities and counts are empty and serving uses the insufficient-history fallback. The minimal header is retained for that scoped identity's ordering lifecycle until deletion; it contains no interaction payload or Item references. Erasure removes the profile and preserves only the existing suppression/deletion tombstone contract. Opt-out creates an immediate no-use barrier for reads begun after its acknowledgement. A request already reading the prior profile may finish using that profile; opt-out does not promise cancellation of in-progress requests. Deletion has the same acknowledged-read boundary and creates a durable receipt, after which bounded worker reconciliation purges the ledger, general idempotency records, and profile while retaining only the minimal tombstone required to prevent resurrection and replay the deletion acknowledgement.
Each expiry pass deletes at most 1,000 interaction rows and 1,000 ordinary idempotency rows, touching at most 100 expired interaction keys. Rebuild work visits at most 100 due keys and reduces at most 1,000 retained rows across the pass. Rows continue by sequence from a durable bounded checkpoint; feature state retains the existing 100 recent-Item and 256 affinity/count-key bounds. Physical deletion commits with dirty-state protection before rebuild work begins. Interruptions resume without exposing unfinished features. An appended tail can extend a checkpoint's immutable prefix; expiry of contributing signals or a shortened policy invalidates it. Publication holds the header lock and checks the captured version before advancing the profile version.
Manual rebuild_profile also advances at most 1,000 retained rows. If unfinished, it returns the
safe header rather than a partial feature payload. Deletion immediately removes the bounded
profile and any rebuild checkpoint, then erases at most 1,000 ledger/idempotency payload rows per
pass across claimed receipts. A receipt remains pending until no payload remains; the suppression
tombstone prevents resurrection throughout that work.
Simulation, evaluation, and experiments¶
Simulation Scenario personalization journeys use deterministic synthetic Shopper, Session, and interaction identities derived from the scenario seed and logical time. The journey adapter calls production-shaped Interaction and Serving seams and records only a safe alias, acknowledgement watermark, Snapshot ID, bounded outcome, causal observation, and rank delta. Recommendation-feedback journeys are explicitly excluded from independent relevance claims.
Offline evaluation splits chronologically within a property/Catalog/Shopper boundary and rejects
future-derived features. It compares the non-personalized Snapshot baseline with for-you or
permitted reranking using Recall@K, NDCG@K, coverage-related slices, and minimum-count suppression.
Metric summaries have a closed state: available evidence requires a positive integer observation
count and both finite rates in [0,1]; suppressed/not-applicable evidence retains neither value.
Counts remain nonnegative integers. Single-sided, nonfinite or out-of-range metrics are rejected
before serialization; unavailable summaries contain explicit null metrics.
Each report now declares one strategy and evaluation_schema_version = "2". An invocation
permits at most one observation per property/Catalog/Shopper key and strategy, rejecting replays
even when cohort labels or feedback mode differ. Counts represent distinct scoped evaluation
units with future truth, rather than replayed rows. The same opaque key in another Catalog is a
separate scoped unit, with a separate Catalog cohort. Feedback remains excluded from relevance
and is validated against the report's property boundary. Multi-strategy means are rejected until
their aggregate semantics are defined. Previous unversioned row-count evidence is not interchangeable.
The offline helper bounds each split and observation input sequence to 10,000 declared units by
default; callers may explicitly configure another positive integer bound. Large evaluations
require external streamed grouping, rather than an unbounded service registry.
Experiment assignment is default-off, stable for permitted units, versioned, and requires exposure
before outcome attribution. Offline and synthetic results are proxy/correctness evidence only;
conversion, revenue, retention, attribution, or causal uplift require controlled production evidence.
Assignments now carry the full Commerce Scope and explicit algorithm identity
hmac-sha3-512-json-v2. Assignment and exposure use distinct domain prefixes in canonical compact
UTF-8 JSON arrays, preserving HMAC-SHA3-512. Both frames include Data Source, Tracking ID, Catalog
ID, experiment/config identity, unit type and unit key; exposure also includes the exact variant.
The guard checks the complete stored assignment before reuse or attribution. Delimiter-separated
legacy material has no fallback verifier. Buckets can change: use a new experiment/config cohort,
regenerate authorized synthetic replay assignments and keep old/new evidence separate. This
format change does not rotate deployment secrets.
ExperimentExposureGuard is a single-Scope, single-owner offline batch helper. Its constructor
requires explicit maximum resident entries, positive attribution window, retention covering that
window, and an aware logical clock. There is no implicit production policy. Identical exposures
retain the first stored time, even at full capacity; an explicitly exposed different assignment
has its own identity. New admission at capacity raises ExposureCapacityError, without evicting
active evidence. Expired entries are pruned on operations, within the declared finite capacity.
Retention is exclusive at its deadline; absent/expired evidence rejects attribution. Outcomes
must occur at/after exposure, strictly before its attribution deadline, and no later than the
logical clock. Late attribution remains possible during retention for an outcome within its
window. Re-exposure after expiry cannot authorize an outcome preceding the new exposure.
close() clears the batch and refuses subsequent operations. Exported records retain digests,
scoped/versioned assignments and times, never raw assignment unit keys.
The helper provides no distributed, concurrent or durable exposure service. An operational adapter still needs atomic first insertion, deletion/retention ownership, complete Commerce Scope and selected lifecycle budgets. The maintainer must choose those budgets before adoption; the finite synthetic test windows are not deployment settings. Canonical HMAC byte/vector, collision, scope, capacity and expiry evidence lives in the evaluation contract tests.
Operational guardrails require finite error/fallback rates in [0,1], a finite positive latency threshold and finite nonnegative observed latency. Invalid measurements fail construction; missing measurements raise an unavailable-evidence error. Prospective rollout consumers must hold exposure on either failure, rather than treating absent breach codes as approval. Valid measurements retain the established error-rate, fallback-rate, then p95-latency breach ordering; values exactly at the threshold do not breach. This is an offline contract, not an implemented live rollout controller.
Deployment and rollback¶
The deployment JSON contains a personalization group with scope capabilities, env-backed property
credentials, accepted policy versions, and an env-backed signing secret. Secret values are resolved
only during API runtime construction and are excluded from configuration fingerprints and
representations. Enabled scopes require a signing secret of at least 32 bytes.
Apply migration 0008 before starting these binaries. It invalidates existing projections for bounded rebuild while preserving their causal headers and retained ledger. Drain older writers, which do not maintain signal deadlines. Keep personalization admission disabled when rolling back to a binary without dirty-state protection. The migration refuses downgrade while dirty projections or checkpoints remain. Ordinary Recommendation Snapshot serving remains available during reconciliation.
Service-owned credential fingerprints, causal-token Shopper bindings, experiment assignments and exposure correlation use SHA3-512 (HMAC-SHA3-512 where keyed). Newly issued causal tokens and Personalization-Context values carry version 2 and reject version 1; both are short-lived, so deployments should refresh in-flight contexts and acknowledgements across this transition.
Rollout remains an operational gate: synthetic validation, internal simulation, allowlisted write-only traffic, read shadowing, small exposure, then experiment-gated expansion. Rollback disables read/write admission immediately but continues expiry, opt-out, and deletion reconciliation. No production exposure is approved by this implementation alone; privacy inventory, threat model, controller/counsel review, encryption/key policy, runbooks, and production-equivalent verification remain release prerequisites.