# TORAZ Backend — Database Design

**Status:** Grows one module section per recovery batch (plan item P1). Each section is written before that batch's models. Finalized in Recovery 10.

Everything here is RECONSTRUCTED. The original database design was lost. Only the model names are confirmed by the surviving record (R04, R02); every field, index and rule below is a reconstruction from the master prompt, the recovery decisions and the frontend contract.

| Section | Entities | Batch | State |
|---|---|---|---|
| 1 | Conventions | Recovery 2 | Written |
| 2 | `User`, `OtpRequest`, `Session` | Recovery 2 | Written |
| 3 | `Profile` | Recovery 3 | Written |
| 4 | `Photo` and the files on disk | Recovery 3 | Written |
| 5 | `Like` (likes, Super Likes and passes), `Match`, `Block` (read-only policy, plan item P3), `SuperLikeLedgerEntry` | Recovery 4 | Written |
| 6 | `Conversation`, `Message` | Recovery 5 | Written |
| 7 | `Block` (written), `Report`, `ModerationEvent`, `User.safetyLock` | Recovery 6 | Written |
| 8 | `Verification` | Recovery 7 | Written (decisions AD-47 to AD-54) |
| 9 | `PremiumEntitlement`; Super Like ledger credits and the contamination safeguard | Recovery 8 | Written (decisions AD-55 to AD-64) |
| 10 | `AdminAuditLog`; `User.adminLock`; admin indexes on existing models | Recovery 9 | Implemented in Recovery 9-A to 9-D (AD-65 to AD-83), runtime-unverified. *Recovery 9B correction: this row still described Recovery 9-A* |
| 11 | `UserSettings` (the Online Activity Indicator only); the member counters | Recovery 9B | **Written and implemented** (AD-70, AD-71); runtime-unverified |
| — | `AccountDeletionRequest`, export, purge, retention | Recovery 9B | **Not written**: design only (`docs/reports/RECOVERY_9B_DATA_LIFECYCLE_DESIGN.md`) |

---

## 1. Conventions

- MongoDB through Mongoose. The connection string comes only from `MONGODB_URI`.
- Every collection has `createdAt` and `updatedAt` (Mongoose timestamps).
- References between collections are ObjectIds.
- Uniqueness that matters is enforced by a unique index, never only by an application check (MP §4).
- Documents never leave the data layer as Mongoose documents. Each store returns plain objects with a string `id`, and each API response is built by a serializer that copies named fields. A field not named in a serializer cannot reach a client.
- **Visibility** in the tables below: *owner* = returned to the account it belongs to; *admin* = may be returned by admin routes (Recovery 9); *internal* = never serialized to any client.
- Operations that must not race are written as single conditional updates (`findOneAndUpdate` with the precondition in the filter), so correctness does not depend on transactions. Multi-document transactions are introduced where a batch needs them (first in Recovery 4).

### Data access layer

Services do not call Mongoose. They call a store with a small set of methods (`src/repositories/`). There is one Mongoose implementation per store. Tests use an in-memory implementation of the same methods, and one shared contract test suite is written to run against both, so that the in-memory stores cannot quietly behave differently from the real ones.

---

## 2. Authentication (Recovery 2)

### 2.1 Relationships

```text
User 1 ──── * Session        Session.userId → User._id
User        (no reference)   OtpRequest is keyed by phone number, because a
                             code is requested before any account exists
```

### 2.2 `User` — the account

Identity only. Dating-profile information lives in `Profile` (Recovery 3) and is never duplicated here (MP §5).

| Field | Type | Required | Default | Visibility | Notes |
|---|---|---|---|---|---|
| `_id` | ObjectId | yes | generated | owner (as `id`), admin | The identifier used wherever a member is addressed (gap D1) |
| `countryCode` | String | yes | — | owner, admin | `+91` only. Frontend name (gap C4) |
| `phoneNumber` | String | yes | — | owner; admin **masked only** | 10 digits. Returned unmasked only to its owner, by `GET /api/profile/me`, because the frontend's form needs the full number to save (decided in Recovery 3). Everywhere else masked |
| `phoneVerifiedAt` | Date | no | `null` | owner (as boolean `phoneVerified`) | Set when a code is first verified. Not identity verification |
| `role` | String enum `USER`, `ADMIN` | yes | `USER` | owner, admin | MP §5. Changed only by the first-admin command; no HTTP input can set it |
| `accountStatus` | String enum `active`, `suspended`, `deleted` | yes | `active` | admin | Gap C3. Suspension and deletion are driven by Recovery 9 |
| `registrationCompletedAt` | Date | no | `null` | owner (as boolean `registrationCompleted`) | The account's registration state (MP §6). Set by profile registration in Recovery 3. `isNewUser` is derived from it |
| `relationshipLock` | Number | yes | `0` | never serialized | The pair lock of the like and Super Like transactions (§5.8, decision AD-30). A counter with no meaning of its own; only written, never read for a decision |
| `lastLoginAt` | Date | no | `null` | admin | Set on each successful verify-OTP. Basis of the admin "active users" proxy (R01 §5) |
| `createdAt`, `updatedAt` | Date | yes | automatic | admin | |

**Indexes**

| Index | Kind | Purpose |
|---|---|---|
| `{ countryCode: 1, phoneNumber: 1 }` | **unique** | One account per number. Makes concurrent first sign-ins safe: the second insert fails and falls back to a read |
| `{ role: 1 }` | plain | Counting administrators |

**Rules**

- Created only by a successful verify-OTP, with an atomic find-or-create on the unique index.
- `role`, `accountStatus`, `phoneVerifiedAt`, `registrationCompletedAt` are never accepted from a client.
- Deletion and what happens to the phone number afterwards are not designed yet (gaps B8, D16; Recovery 9). In this batch an account whose status is not `active` cannot sign in.

### 2.3 `OtpRequest` — one request for a code

| Field | Type | Required | Default | Visibility | Notes |
|---|---|---|---|---|---|
| `_id` | ObjectId | yes | generated | internal | |
| `requestId` | String | yes | — | returned to the requester | 32 random hexadecimal characters. The frontend's `requestId` |
| `countryCode` | String | yes | — | internal | |
| `phoneNumber` | String | yes | — | internal (returned masked) | |
| `channel` | String enum `sms`, `whatsapp` | yes | `sms` | internal | Recorded as requested; delivery is SMS |
| `codeHash` | String | yes | — | **internal** | HMAC-SHA-256 of `requestId:code` under a key derived from server secrets. The code is never stored |
| `expiresAt` | Date | yes | — | internal | Most recent send + 5 minutes |
| `attempts` | Number | yes | `0` | internal | Wrong-or-right verification attempts since the last send. Limit 5 |
| `resendCount` | Number | yes | `0` | internal | Limit 5 |
| `lastSentAt` | Date | yes | — | internal | Drives the 30-second cooldown |
| `sentAt` | [Date] | yes | — | internal | One entry per send. Used for hourly and daily caps per number |
| `active` | Boolean | yes | `true` | internal | `true` until the request is consumed or invalidated. Exists so that "one active request per number" can be a unique index |
| `consumedAt` | Date | no | `null` | internal | Set once, on successful verification |
| `invalidatedAt` | Date | no | `null` | internal | Set when a newer request replaces this one or delivery fails |
| `purgeAt` | Date | yes | — | internal | Most recent send + 25 hours |
| `createdAt`, `updatedAt` | Date | yes | automatic | internal | |

**Indexes**

| Index | Kind | Purpose |
|---|---|---|
| `{ requestId: 1 }` | **unique** | Lookup by the public handle |
| `{ countryCode: 1, phoneNumber: 1, lastSentAt: -1 }` | plain | Cooldown and caps per number; replacing older requests |
| `{ countryCode: 1, phoneNumber: 1 }` where `active: true` | **unique, partial** | At most one active request per number. Two simultaneous request-otp calls for one number therefore send one code: the second insert fails |
| `{ purgeAt: 1 }` | TTL, `expireAfterSeconds: 0` | Automatic removal about a day after the last send, once the daily cap no longer needs the record |

**Rules**

- "Active" means the `active` flag is `true`. It is set to `false` in the same update that sets `consumedAt` or `invalidatedAt`.
- A new request first invalidates the number's active request, then inserts. An expired but unused request stays active until that happens, so it never blocks a new one.
- A verification attempt is counted by one conditional update (`attempts < 5`, active, not expired) **before** the code is compared, so parallel guesses cannot exceed the limit.
- A request is consumed by one conditional update (`active: true`), so a code can succeed once only, even if submitted twice at the same instant.
- A resend is one conditional update that checks the cooldown and the resend limit and replaces the hash.
- The hourly and daily caps per number are read-then-insert, not atomic. Under simultaneous requests a cap can be passed by the number of requests in flight; the one-active-request index and the per-IP limit bound that.
- No IP address is stored. Per-IP limits are held in memory by the rate limiter.
- No OTP value, and no hash, is ever logged or returned.

### 2.4 `Session` — one signed-in device

| Field | Type | Required | Default | Visibility | Notes |
|---|---|---|---|---|---|
| `_id` | ObjectId | yes | generated by the application | owner (as `id`, in Recovery 9's session list) | Generated before insert, because the refresh token names it |
| `userId` | ObjectId → `User` | yes | — | internal | |
| `refreshTokenHash` | String | yes | — | **internal** | SHA-256 of the current refresh token. The token is never stored |
| `userAgent` | String | no | `''` | owner (as a device label, Recovery 9) | Truncated to 256 characters |
| `lastUsedAt` | Date | yes | creation time | owner | Updated on each rotation |
| `expiresAt` | Date | yes | — | internal | Now + `JWT_REFRESH_EXPIRES_IN`, moved forward on each rotation |
| `revokedAt` | Date | no | `null` | internal | |
| `revokedReason` | String enum `logout`, `reuse_detected`, `role_change`, `admin`, `user` | no | `null` | internal | `admin` and `user` are reserved for Recovery 9 |
| `createdAt`, `updatedAt` | Date | yes | automatic | owner | |

**Indexes**

| Index | Kind | Purpose |
|---|---|---|
| `{ userId: 1, revokedAt: 1 }` | plain | Listing and revoking an account's sessions |
| `{ expiresAt: 1 }` | TTL, `expireAfterSeconds: 0` | Expired sessions are removed automatically |

**Rules**

- Several sessions per account are allowed (MP §9, "multiple sessions/devices").
- Rotation is one conditional update: not revoked, not expired, and `refreshTokenHash` equal to the hash of the token presented. If it matches nothing while the session is otherwise live, the token was an old one: the session is revoked with reason `reuse_detected`.
- Revocation is permanent. A revoked session is kept until `expiresAt`, then removed by the TTL index.
- Every authenticated request reads the session and the account, so a revocation, suspension or role change takes effect on the next request, not when the access token expires.

### 2.5 What is deliberately not stored

- OTP codes, access tokens, refresh tokens.
- IP addresses or location (gap D12: no geolocation source is approved).
- A password of any kind.
- Any provider reference: the SMS adapter keeps nothing.

---

## 3. Profile (Recovery 3)

One document per account: the dating profile. Field-by-field mapping to the frontend: `FRONTEND_BACKEND_FIELD_MAPPING.md` §2.1.

### 3.1 Relationships

```text
User 1 ──── 0..1 Profile     Profile.userId → User._id   (unique)
User 1 ──── 0..5 Photo       Photo.userId   → User._id   (photos belong to the account, so they can be uploaded during registration)
```

### 3.2 Fields

| Field | Type | Notes |
|---|---|---|
| `_id` | ObjectId | Returned once, as `profileId`, by registration |
| `userId` | ObjectId → `User` | unique |
| the 46 profile fields | see the mapping | `phoneVerified`, `countryCode`, `phoneNumber` live on `User`, not here (MP §5) |
| `dob` | Date | UTC midnight of the date of birth. The API uses `{ day, month, year }` |
| `privacy` | `{ visibleInDiscovery, showOnlineStatus, showExactAge, showApproxDistance }` | each Boolean, default `true` |
| `consents` | `{ safetyPledgeAcceptedAt, termsAcceptedAt, privacyAcknowledgedAt }` | Dates. Set at registration and kept on updates |
| `registeredAt` | Date or `null` | `null` while the profile is a draft |
| `createdAt`, `updatedAt` | Date | |

Optional fields are absent from the document when not set, rather than stored as `""`. Mongoose validation on this model is deliberately loose (types and enums only): drafts are allowed to be incomplete, and completeness is enforced by the request validators at registration and update.

### 3.3 Indexes

| Index | Kind | Purpose |
|---|---|---|
| `{ userId: 1 }` | **unique** | One profile per account. Also what makes a draft and a registration converge on one document |

Discovery indexes (age, intention, city and so on) are designed in Recovery 4 from its actual queries, not guessed now.

### 3.4 State and the two registration markers

| State | `Profile.registeredAt` | `User.registrationCompletedAt` |
|---|---|---|
| No profile | — | `null` |
| Draft | `null` | `null` |
| Registered | set | set |

Drafts and registration both write through one conditional upsert on `{ userId, registeredAt: null }`. If its insert fails on the unique `userId` index, either the profile is registered or another first save created it a moment earlier; the write is then retried once without upsert, which applies to a draft and finds nothing for a registered profile. So two simultaneous first saves both succeed, and a registered profile is never touched by a draft.

Two markers exist for two different jobs. `Profile.registeredAt` is the **guard**: registration is one conditional write (`registeredAt: null` in the filter), so two simultaneous registrations cannot both succeed. `User.registrationCompletedAt` is the **account state** that sign-in reports as `isNewUser` (ledger R2-11). Registration completion is **one transaction** (decision AD-30): register the profile, mark the account, and grant the three initial Super Likes (§5.5). Either all three are written or none is: a failure at any point leaves a draft exactly as it was, and the member can simply submit again. A registered profile with an unmarked account, or a registered account without its grant, cannot exist. (Before the correction, the writes were separate and a "repair" path existed; both are gone.)

### 3.5 Rules

- Registration and update replace all profile fields at once; a draft sets only the fields it carries.
- A registered profile cannot go back to draft. A draft cannot be updated as if registered.
- Profiles are never deleted in this batch. Deletion and purge are Recovery 9 (gaps B8, D16).

---

## 4. Photo and the files on disk (Recovery 3)

### 4.1 `Photo`

| Field | Type | Required | Visibility | Notes |
|---|---|---|---|---|
| `_id` | ObjectId | yes | owner, and viewers allowed by the visibility policy | **96 random bits**, generated by the application, so photo IDs cannot be guessed or enumerated |
| `userId` | ObjectId → `User` | yes | internal | |
| `slot` | Number 0–4 | yes | internal | One of five slots. The unique index on `(userId, slot)` is what limits an account to 5 photos, even under simultaneous uploads |
| `isPrimary` | Boolean | yes | owner | At most one per account, enforced by a partial unique index |
| `storageKey` | String | yes | **internal** | `profiles/<userId>/<random UUID>.jpg`. Never sent to a client |
| `mimeType` | String | yes | internal | Always `image/jpeg` after re-encoding |
| `width`, `height` | Number | yes | internal | Of the stored, re-encoded image |
| `sizeBytes` | Number | yes | internal | Of the stored file |
| `createdAt`, `updatedAt` | Date | yes | internal | Upload order is `createdAt` |

Nothing from the uploaded file is stored: not its name, not its declared type, not its metadata.

### 4.2 Indexes

| Index | Kind | Purpose |
|---|---|---|
| `{ userId: 1, slot: 1 }` | **unique** | At most 5 photos per account (slots 0–4) |
| `{ userId: 1 }` where `isPrimary: true` | **unique, partial** | At most one primary per account |
| `{ userId: 1, createdAt: 1 }` | plain | Listing an account's photos in order (ties within one millisecond broken by `slot`) |

### 4.3 Concurrency

| Situation | Outcome |
|---|---|
| Two uploads race for the last free slot | One insert fails on the unique slot index; that upload tries the next free slot, and if none is left, its file is removed and it gets 409 |
| Two first uploads both try to be primary | One insert fails on the primary index and is retried as a non-primary photo. A new photo is primary whenever the account has no primary at that moment, so an account can never stay without one after an upload |
| Two "make primary" calls at once | Each clears other primaries then sets its own; a collision on the primary index is retried. One ends primary |
| Deleting the primary | The oldest remaining photo is promoted with a conditional update, only if no primary exists |
| Two deletions of an account's last two photos at once | Not atomic: both can succeed, leaving a registered profile with no photo. Rare and recoverable (the frontend then requires a photo to save); recorded as a known limitation |

### 4.4 Files

| Rule | Detail |
|---|---|
| Location | `UPLOAD_DIR/profiles/<userId>/<uuid>.jpg`. `UPLOAD_DIR` is resolved once at start-up |
| Names | Generated: a random UUID and the fixed `.jpg` extension. The client's file name is never used in a path |
| Path safety | `userId` must be a 24-character hexadecimal ID and the file name a UUID; the final path is resolved and must lie inside `UPLOAD_DIR`, or the operation is refused |
| Writing | To a temporary name in the same folder, then renamed, so a half-written file is never visible. Folders `0750`, files `0640` |
| What is written | Only the re-encoded JPEG. The original upload exists only in memory |
| Order of operations | Upload: write the file, then insert the record; if the insert fails, remove the file. Delete: remove the record, then the file; a failure to remove the file is logged and leaves an unreferenced file, never a record without a file |
| Serving | Only through `GET /api/photos/:photoId`. No static file serving of `UPLOAD_DIR` exists |
| Execution | Files are never executed or interpreted; they are read as bytes and sent with `Content-Type: image/jpeg` and `nosniff` |

### 4.5 Image limits (named settings)

| Setting | Value | Status |
|---|---|---|
| `MAX_FILE_SIZE_MB` | 10 | **Approved** (AD-18) |
| `MAX_IMAGE_WIDTH`, `MAX_IMAGE_HEIGHT` | 8000 each | Provisional; names from MP §30 |
| `MIN_IMAGE_DIMENSION` | 320 | Provisional |
| `PHOTO_OUTPUT_MAX_DIMENSION` | 2048 | Provisional |
| JPEG quality | 85 | Provisional constant |
| Photos per account | 5 | From the frontend (`maxPhotos`) |
| Decoder pixel limit | `MAX_IMAGE_WIDTH × MAX_IMAGE_HEIGHT` | Refuses decompression bombs before decoding |

---

## 5. Discovery and matching (Recovery 4)

Decisions AD-22 to AD-28. Every relationship record refers to accounts (`User._id`), not profiles (gap D1). The models are the ones the recovery package names (R04: `Like`, `Match`, `SuperLikeLedgerEntry`, `Block`); no other model is added.

### 5.1 `Like` — one decision per direction

A member's decision about another member is one record: a like, a Super Like or a pass. The preflight design had a separate `Pass` model; it was folded into `Like` because R04 says to add only models the recovered design justifies, and because AD-27 makes a pass and a like to the same person mutually exclusive, which one record per direction enforces by itself.

| Field | Type | Notes |
|---|---|---|
| `_id` | ObjectId | Random (12 random bytes). Internal; never returned |
| `fromUserId` | ObjectId → `User` | Who decided |
| `toUserId` | ObjectId → `User` | About whom |
| `type` | String | `like`, `super_like` or `pass` |
| `version` | Number | Increases with every change; makes Super Like debits idempotent (§5.5) |
| `superLikeRef` | String or null | The ledger key that paid for the current or last Super Like on this record |
| `matchId` | ObjectId or null | Set ("sealed") when the record is part of a Match. A sealed record never changes again |
| `createdAt`, `updatedAt` | Date | |

| Index | Kind | Purpose |
|---|---|---|
| `{ fromUserId: 1, toUserId: 1 }` | **unique** | One decision per direction: no duplicate like (MP §14), and no like and pass together (AD-27) |
| `{ toUserId: 1, type: 1, updatedAt: -1 }` | plain | Liked-you list |

Withdrawing a like or revoking a pass deletes the record, and only while it is unsealed and of the expected type.

### 5.2 `Match`

| Field | Type | Notes |
|---|---|---|
| `_id` | ObjectId | Derived from the pair: the first 24 hexadecimal characters of SHA-256(`toraz:match:` + `userA` + `:` + `userB`). Concurrent attempts therefore agree on it. Never returned to a client; Recovery 5 attaches the conversation to it (gap D10) |
| `userA`, `userB` | ObjectId → `User` | The canonical pair: `userA` is the smaller ID, `userB` the larger. A + B and B + A give the same pair (MP §16) |
| `createdAt` | Date | |

| Index | Kind | Purpose |
|---|---|---|
| `{ userA: 1, userB: 1 }` | **unique** | At most one Match per pair |
| `{ userA: 1, createdAt: -1 }`, `{ userB: 1, createdAt: -1 }` | plain | Listing a member's matches, newest first |

A Match is never deleted in Recovery 4; unmatching does not exist (AD-27). It is created in the same transaction as the like or Super Like that completes it, together with both seals (§5.8, `API_CONTRACT.md` §9.7): the Match document and the two sealed likes exist together or not at all.

### 5.3 `Block` (read-only policy; plan item P3)

| Field | Type | Notes |
|---|---|---|
| `blockerId`, `blockedId` | ObjectId → `User` | |
| `createdAt` | Date | |

Indexes `{ blockerId: 1, blockedId: 1 }` **unique** and `{ blockedId: 1 }`. Recovery 4 only **reads** blocks, in both directions, for discovery, actions, lists and profile and photo visibility. Creating, removing and listing blocks are Recovery 6 routes; until then no block exists outside tests.

### 5.4 Relationship state, computed

For viewer V and member M, from V's record to M (`mine`) and M's record to V (`theirs`):

| State | Condition |
|---|---|
| `matched` | `mine` and `theirs` both sealed |
| `super_liked` | `mine.type = super_like` |
| `liked` | `mine.type = like` |
| `none` | `mine.type = pass` |
| `liked_you` | no `mine`, and `theirs.type` is `like` or `super_like` |
| `none` | otherwise |

`pending` is never produced (AD-27 item 8).

### 5.5 `SuperLikeLedgerEntry`

| Field | Type | Notes |
|---|---|---|
| `userId` | ObjectId → `User` | Whose balance |
| `seq` | Number | 1, 2, 3 … per account |
| `delta` | Number | `+3` for the initial grant, `-1` for a Super Like, `+count` for a simulated pack (Recovery 8, development and test only) |
| `balanceAfter` | Number | The balance after this entry; never negative |
| `reason` | String | `initial_grant` (AD-22), `super_like`, or `simulated_pack_purchase` (AD-61) |
| `referenceId` | String | `registration` for the grant; the Super Like key for a debit; `key:<purchaseKey>` or `auto:<random>` for a simulated pack |
| `createdAt` | Date | |

| Index | Kind | Purpose |
|---|---|---|
| `{ userId: 1, seq: 1 }` | **unique** | One sequence per account: two writers cannot both append entry *n* |
| `{ userId: 1, reason: 1, referenceId: 1 }` | **unique** | Each event is recorded once: one initial grant per account, one debit per Super Like key, one credit per purchase key. Also serves the per-account simulated-credit check (AD-61) |
| `{ reason: 1, createdAt: -1 }` | regular | The production start-up check for simulated credits (AD-61); recent activity by reason |

**Balance** = the latest entry's `balanceAfter`, or 0 with no entries. It is the sum of all `delta`s, which a test checks. Never a client value and never an edited number (R01 §5, MP §23).

**Appending — only inside a transaction** (decision AD-30). Every ledger entry is written in the transaction of the operation it belongs to; the service refuses a ledger write without a session. In that transaction: if the event's key already exists, return it (idempotent); read the latest entry *n*; refuse a debit when `balanceAfter < 1` (409 `no_super_likes`, which aborts the whole transaction); insert entry *n* + 1. If a concurrent transaction took position *n* + 1, the unique index fails the insert, the transaction aborts, and the runner re-runs the whole operation against the new balance (§5.8). A balance of 1 therefore pays for exactly one Super Like, whatever the timing.

**A debit never exists without its Super Like.** The debit, the record change and any Match commit together or not at all, so a crash or a failed write after the debit leaves no charge (AD-29).

**The Super Like key** is `<record ID>:v<version>`: the version the record had before the change, or `<new record ID>:v0` for a new record. The record write that follows is conditional on that version and stores the key in `superLikeRef`. If it fails, the transaction aborts (debit included) and is retried. The key is deterministic, so a retried transaction derives the same key, and the unique index remains a second guard against paying twice. **The initial grant** is appended with key `registration` inside the registration transaction (§3.4).

There is no reversal entry: an aborted transaction leaves nothing to reverse.

### 5.6 Discovery query and its indexes

One aggregation: profiles matching E3 (registered), E4 (`privacy.visibleInDiscovery` not `false`), E6 (gender and `interestedIn` sets) and the age (leaving out `privacy.showExactAge: false` while an age filter is active), intention and text filters → join to `User` for E2 (`active`) and the order (`lastLoginAt`, then ID) → exclusion of the IDs in E1, E5 and E7 (`$nin`) → skip and limit + 1 (for `hasMore`). Cards are then built for the page, dropping any candidate without a photo (E3).

The exclusion list (the viewer's own decisions, matches and blocks both ways) is read first. That is simple and correct at launch scale; a member with tens of thousands of decisions would need a different plan. Recorded as a known limit.

| Index | Collection | Purpose |
|---|---|---|
| `{ registeredAt: 1, gender: 1, interestedIn: 1, dob: 1 }` | `Profile` | E3, E6 and the age filter |
| `{ accountStatus: 1, lastLoginAt: -1 }` | `User` | E2 and the order |

The text filter is an escaped, case-insensitive literal pattern; the client never supplies a regular expression. No text index; no geospatial index (no coordinates exist, AD-24).

### 5.7 When an account changes

| Change | Stored records | What is shown |
|---|---|---|
| Account suspended or deleted | Nothing deleted (deletion and purge: Recovery 9) | Gone from discovery, liked-you and match lists; cannot be acted on (404) |
| Profile hidden from discovery | Nothing | Not in discovery; still in a match's list and viewable by the match and by members the owner liked |
| Block either way | Nothing deleted | Not shown to the other anywhere; no action possible (404) |

### 5.8 Transactions and the pair lock (decisions AD-30, AD-31)

**Which operations are transactions.**

| Operation | Writes in one transaction, in order |
|---|---|
| Like (new, over a pass, or a like-back) | pair lock · write the like · if the other member likes back: seal theirs, seal mine, insert the Match, insert its Conversation (Recovery 5, §6.1) |
| Super Like (new, over a pass, upgrade of a like, on an admirer) | pair lock · ledger debit · write the Super Like · if the other member likes back: seal theirs, seal mine, insert the Match, insert its Conversation |
| Registration completion | register the profile · mark the account · grant 3 Super Likes |

Pass, pass revocation and like withdrawal are single conditional writes and run without a transaction; a sealed record refuses all three, so none of them can undo or half-undo a Match.

**Settings.** Read concern `snapshot`, write concern `majority`, read preference `primary`. Every read and write of the operation passes the same session.

**Retries.** In a MongoDB transaction a failed write aborts the whole transaction. The runner (`src/repositories/transactions.js`) therefore re-runs the whole operation in a fresh session, at most 5 times, when the transaction failed on: a duplicate key (a concurrent transaction committed the same record, Match or ledger position first), a conditional write that matched nothing (`RetryableConflict`), or an error MongoDB labels `TransientTransactionError` (a write conflict). Every other error, such as 409 `no_super_likes`, aborts and is returned at once. Each operation re-reads what it needs, so a re-run sees the state the other transaction committed.

**The pair lock.** Transactions read a snapshot. Two simultaneous first likes, A→B and B→A, write two different `Like` documents; without anything more, each transaction would see no like from the other, both would commit, and no Match would be made (write skew). So the first write of every like and Super Like transaction increments `relationshipLock` on the pair's first member (`userA`, the smaller ID). Any two transactions about the same pair now write the same document; MongoDB lets only one proceed and aborts the other with a write conflict, and its re-run sees the first one's like. The lock serialises only transactions about the same pair and about the same first member; its cost is one small write per like.

**Deployment requirement.** Transactions need a replica set or a sharded cluster. The server checks this when it starts and refuses to start otherwise (`src/config/transactionSupport.js`; README, "MongoDB must be a replica set"). There is no non-transactional mode.

---

## 6. Messaging (Recovery 5)

Decisions AD-32 to AD-36. Contract: `API_CONTRACT.md` §10 and §11. Two models, both named by the recovery package (R04: `Conversation`, `Message`); nothing else is stored. Summaries, unread counts and presence are derived.

### 6.1 `Conversation`

| Field | Type | Notes |
|---|---|---|
| `_id` | ObjectId | **Random** (12 random bytes). The ID clients use. Not the Match ID: that one is derived from the pair, so anyone who knows two account IDs could compute it, and it stays internal (R4-03) |
| `matchId` | ObjectId → `Match` | The Match this conversation belongs to |
| `userA`, `userB` | ObjectId → `User` | The Match's canonical pair, copied so that membership is checked from one document |
| `createdAt` | Date | |

| Index | Kind | Purpose |
|---|---|---|
| `{ matchId: 1 }` | **unique** | Exactly one conversation per Match |
| `{ userA: 1 }`, `{ userB: 1 }` | plain | A member's conversations |

**Created in the Match's transaction** (AD-36, gap D10): `completeMatchIfMutual` inserts the Conversation right after the Match, with the same session, under the same pair lock and retry rules (§5.8). Both exist or neither does. A concurrent duplicate fails the unique `matchId` index and aborts its transaction, which is re-run and finds the Match done. The ID is drawn afresh on every attempt; only the committed one exists. Conversations are never deleted in Recovery 5 (unmatching does not exist; purge tombstones are Recovery 9).

### 6.2 `Message`

| Field | Type | Notes |
|---|---|---|
| `_id` | ObjectId | Laid out as MongoDB's own ObjectId (seconds, a per-process random part, a counter), so IDs made by one server increase in creation order and break ties between messages stored in the same millisecond. Not secret: access is checked on every use (§10.1 of the contract) |
| `conversationId` | ObjectId → `Conversation` | |
| `senderId`, `recipientId` | ObjectId → `User` | Set by the server from the token and the conversation; never from a request |
| `text` | String | Trimmed; 1–2000 code points (provisional). Never logged |
| `moderation` | String | Internal state: `unmoderated` (Recovery 5: no provider checked it), later `clear`, `pending_review`, `blocked`. Served as the hold state `clear` plus `moderationChecked: false` (`API_CONTRACT.md` §10.3) |
| `clientMessageId` | String or absent | Optional client key for idempotent sends |
| `createdAt` | Date | Server clock at storage; the order key |
| `deliveredAt` | Date or null | First fetch by, or socket acknowledgement from, the recipient (AD-35) |
| `readAt` | Date or null | Set by the recipient's read-up-to (AD-35) |

| Index | Kind | Purpose |
|---|---|---|
| `{ conversationId: 1, createdAt: -1, _id: -1 }` | plain | History pages (newest first, cursor `createdAt, _id`) and the latest message per conversation |
| `{ recipientId: 1, conversationId: 1, readAt: 1 }` | plain | Unread counts; the read-up-to update |
| `{ senderId: 1, clientMessageId: 1 }` | **unique, partial** (only where `clientMessageId` is a string) | One message per client key per sender |

### 6.3 Writes, and why none needs a transaction

**Amended by Recovery 6 (§7.5):** a send becomes a pair-locked transaction (the block race, AD-45), and a held message is written with its moderation event in one transaction (AD-42). Mark-read and mark-delivered remain single writes.

| Operation | Write | Consistency |
|---|---|---|
| Send | One insert | Atomic by itself. Stored before any answer or push; a failed insert answers an error and pushes nothing. A repeated `clientMessageId` hits the unique index; the stored message is read back and returned (or 409 if it differs) |
| Mark read up to *M* | One `updateMany` with filter `conversationId = M's`, `recipientId = caller`, `readAt = null`, and (`createdAt < M.createdAt`, or equal with `_id ≤ M._id`) | Each document changes atomically. `recipientId = caller` means a member can only ever mark messages addressed to them. `readAt = null` means a read time is set once and never moved back; two concurrent calls with different *M* both only add reads, so the result is the same in any order |
| Mark delivered | One `updateMany` with filter `recipientId = recipient`, `_id ∈ ids`, `deliveredAt = null` | Idempotent; touches only messages addressed to that member |

There is no conversation summary document (last message, counters). Keeping one would turn every send into a two-document write needing a transaction, and a counter could drift. The summary is read from `Message` through the first two indexes.

### 6.4 Reads

| Read | Query |
|---|---|
| Conversation list | The member's conversations (`userA` or `userB`) → eligibility of the other members (active, registered, unblocked) → one aggregation over `Message` for those conversations: latest message and unread count per conversation → order by latest activity → page |
| History page | `conversationId`, optionally (`createdAt`, `_id`) before the cursor message's, sorted `createdAt: -1, _id: -1`, `limit + 1`; reversed for the answer |
| Unread count after read | count with `recipientId`, `conversationId`, `readAt: null` |

**Known limit:** the list reads every conversation of the member before paging, like Matches (R4-20). Correct and simple at launch scale.

### 6.5 Presence (not stored)

Presence lives in the server process: for each account, its connected sockets and the time its last socket disconnected (`API_CONTRACT.md` §11.6). Nothing is written to the database, so it resets on restart and requires a single instance.

### 6.6 When an account or relationship changes

| Change | Stored records | What happens |
|---|---|---|
| Other member suspended or deleted | Nothing deleted | Conversation hidden from the list; reading, sending and marking read answer 404; no presence |
| Block either way | Nothing deleted | Same: hide and freeze, restored on unblock (AD-38, §7) |
| Caller's own session revoked or account suspended | Nothing | REST refused (§3.9); sockets refused at the next event, at expiry, or at once on logout |
| Purge (Recovery 9) | — | Messages to be tombstoned in place (R01 §5); not built here |


---

## 7. Safety (Recovery 6)

Decisions AD-38 to AD-45. Contract: `API_CONTRACT.md` §12. Models named by the recovery package (R04: `Block`, `Report`, `ModerationEvent`); nothing else is added except one counter on `User` (§7.4).

### 7.1 `Block` (exists since Recovery 4; now written)

Unchanged fields: `blockerId`, `blockedId`, `createdAt` (the `blockedAt` of the contract).

Unchanged indexes:
- `{ blockerId: 1, blockedId: 1 }`, **unique**;
- `{ blockedId: 1 }`.

One index is added: `{ blockerId: 1, createdAt: -1 }`, for the blocked list. Records are created and deleted only by the block service, in a pair-locked transaction (§7.5). Nothing else reads blocks: every consumer goes through the safety policy (`API_CONTRACT.md` §12.1).

### 7.2 `Report`

| Field | Type | Notes |
|---|---|---|
| `_id` | ObjectId | Random |
| `reporterId` | ObjectId → `User` | From the token, never from input |
| `targetType` | String | `user`, `profile`, `message` |
| `targetUserId` | ObjectId → `User` | The reported account. For a message report, its sender |
| `targetMessageId`, `conversationId` | ObjectId or null | Message reports only |
| `reason` | String or null | Optional, at most 1000 code points; never logged |
| `evidence` | `{ messageText, messageSentAt }` or null | Message reports only; copied in the creating transaction (AD-41). **Retention undecided (gap D30, Recovery 9)** |
| `status` | String | `OPEN`, `UNDER_REVIEW`, `RESOLVED`, `REJECTED` |
| `openKey` | String or absent | `<targetType>:<targetId>` while `OPEN` or `UNDER_REVIEW`; removed on `RESOLVED` or `REJECTED` |
| `resolution`, `internalNote` | String or null | Set only by the administrative hooks (§7.7) |
| `statusChangedAt`, `createdAt`, `updatedAt` | Date | |

| Index | Kind | Purpose |
|---|---|---|
| `{ reporterId: 1, openKey: 1 }` | **unique, partial** (`openKey` is a string) | **One open report per reporter and target**, enforced by the database, so simultaneous duplicates cannot both be created (AD-40) |
| `{ reporterId: 1, createdAt: -1 }` | plain | The rolling 24-hour count (AD-39) |
| `{ status: 1, createdAt: -1 }` | plain | The administrative list by status |
| `{ targetUserId: 1, createdAt: -1 }` | plain | Reports about an account (administrative; Recovery 9) |

### 7.3 `ModerationEvent`

| Field | Type | Notes |
|---|---|---|
| `_id` | ObjectId | Random |
| `messageId` | ObjectId → `Message` | **Unique**: one event per message |
| `conversationId`, `senderId`, `recipientId` | ObjectId | |
| `outcome` | String | `pending_review` or `blocked` |
| `providerRef` | String or null | The provider's own reference, when one exists; `null` until then |
| `status` | String | `OPEN` (for the future screening queue; nothing changes it in Recovery 6) |
| `createdAt` | Date | |

**No copy of the text** (AD-42): the message holds it.

Indexes:
- `{ messageId: 1 }`, unique;
- `{ status: 1, createdAt: -1 }`.

### 7.4 `User.safetyLock`

A counter like `relationshipLock`, never serialized. The report transaction writes it first, which serializes **one reporter's** report transactions. The rolling count and the insert of report *n* + 1 therefore cannot interleave with another report by the same member: the limit holds under concurrency (AD-39).

### 7.5 Transactions and lock order

| Operation | Writes, in order, in one transaction |
|---|---|
| Block | pair lock (`relationshipLock` of the pair's first member) · insert `Block` (a duplicate inside the transaction aborts it; the re-run finds it and answers 200) |
| Unblock | pair lock · delete the caller's `Block` |
| Like / Super Like (Recovery 4, amended) | pair lock · **block re-check (read)** · … unchanged (debit, like write, seals, Match, Conversation) |
| Send (Recovery 5, amended) | pair lock · access re-check, including the block (reads) · insert `Message` · if held: insert `ModerationEvent` |
| Report | reporter's `safetyLock` · rolling count (read) · for a message: read message and conversation · insert `Report` (the unique `openKey` index aborts a duplicate; the re-run returns the existing one) |

**Lock order.** Every transaction writes **at most one lock document, first**: the pair lock for block, unblock, matching and send; the reporter's `safetyLock` for reports. No transaction waits on two locks, so there is no lock-order deadlock. MongoDB resolves conflicts on a lock by aborting one transaction, which the runner re-runs (AD-30).

**Mark-read and delivery stay single writes** (`updateMany` filtered on the caller as recipient), unchanged from Recovery 5. They create nothing a block must prevent; their pushes are governed by §7.6.

**Effect on Recovery 5.** A send was one insert; it becomes a transaction with one extra write (the pair lock).
- Sends within one pair are serialized, as likes within one pair already are; this is the same hot-spot trade-off as R4-T3.
- The `clientMessageId` duplicate inside the transaction aborts it, and the re-run finds the stored message and replays it (as R5-10).
- Moderation is called **before** the transaction, so that no lock is held during a provider call. The outcome does not depend on the block.

### 7.6 The commit-to-emission boundary (AD-45; **decided: S1, AD-46**)

A MongoDB transaction ends at commit; a Socket.IO emission is a separate step after it. The sequence for a send is: commit (T1), then emit (T2). A block can commit at any instant Tb, including **T1 < Tb < T2**. In that window the message was stored legitimately before the block, but the push would leave the server after the block took effect. AD-45 forbids that.

**No re-check closes this.** A check at T1.5 can always be followed by a block at T1.6 and the emit at T1.7. Strictness needs **mutual exclusion** between "a block commits for pair P" and "the server emits anything between the members of P". The same applies to two other pushes:
- `message:read` receipts;
- `presence:update`, which a block also must stop.

Three ways to get that exclusion:

| Option | How | Guarantee | Cost and effect on Recovery 5 |
|---|---|---|---|
| **S1: in-process pair gate (recommended)** | A per-pair asynchronous mutex in the server process. Block and unblock hold the gate around their transaction. Send holds it around the transaction **and** its emissions. Mark-read holds it around its update and receipt. Each presence push to member M about U holds gate(U, M) and reads the block state inside it | **Exact on the single instance AD-36 already requires**: every emission happens either entirely before the block commits (the message or receipt existed before the block), or after a read inside the gate that sees the block, and is then not made. Persistence is exact on any topology (the pair lock) | No new collection, process or wire change. The gate is held for one short transaction plus a synchronous emit. **But delivery-safety now depends on the single-instance deployment.** If AD-36 is ever lifted, the gate must become a distributed lock, or the delivery guarantee degrades to best effort (persistence stays exact) |
| S2: database lease across emission | After the send commits, a **second** transaction writes the pair lock, re-reads the block, emits, then commits. A block cannot commit while that lock write is uncommitted, so it is re-run afterwards | Exact on any topology | Two transactions per message, one held open during the emission. If the second commit fails after emitting, its re-run emits again (duplicate `message:new`; clients must de-duplicate by ID). Presence pushes need one lock write per audience member per connect and disconnect, or must stay best effort |
| S3: transactional outbox | The send transaction also writes an outbox record; a dispatcher delivers outbox records | Still needs S1 or S2 at the dispatcher to be strict | A new collection, a background loop and added latency. Largest; not recommended |

What every option keeps:
- persistence before delivery;
- no partial Match/Conversation or message/event pair;
- `clientMessageId` idempotency;
- read up to, and delivery tracking (delivery acknowledgements are server writes, not emissions to a member);
- socket authorization: per-event re-checks, and audiences computed at emit time.

**Decision (AD-46): S1, the in-process pair gate**, implemented in `src/realtime/pairGate.js`.

| Operation | Inside gate(U, M), in order |
|---|---|
| Block / unblock | transaction (pair-lock write → insert or delete `Block`) → commit → both members' sockets leave the pair's conversation room |
| Send | (validation, a pre-check of access, the idempotent replay pre-check and the moderation call happen **before** the gate, so no gate is held during a provider call) → transaction (pair-lock write → access re-check including the block → replay check → insert `Message` → insert `ModerationEvent` if held) → commit → **re-read the block** → if not blocked: push to the recipient (deliverable messages only) and to the sender's other sockets |
| Mark-read | access re-check (including the block) → `updateMany` read up to → unread count → **re-read the block** → if something changed and not blocked: receipts to both |
| Presence push U → M | **re-read the block** → if not blocked: `presence:update` to M |
| Conversation join (`conversation:join`; added in Recovery 6.1, ledger R6-25) | (a preliminary access check before the gate only finds the other member; it decides nothing) → the caller's registration → the full access check again (membership, Match, the other member's account and profile, the block both ways) → the newest history page, read only → the socket joins the conversation room → the page's messages to the caller are marked delivered (one write; if it fails, the room entry is undone and the join fails, ledger R6-26) → release. If the room join itself fails, possibly after adding the socket, an undo of the entry is attempted before the error is returned, still inside the gate (ledger R6-27). A block that commits first makes the join fail with `not_found`, no room and no history; a block requested during the join waits and then evicts the socket |

**Rules:**
- The gate is always taken **before** any pair-lock write and released in `finally`.
- A presence fan-out takes one gate at a time.
- An attempt to take a second gate while one is held throws, by design, so a lock-order violation fails loudly instead of deadlocking.
- Gates for different pairs never wait on each other.
- Matching, which emits nothing, keeps using only the database pair lock and its in-transaction block re-check.

**Why it is exact:**
- Every block or unblock between U and M commits while holding gate(U, M).
- Every push between them is decided and emitted while holding the same gate, after a fresh read of the block.
- Every room join for their conversation is decided and completed while holding the same gate, after a fresh access check; the block's room eviction runs inside its own gate after its commit. So a socket is either in the room before the block commits (and then evicted) or never enters it.
- So each push is either emitted before the block's commit, or the read sees the block and nothing is emitted.

Network arrival can still trail emission (transport latency).

**Hard deployment restriction (AD-46):** one Node.js process. Several processes would each have their own gates, and the delivery guarantee (3) would no longer hold. Guarantees (1), (2) and (4) rest on the database pair lock and transactions and do not depend on the process count.

### 7.7 Administrative hooks (AD-43)

The report service exposes, to code only:
- `list({ status, page, limit })`, newest first;
- `get(reportId)`, including evidence;
- `transition(reportId, { from, to, resolution?, internalNote?, actorId })`. This is one conditional update with filter `{ _id, status: from }`. It sets `status` and `statusChangedAt`, removes `openKey` for `RESOLVED` or `REJECTED`, and stores `resolution` and `internalNote`. `actorId` is required now, so that the Recovery 9 audit record has it.

No route calls them in Recovery 6.

### 7.8 Invariants carried over, and their tests

| Invariant (origin) | Kept by | Tests that must still pass |
|---|---|---|
| A Match and its Conversation exist together or not at all; no sealed record changes; at most one Match per pair (R4, AD-30, AD-36) | Block never touches them; the re-check aborts the whole matching unit | `matching.faults.test.js` (52 fault points, extended by the block re-check); the race test asserting one Conversation; store contract |
| Ledger arithmetic; no refund (AD-22, AD-29) | Blocks write no ledger entry; a refused like or Super Like aborts before or with its debit | Ledger checks in `matching.faults`; `matchingFlow` Super Like tests |
| Message stored before any push; `clientMessageId` idempotent; read up to; delivery tracking (AD-35, AD-36) | Send transaction + Q9 boundary; mark-read and delivery unchanged | `messagingFlow`, `messaging.faults`, `sockets.gateway`; extended with the send transaction's fault points and held messages |
| Socket authorization: handshake, per-event re-check, rooms never a permission (AD-32) | Unchanged; block adds room eviction | `sockets.gateway` |
| AD-31 / AD-33 start-up refusals | Untouched | `transactionSupport.test.js`, `messaging.units.test.js` |
| D9 fallback behaviour (now AD-38) | Moves into the one safety policy | Existing block tests in `matchingFlow` and `messagingFlow`, unchanged |

---

## 8. Verification (Recovery 7)

Decisions B10, B13, C1, D21 (gap defaults, as recorded) and AD-47 to AD-54. RECONSTRUCTED: the original model is lost; R04 confirms only the name `Verification`.

### 8.1 `Verification`

One document per account, created by the account's first successful verification action. An account with no document has the **derived** state `mobile_verified` (every account is created by a verified OTP, so `phoneVerifiedAt` is set), or `not_started` if `phoneVerifiedAt` is null.

| Field | Type | Required | Default | Exposure | Notes |
|---|---|---|---|---|---|
| `_id` | ObjectId | yes | auto | internal | |
| `userId` | ObjectId → `User` | yes | | internal | **unique** |
| `state` | String: `not_started`, `mobile_verified`, `digilocker_pending`, `digilocker_verified`, `selfie_pending`, `face_match_processing`, `retry_required`, `manual_review`, `verified`, `failed` | yes | | member (`state`) | The frontend's `VerificationState` (C1) |
| `evidence` | String: `simulation`, `provider` | yes | | **internal** | Provenance of the **current verification chain** (8.2) |
| `providerName` | String ≤ 60 | no | `null` | **internal** (admin in Recovery 9) | Name of the real provider adapter that produced the last provider result |
| `providerRef` | String ≤ 200, `[A-Za-z0-9._:-]` | no | `null` | **internal** (admin in Recovery 9) | Opaque reference from the last validated provider result; never a payload |
| `stateChangedAt` | Date | yes | | member (`updatedAt`) | |
| `verifiedAt` | Date | no | `null` | internal | Set on entering `verified`, cleared on leaving it |
| `version` | Number (integer ≥ 1) | yes | `1` | internal | Monotonic; +1 on every write (8.3) |
| `createdAt`, `updatedAt` | Date | yes | | internal | Explicit (no Mongoose timestamps), as in `Report` |

**Indexes:** `{ userId: 1 }` unique; `{ state: 1, stateChangedAt: 1 }` (Recovery 9's `manual_review` queue, D14, and the `verification_backlog` KPI). No index on `providerRef`: there is no callback to look records up by it (AD-49).

**Never stored:** identity documents, document images, selfies, liveness frames, face templates or match scores, legal name, date of birth, ID numbers, address, raw provider requests or responses, provider credentials, tokens, IP addresses, device data. `percentComplete` and the Recovery 9 admin status are derived, never stored.

### 8.2 Provenance: the trust invariant (AD-51)

A **verification chain** begins with `start` (from `mobile_verified` or `not_started`) and continues through every later action on the same record. `evidence` records whether **every** step of the current chain was performed by a real provider:

| Step | `evidence` after the step |
|---|---|
| `start`, by the real provider | `provider` (a new chain) |
| `start`, by simulation | `simulation` (a new chain) |
| any later step (`liveness`, `retry`), by the real provider | unchanged: `provider` stays `provider`, `simulation` stays `simulation` |
| any later step, by simulation | `simulation` |

So the taint is **sticky**: once any step of a chain was simulated, nothing later in that chain can make it `provider`. Only a new `start` begins a new chain.

**Trusted verification** (what `isVerified` and a `verified` status mean):

| Environment | A record counts as verified when |
|---|---|
| production (`NODE_ENV` other than exactly `development` or `test`) | `state === 'verified'` **and** `evidence === 'provider'` |
| development, test | `state === 'verified'` (simulation is the point of these environments) |

**Effective record in production.** A record whose `evidence` is not `provider` (simulation, or any unknown or missing value) is **read as absent**: its member is shown the derived state (`mobile_verified`) and is never `isVerified`. That member may `start` again; a real-provider `start` overwrites the record (compare-and-set on its `version`) and begins a fresh `provider` chain. A record whose `evidence` is unknown is never trusted anywhere.

**What this guarantees:**
- simulation never confers production-trusted verification, whatever happens later;
- a development database reused in production shows no simulated member as verified, and lets none of them continue a simulated chain;
- a real-provider result on top of a simulated document step (or the reverse) stays `simulation`;
- the only producer of `evidence: provider` in this build is a validated result from the real-provider adapter, which does not exist (AD-53). So **in this build nothing can be production-trusted**;
- Recovery 9's admin decisions are not built (AD-51). Admin trust needs its own approved policy and an explicit change to this rule. Today the rule trusts `provider` only, and a test asserts it.

### 8.3 Writes and concurrency (AD-52)

- **First write:** an insert with `version: 1`. A concurrent second insert fails the unique `userId` index; the service re-reads and answers 409.
- **Later writes:** `findOneAndUpdate({ userId, version: expected }, { $set: { … }, $inc: { version: 1 } })`. `null` (the version moved) → 409.
- **The expected version is read before the provider is called.** If anything changed the record during the call, including A → B → A changes of `state`, the version differs, the write fails, and the provider result is discarded (logged without its content).
- One document per write: no transaction, no pair gate (verification concerns one account).
- A write is never retried automatically: a stale result must not be re-applied.

### 8.4 Modes and stores

The pure gate (`src/services/verificationGate.js`) resolves `real`, `dev_simulation` or `unavailable` from `NODE_ENV`, `VERIFICATION_PROVIDER_ENABLED`, `VERIFICATION_PROVIDER_URL`, `VERIFICATION_PROVIDER_KEY` and `VERIFICATION_DEV_SIMULATION` (`API_CONTRACT.md` §13.2). In `unavailable` mode, and in `real` mode while no implementation exists, **no verification document is ever written**.

`verificationStore` (memory and MongoDB, one contract): `findByUserId`, `insert`, `updateIfVersion`, `listVerifiedByUserIds` (`state: 'verified'`, one `$in` read; the trust rule is applied by the service, not the store).

### 8.5 Interactions

- **Cards and conversation summaries:** `isVerified` comes from one batched `listVerifiedByUserIds` per list, filtered by the trust rule; no other verification data leaves the store.
- **Account suspension:** unchanged; the `authenticate` middleware refuses the account before any verification code runs.
- **Account purge (Recovery 9):** deletes the document ("delete verification document", R01 §5).
- **Admin decisions (Recovery 9):** not built.

---

## 9. Premium (Recovery 8)

Decisions AD-55 to AD-64; gap defaults D22, B13, B12. RECONSTRUCTED: MP §4 names the concept `PremiumEntitlement`; nothing else about it survives.

### 9.1 `PremiumEntitlement`

One per account, created by the first successful simulated Boost or subscription (no real provider exists). No document means free, with no Boost.

| Field | Type | Required | Notes |
|---|---|---|---|
| `userId` | ObjectId → `User` | yes | **unique** |
| `subscription` | `{ planId, source, startedAt }` or `null` | no (`null`) | `planId` from the catalog; `source`: `simulation` or `provider`. **No expiry** (AD-55) |
| `boost` | `{ optionId, source, activatedAt, expiresAt }` or `null` | no (`null`) | The **latest** Boost only; a new activation replaces it (AD-57). No history: `boost_triggers` stays not tracked |
| `version` | Number ≥ 1 | yes | Monotonic; every write is a compare-and-set on it (AD-64) |
| `createdAt`, `updatedAt` | Date | yes | Explicit |

**Index:** `{ userId: 1 }` unique.

**Never stored:** the Super Like balance (the ledger, §5.5, is the only source), prices, payments, orders, receipts, settlements, payment instruments, provider payloads or credentials.

### 9.2 Trust (AD-62, AD-63)

| Environment | A subscription or Boost counts when |
|---|---|
| production (`NODE_ENV` other than exactly `development` or `test`) | `source === 'provider'` |
| development, test | `source` is `simulation` or `provider` |

An untrusted component is read as absent; an unknown `source` is never trusted. Nothing ever writes `source: provider` in this build (no real provider exists), so in production no subscription or Boost can be trusted. A future real action would overwrite a simulated component by compare-and-set.

### 9.3 Writes (AD-64)

- **First write:** an insert with `version: 1`, guarded by the unique `userId`; a concurrent second insert answers 409 `entitlement_changed` after a re-read.
- **Later writes:** `findOneAndUpdate({ userId, version: expected }, { $set, $inc: { version: 1 } })`; `null` → 409 `entitlement_changed`. A Boost write keeps the subscription as read, and the reverse; because the version is compared, a concurrent change to the other component also refuses the write instead of overwriting it.
- One document per write: no transaction.

### 9.4 Simulated Super Like credits and the contamination safeguard (AD-61)

- **The credit:** `superLikeService.credit` appends `+count` with reason `simulated_pack_purchase` and reference `key:<purchaseKey>` (or `auto:<random hex>` without a key), **inside a transaction** like every ledger write. The existing indexes give exactly-once per reference and serialize credits with debits; the runner retries a lost race for the next position. The service refuses to credit in production.
- **Production start-up:** after the database connection, one query (`reason: 'simulated_pack_purchase'`, using `{ reason, createdAt }`) refuses start-up if any entry exists. Nothing is deleted or rewritten.
- **Production at run time:** before returning a balance and before every ledger append (a debit, or the registration grant), one indexed query checks that account for a `simulated_pack_purchase` entry, inside the same transaction when there is one. If found, that account's Super Like balance and spending answer 503 `super_likes_unavailable`, the transaction aborts (no debit, no record change, no Match), and an error is logged with the account ID only. The balance is never recomputed; no entry is changed.
- **Clean accounts:** the same reads and writes as before, plus that one check in production; the AD-22 grant and every debit behave exactly as before.
- **Development and test:** simulated credits are ordinary ledger entries; the balance includes them.

### 9.5 Stores

- `entitlementStore` (memory and MongoDB, one contract): `findByUserId`, `insert`, `updateIfVersion`.
- `ledgerStore` gains `hasReason(userId, reason, { session })` and `existsWithReason(reason)`.

---

## 10. Admin and moderation operations (Recovery 9) — **IMPLEMENTED (Recovery 9-A to 9-D); RUNTIME-UNVERIFIED**

> **Status after Recovery 9-A:**
> - **Implemented:**
>   - `AdminAuditLog` (§10.1): model, indexes, append-only middleware, insert-only store (`src/repositories/adminAudit.repository.js`), entries built only by `buildAuditEntry` (`src/config/adminPolicy.js`);
>   - `User.adminLock` and `userStore.touchAdminLock` (§10.3);
>   - `session` options on `sessionStore.revokeAllForUser` and `reportStore.transition` (§10.2);
>   - the transaction guard that writes the lock, re-reads the actor and writes the audit in one unit (`src/services/adminGuard.service.js`).
> - **Recovery 9-B:** the report list, detail and transition routes and the audit-log listing use these (contract §15.6). The action `report.evidence_released` is renamed `report.details_released` (AD-77); nothing had written the old name. `reportStore.findById` takes a `session` option; `reportStore.listByStatus` takes `order` (`desc` or `asc`, by `createdAt` then `_id`). No model, field or index changes.
> - **Recovery 9-C:** the `User { registrationCompletedAt: 1 }` index (R9-T10); `userStore.setAccountStatusIf(id, { from, to }, { session })` (transaction only; conditional on role `USER` and status `from`); batched `verificationStore.findByUserIds` and `listByState(state, { evidence, skip, limit })` (oldest `stateChangedAt` first, on the existing `{ state, stateChangedAt }` index); batched `entitlementStore.findByUserIds`; a read-only `adminUserStore.listIds` (an aggregation over `users`, with `$lookup` into `profiles` for the escaped search and into `verifications` for the effective-record filter, sorted by `registrationCompletedAt` and `_id` descending, then `$skip` and `$limit`). The suspension and reinstatement transactions of §10.2 are implemented as written. No new collection or field.
> - **Recovery 9-D:** the `Session { lastUsedAt: 1 }` and `Message { createdAt: 1, moderation: 1 }` indexes (R9-T10). Read-only count methods, each refusing to run without a positive integer `maxTimeMS` and applying it (`src/utils/queryTimeout.js`): `adminUserStore.countEligible` (the same filter as `listIds`, optionally a registration range [from, before)), `verificationStore.countByState`, `reportStore.countByStatuses`, `moderationEventStore.countByStatus`, `sessionStore.countAccountsUsedBetween` (a distinct-account aggregation), `messageStore.countDeliverableBetween` (held messages excluded), `ledgerStore.countByReasonBetween`. `verificationStore.listByState` takes an optional `order` (`asc` by default, unchanged). No new collection or field. Super Like ledger entries are stamped with the server time at insert (Mongoose timestamps), so the `super_likes` window relies on the server clock, which is what the dashboard uses in production.
> - **Deployment:** run `npm run db:indexes` (AD-74) so that the three Recovery 9 indexes on existing collections exist before the dashboard is used; without them its counts scan and may hit `maxTimeMS`, which answers 503.
> - **Not demonstrated:** the MongoDB behaviour (append-only middleware, transactional insert creating the collection, the `adminLock` write conflict). All of it is NOT EXECUTED in this workspace (readiness checks D-2, D-3, D-5).

> Design proposal awaiting approval (revision 2, after design review); no model or index below exists. Detail: `docs/reports/RECOVERY_9_DESIGN_REQUEST.md` §7–§16. Decision status: `IMPLEMENTATION_DECISIONS.md`, "Recovery 9: proposed".

### 10.1 `AdminAuditLog` (implemented, Recovery 9-A)

| Field | Type | Required | Visibility | Notes |
|---|---|---|---|---|
| `_id` | ObjectId | yes | admin | |
| `actorId` | ObjectId → `User` | yes | admin | Re-read as an active `ADMIN` inside the action's transaction |
| `actorSessionId` | ObjectId → `Session` | yes | admin | |
| `action` | String enum `user.suspended`, `user.reinstated`, `report.status_changed`, `report.details_released` | yes | admin | `report.details_released` = the server committed to returning a report's details, with or without evidence (AD-77, replacing the proposed `report.evidence_released`); it does not claim a human read them |
| `targetType` | String enum `user`, `report` | yes | admin | |
| `targetId` | ObjectId | yes | admin | |
| `subjectUserId` | ObjectId → `User` | yes | admin | The member affected |
| `change` | `{ from, to }` (enumerated strings) or `null` | no | admin | Account states or report statuses only; `null` for a details release |
| `requestId` | String | yes | admin | The existing request ID |
| `outcome` | String enum `success` | yes | admin | Entries exist only for actions that committed |
| `createdAt` | Date | yes | admin | Server time |

**Never stored:**
- report reasons, resolutions and internal notes;
- evidence and message text;
- names, and phone numbers;
- tokens and OTPs;
- IP addresses and user agents;
- request bodies.

**Indexes (proposed):**
- `{ createdAt: -1, _id: -1 }`, for listing and the cursor;
- `{ actorId: 1, createdAt: -1 }`;
- `{ targetType: 1, targetId: 1, createdAt: -1 }`;
- `{ subjectUserId: 1, createdAt: -1 }`;
- `{ action: 1, createdAt: -1 }`.

**Append-only:**
- the store has `insert` and reads only;
- schema middleware refuses `updateOne`, `updateMany`, `findOneAndUpdate`, `replaceOne`, `deleteOne`, `deleteMany`, `findOneAndDelete` and `findOneAndReplace`;
- a project rule allows writes only from the admin guard;
- no route updates or deletes an entry: the only audit route is the listing `GET /api/admin/audit-logs` (Recovery 9-B, AD-78), whose answer never includes `actorSessionId`.

A database role without update or delete privileges on the collection is a deployment control, **not verifiable in this workspace**.

**Retention:** undecided (a production blocker; AD-78 keeps every retention period undecided); no deletion is built. The record holds IDs and enumerated values only, so an account purge (Recovery 9B) needs no audit rewrite.

### 10.2 Proposed transaction boundaries and concurrency

| Action | One transaction | After commit | Concurrency |
|---|---|---|---|
| Report status change (implemented, R9-B) | actor lock write + re-read (R9-T2); `Report` read and conditional update on `{ _id, status: expectedStatus }` (existing hook, with `session`); `report.status_changed` insert; `report.details_released` insert (the answer is the report's details) | — | a stale `expectedStatus` answers 409 `report_state_changed`; the graph is acyclic, so no ABA |
| Details release (implemented, R9-B) | actor lock write + re-read; `Report` read (with evidence, with `session`); `report.details_released` insert | the details are put in the response | a failed read writes no entry; a failed insert answers 503 and a failed commit fails the request; neither returns details |
| Account suspension (implemented, R9-C) | actor lock write + re-read; `User` conditional update on the current status; `Session` revoke all (reason `admin`, with `session`); audit insert | disconnect the member's sockets (best effort) | the loser of a race answers 409 `account_status_changed`, or 200 without an entry if nothing would change |
| Account reinstatement (implemented, R9-C) | actor lock write + re-read; `User` conditional update; audit insert | — | as above; revoked sessions stay revoked |

An audit insert failure aborts the transaction: nothing changes (P-11). Retries are the runner's existing bounded retries only.

### 10.3 Changes to existing models (`adminLock` implemented in 9-A; the `User` index in 9-C; the `Session` and `Message` indexes in 9-D)

| Model | Change | Serves |
|---|---|---|
| `User` | **field** `adminLock` (Number, default 0, internal, never returned), written first by every admin transaction (R9-T2, revised 2.2) | a write conflict with a concurrent demotion or suspension of the acting admin |
| `User` | `{ registrationCompletedAt: 1 }` (**implemented, R9-C**) | `total_members`, `new_today`, recent registrations, the admin user list order |
| `Session` | `{ lastUsedAt: 1 }` (**implemented, R9-D**) | `active_users` (approximate) |
| `Message` | `{ createdAt: 1, moderation: 1 }` (**implemented, R9-D**) | `messages_sent` (24 h, deliverable messages only; held messages excluded) as a covered count |

Existing indexes already serve:
- `open_safety_reports`: `Report { status, createdAt }`;
- `moderation_alerts`: `ModerationEvent { status, createdAt }`;
- `super_likes`: `SuperLikeLedgerEntry { reason, createdAt }`;
- `verification_backlog` and the queue: `Verification { state, stateChangedAt }`;
- the settings counters: `Block { blockerId, createdAt }`, `Report { reporterId, createdAt }`.

**No retention fields are added in Recovery 9.** `Report.evidenceRedactedAt` and a redaction or anonymization command (design request §12) would be added **only after** retention periods are approved (P-13).

### 10.4 Unchanged

- `Report`: graph, `openKey`, rate limit and evidence capture (§7.2);
- `ModerationEvent`: no review workflow (§7.3);
- `Verification` and its trust rule (§8);
- `PremiumEntitlement` and the ledger (§9);
- `User.role` changes only through the command line or the documented operator procedure (§2; design request §7.1).

No admin read bypasses the member privacy rules (P-09).

---

## 11. Member settings (Recovery 9B) — **IMPLEMENTED; RUNTIME-UNVERIFIED**

Decisions AD-19, AD-34, AD-70, AD-71, AD-84 to AD-89, AD-93 to AD-96; `API_CONTRACT.md` §16.

### 11.1 `UserSettings` (collection `usersettings`)

| Field | Type | Required | Visibility | Notes |
|---|---|---|---|---|
| `_id` | ObjectId | yes | owner | |
| `userId` | ObjectId → `User` | yes | owner | **Unique**: one record per account |
| `privacy.onlineActivityIndicator` | Boolean | no | owner | `false` hides the member's online status (with the profile's `showOnlineStatus`, the more restrictive winning). Absent: no restriction (AD-85) |
| `privacy.displayExactAge` | Boolean | no | owner | `false` hides the member's exact age (with the profile's `showExactAge`, the more restrictive winning). Absent: no restriction (AD-93) |
| `paused` | Boolean | no | owner | `true` keeps the member out of discovery (AD-89). Absent: not paused |
| `createdAt`, `updatedAt` | Date | yes | — | Server time |

- Strict schema: no other setting is stored. `approximateProximity` (AD-94), `intentAndDietaryPrivacy` (AD-95, deferred), `culturalHeritageAndHometown` (AD-96) and the notifications are not approved.
- **No migration:** records written before AD-89 and AD-93 simply lack the new fields, which read as "no restriction" and "not paused". Members without a record are unchanged.
- Index: `{ userId: 1 }` unique. Registered with `npm run db:indexes` (`listModels()`). In production `autoIndex` is off, so `db:indexes` must run before the settings routes take traffic; otherwise two simultaneous first writes for one member could insert two records (the unique index is what prevents it).
- Store `userSettingsStore` (`src/repositories/userSettings.repository.js`): `findByUserId`, `findByUserIds` (batched), `setPrivacy(userId, values, now)` (one or both approved switches in one write; any other key is a `TypeError`) and `setPaused(userId, paused, now)`. Each is one upsert on the unique `userId`; a duplicate-key race between two first writes is retried once, then it is an update. **No delete method**: removing settings belongs to the account-deletion design, which is not approved.
- Written only by `src/services/settings.service.js`; read only by it and `src/services/settingsPrivacy.js` (project rule). Admin code receives only `{ displayExactAge }` through `settingsPrivacy.ageSettingsOf`, to show the age as members see it (AD-75).
- **Discovery:** the discovery aggregation (`src/repositories/discovery.repository.js`) looks up each candidate's record on the unique `userId` index after the account lookup and leaves out `paused: true`, and, with an age filter, `privacy.displayExactAge: false`. A candidate without a record passes. No new index.

### 11.1a Sessions (AD-88)

- `sessionStore.listActiveForUser(userId, { now, limit })`: `{ userId, revokedAt: null, expiresAt: { $gt: now } }`, sorted by `lastUsedAt` descending, at most `limit` (50, provisional). On the existing `sessions { userId, revokedAt }` index: only the account's own sessions are read, then sorted. No new index.
- `sessionStore.revokeForUser(id, userId, { reason, now })`: one conditional update on `{ _id, userId, revokedAt: null, expiresAt: { $gt: now } }`, reason `user`; returns whether it revoked. It cannot touch another account's session.

### 11.2 The counters

- `blockStore.countByBlocker(blockerId)`: `{ blockerId }` on `blocks { blockerId, createdAt }`, exactly the set `listByBlocker` pages through.
- `reportStore.countByReporterInStatuses(reporterId, statuses)`: `{ reporterId, status: { $in } }` on `reports { reporterId, createdAt }`; never by target. Called with `OPEN` and `UNDER_REVIEW`.
- Each count reads only the caller's own records (the index's first field is the caller). No new index.

## 12. Deletion request (batch LC-3) — **IMPLEMENTED; RUNTIME-UNVERIFIED; NON-DESTRUCTIVE**

Decisions AD-97 to AD-102; `API_CONTRACT.md` §17. Nothing in this section deletes anything.

### 12.1 `User.deletionPendingAt`

- Date or `null` (default `null`; a missing field reads as `null`, so no migration is needed). Set while a request is pending.
- Separate from `accountStatus`: suspension and reinstatement do not touch it, and it does not touch them.
- Written only by `userStore.markDeletionPending(id, at, { session })`, a conditional update on `{ _id, role: USER, accountStatus: active, deletionPendingAt: null }`, and `userStore.clearDeletionPending(id, { session })`, on `{ _id, deletionPendingAt: { $ne: null } }`. Both run only inside a transaction. `promoteToAdmin` refuses a pending account.
- Read by `isMemberAvailable` (`src/utils/memberAvailability.js`) wherever another member's availability is decided. The discovery aggregation matches `'account.deletionPendingAt': null` after the account lookup. **No new index**: the field is checked on documents already selected.

### 12.2 `AccountDeletionRequest` (collection `accountdeletionrequests`)

| Field | Type | Notes |
|---|---|---|
| `_id` | ObjectId | Generated before the insert, so the history can name it |
| `userId` | ObjectId → `User` | |
| `status` | `pending` \| `cancelled` | Later purge states do not exist |
| `requestedAt` | Date | |
| `scheduledPurgeAt` | Date | `requestedAt` + 30 days: an **eligibility** time (AD-98); nothing reads it |
| `cancelledAt` | Date \| null | |
| `createdAt`, `updatedAt` | Date | |

- Strict schema. Indexes: `{ userId: 1 }` **unique, partial on `status: "pending"`** (one pending request per account); `{ userId: 1, requestedAt: -1 }`.
- Store `accountDeletionStore`: `findPendingByUserId`; `insertPending` (transaction only); `cancelPending(id, userId, at)` (transaction only; conditional on `{ _id, userId, status: pending }`). **No delete method.**

### 12.3 `AccountDeletionEvent` (collection `accountdeletionevents`; append-only)

| Field | Type |
|---|---|
| `requestId` | ObjectId → `AccountDeletionRequest` |
| `userId` | ObjectId → `User` |
| `event` | `requested` \| `cancelled` |
| `sessionId` | ObjectId → `Session` (the confirming session) |
| `createdAt` | Date |

- Strict schema. The model refuses every update and delete operation (the admin audit log's list). Indexes: `{ requestId: 1, createdAt: 1 }`, `{ userId: 1, createdAt: -1 }`.
- Store `accountDeletionEventStore`: `insert` (transaction only), `listForUser`. No retention period is chosen.

### 12.4 `OtpRequest.purpose` and `OtpRequest.userId` (AD-97, AD-104)

- `purpose`: `sign_in` \| `deletion_request` \| `deletion_cancel`. Required on new records. A record made before AD-97 has none and reads as `sign_in`; the queries also match a missing value for `sign_in`, so such records stay valid before and after the migration.
- `userId`: the account of a deletion-related code; `null` for sign-in codes (enforced by the store).
- Indexes:
  - **`{ countryCode: 1, phoneNumber: 1, purpose: 1 }` unique, partial `{ active: true }`**: one active code per number and purpose;
  - `{ userId: 1, purpose: 1, lastSentAt: -1 }`, partial on `userId` being an ObjectId: the per-account limits;
  - unchanged: `{ requestId: 1 }` unique, `{ countryCode: 1, phoneNumber: 1, lastSentAt: -1 }`, and the TTL on `purgeAt`.

### 12.5 Deployment

- `npm run db:indexes` creates the new indexes. `listModels()` includes both new models. Run it before the routes take traffic: without the partial unique index, two simultaneous requests could each insert a pending record.
- **Runtime-unverified:** none of this has run on MongoDB.

### 12.6 The OTP purpose migration (AD-104)

| | Index | Effect |
|---|---|---|
| Old | `{ countryCode: 1, phoneNumber: 1 }`, unique, partial `{ active: true }`, name `countryCode_1_phoneNumber_1` | One active code per number, any purpose |
| New | `{ countryCode: 1, phoneNumber: 1, purpose: 1 }`, unique, partial `{ active: true }`, name `countryCode_1_phoneNumber_1_purpose_1` | One active code per number and purpose |

`npm run db:indexes` creates the new index but **never drops the old one**. While both exist, the old, stricter index still applies: a deletion code is refused (429) while a sign-in code is active for the number. Uniqueness is never weakened, but the purposes are not yet isolated. Nothing drops or replaces an index at application start (`autoIndex` is off in production, and no application code loads the migration).

**Command:** `npm run db:migrate-otp-purpose`. It is a dry run by default, reading and reporting only. `-- --apply` backfills `purpose: "sign_in"` and `userId: null` on records without a purpose, then creates the declared indexes. `-- --apply --drop-old-index` then drops the old index, only if it has exactly the old specification and the new index exists. It is idempotent, it refuses an index named like the old one with another specification, and it prints the target with credentials masked. Nothing is deleted.

**Deployment order:**
1. Run it on a **disposable copy** of the database (restored backup or `mongodb-memory-server`), and check the printed plan and the result: `db.otprequests.getIndexes()`.
2. Deploy the code.
3. Run `--apply` (the new index appears; the old one still applies).
4. Run `--apply --drop-old-index` (the purposes become isolated).

Existing OTP records live about a day (TTL on `purgeAt`) and active codes five minutes. A pre-AD-97 active sign-in code stays usable as a sign-in code throughout.

**Runtime-unverified:** the migration has run only against a recording stand-in here. `tests/db/otpPurposeMigration.test.js` exercises it on a real replica set and is NOT EXECUTED in this workspace.
