From 7f986dec48cb20186e95ff9dece10d3834a6993a Mon Sep 17 00:00:00 2001 From: Lily Shen <115414357+lilyshen0722@users.noreply.github.com> Date: Sun, 1 Nov 2026 19:33:20 -0800 Subject: [PATCH 1/4] docs(adr-034): Postgres is the single data store; no new Mongo model Records the founder's 2026-10-25 direction as ADR-034, with the split re-measured at e2cb8c2fc: 70 Mongo model names in 69 files against 14 Postgres tables, three Mongo models added after the first count, chat already Postgres-only where PG_HOST is set. Decides JSONB for document fields, text ObjectId ids, a repository per aggregate, a four-step reversible move per model, one major per engine, and the wave order. D4 lands with its guard: mongoModelFreeze.test.js fails on a new model name, an unreadable registration in models/, or a model or schema defined outside models/. POSTGRESQL_MIGRATION.md points at the ADR. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015AKgpQ2pr6xRMhN5mcfoHF --- .../unit/models/mongoModelFreeze.test.js | 83 ++++++++++ docs/adr/ADR-034-postgres-single-store.md | 144 ++++++++++++++++++ docs/database/POSTGRESQL_MIGRATION.md | 3 + 3 files changed, 230 insertions(+) create mode 100644 backend/__tests__/unit/models/mongoModelFreeze.test.js create mode 100644 docs/adr/ADR-034-postgres-single-store.md diff --git a/backend/__tests__/unit/models/mongoModelFreeze.test.js b/backend/__tests__/unit/models/mongoModelFreeze.test.js new file mode 100644 index 0000000000..2e59422499 --- /dev/null +++ b/backend/__tests__/unit/models/mongoModelFreeze.test.js @@ -0,0 +1,83 @@ +/** + * ADR-034 D4: no new Mongo model. Every collection added from now on is a + * Postgres table (a numbered file in config/migrations plus a repository; see + * docs/database/schema-migrations.md). This list is the Mongo models that + * existed when the rule was set, and it only shrinks: a model that moves to + * Postgres comes off it in the same PR. + */ +const fs = require('fs'); +const path = require('path'); + +const BACKEND_DIR = path.join(__dirname, '../../..'); +const MODELS_DIR = path.join(BACKEND_DIR, 'models'); + +// Files in models/ that register no Mongo model: a Postgres-backed model and a helper. +const NOT_MONGO_MODELS = ['ToolCall.ts', 'integrationPublicConfig.ts']; + +const MONGO_MODELS = [ + 'AccountDeletion', 'Activity', 'AdminUserMutationLock', 'AgentAsk', 'AgentComputerTakeover', + 'AgentCredential', 'AgentDigestState', 'AgentEnsembleState', 'AgentEvent', 'AgentFirstContact', + 'AgentInstallation', 'AgentMemory', 'AgentPodReadCursor', 'AgentProfile', 'AgentProviderKey', + 'AgentRegistry', 'AgentRun', 'AgentRuntimeObservation', 'AgentTaskRowWakeState', 'AgentTaskWakeState', + 'AgentTemplate', 'Announcement', 'App', 'AppInstallation', 'ApprovalAction', + 'AttentionItem', 'AttributionVisit', 'AuditLog', 'BillingEvent', 'ChannelVerdict', + 'ConnectorSecret', 'DecisionRequest', 'DeviceAuthorization', 'DiscordIntegration', 'DiscordSummaryHistory', + 'ExternalLink', 'File', 'Gateway', 'GithubGigBinding', 'GithubGigDelivery', + 'HookLedgerEvent', 'HostedMcpDcrRegistration', 'Installable', 'InstallableInstallation', 'Integration', + 'InvitationCode', 'Machine', 'MediaObject', 'Message', 'NeedsYouEmail', + 'NeedsYouEmailQuota', 'OAuthLoginState', 'OAuthState', 'OnboardingSilenceEpisode', 'Pod', + 'PodAsset', 'PodInvite', 'PodLink', 'PodMemberFirstMessage', 'Post', + 'RoomGrant', 'SchedulerHeartbeatLease', 'SkillRating', 'StalledConnectEpisode', 'Summary', + 'SystemSetting', 'Task', 'User', 'WaitlistRequest', 'WebhookDelivery', +]; + +// `mongoose.model('Name', …)` and `model(\n 'Name', …)` alike. +const REGISTRATION = /(?:mongoose\.)?model\s*(?:<[^>]*>)?\(\s*['"](\w+)['"]/g; + +const isSource = (file) => /\.(ts|js)$/.test(file) && !file.endsWith('.d.ts'); +const modelFiles = () => fs.readdirSync(MODELS_DIR).filter(isSource); +const namesIn = (file) => [...fs.readFileSync(path.join(MODELS_DIR, file), 'utf8').matchAll(REGISTRATION)] + .map(([, name]) => name); + +const registeredNames = () => new Set(modelFiles().flatMap(namesIn)); + +// Production source outside the top level of models/, where a model must not be defined. +const SKIP_DIRS = new Set(['node_modules', '__tests__', 'scripts', 'dist', 'coverage']); +const sourceOutsideModels = (dir = BACKEND_DIR) => fs.readdirSync(dir, { withFileTypes: true }) + .flatMap((entry) => { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) return SKIP_DIRS.has(entry.name) ? [] : sourceOutsideModels(full); + if (dir === MODELS_DIR || !isSource(entry.name)) return []; + return [full]; + }); + +describe('Mongo model freeze (ADR-034 D4)', () => { + const registered = registeredNames(); + + it('registers no Mongo model outside the frozen list', () => { + const added = [...registered].filter((name) => !MONGO_MODELS.includes(name)).sort(); + // A new collection is a Postgres table: add backend/config/migrations/NNNN_.sql + // and a repository under backend/repositories/ (docs/adr/ADR-034-postgres-single-store.md). + expect(added).toEqual([]); + }); + + it('reads a registration from every model file, so a new form cannot slip past', () => { + const unread = modelFiles() + .filter((file) => !NOT_MONGO_MODELS.includes(file) && namesIn(file).length === 0); + // Register with mongoose.model('Name', schema), or move the file out of models/. + expect(unread).toEqual([]); + }); + + it('defines no Mongo model or schema outside models/', () => { + const defining = sourceOutsideModels() + .filter((file) => /mongoose\.model\(|new (mongoose\.)?Schema\(/.test(fs.readFileSync(file, 'utf8'))) + .map((file) => path.relative(BACKEND_DIR, file)); + expect(defining).toEqual([]); + }); + + it('lists only models that still exist, so the list shrinks as models move', () => { + const gone = MONGO_MODELS.filter((name) => !registered.has(name)); + // A model that moved to Postgres comes off MONGO_MODELS in the same PR. + expect(gone).toEqual([]); + }); +}); diff --git a/docs/adr/ADR-034-postgres-single-store.md b/docs/adr/ADR-034-postgres-single-store.md new file mode 100644 index 0000000000..040749f3a3 --- /dev/null +++ b/docs/adr/ADR-034-postgres-single-store.md @@ -0,0 +1,144 @@ +# ADR-034: Postgres is the single data store + +**Status:** **Accepted** 2026-11-02 as the direction. The project's founder set it on 2026-10-25: +Mongo plus Postgres makes self-hosting hard, so the target is Postgres only. **Accepting the +direction does not settle three things, and each is named where it lives:** the effort estimate +(Effort is a 10-25 estimate, not a commitment), the order inside Wave 5 (D6), and the size of the +mismatch log that a read cut may tolerate (D3 sets it at zero unexplained mismatches, which may prove +too strict for models with clock-derived fields). + +**Deciders:** founder (direction), eng lead (plan). + +**Scope boundary.** This ADR decides where data lives. It does not reopen these: +- **ADR-002** (attachments): `MediaObject` bytes move to an object-store driver, never to a table. +- **ADR-003** (memory): `AgentMemory` moves table with its contract unchanged. +- **ADR-033** (grant record): its record chains already live in Postgres (`0002_record_chains.sql`). + Its Mongo rows (`RoomGrant`, `ApprovalAction`, `DecisionRequest`, `Task`) move in Wave 3. +- **The founder's decision to keep the current stack** rather than rebuild it on another platform. This + ADR is a migration inside that stack, one model at a time, and the stack keeps working at every step. +- **The vector search index** (`services/vectorSearchService.ts`, a local SQLite file with `sqlite-vec`) + is derived from pod content and rebuilt from it. It is an index, not a store of record. +- **ADR-011** (shell-first): this is kernel work and launch does not wait on it. + +## Context: the split, measured at `origin/main` `e2cb8c2fc` (2026-11-02) + +| | Mongo | Postgres | +|---|---|---| +| Models / tables | **70** registered model names in 69 files under `backend/models/` (`AgentRegistry.ts` registers `AgentRegistry` and `AgentInstallation`) | **14** tables: `messages`, `pod_message_revisions`, `message_reactions`, `thread_user_state`, `message_claims`, `tool_calls`, `tool_call_budgets`, `record_chains`, `record_lines`, `pg_retention_runs`, `migration_records`, plus `pods`, `pod_members` and `users`, which are **copies** of Mongo rows. The migration runner keeps its own `schema_migrations`. | +| Callers | 245 non-test, non-script files import a model from `models/` | 3 repositories under `backend/repositories/` | +| Since `136709aa0` (2026-10-25 06:15 UTC) | **+3** (`AccountDeletion` #2721, `AdminUserMutationLock` #2742, `AgentTaskRowWakeState` #2757), −2 dead (`Session`, `DiscordMessageBuffer`, #2680) | +2 (`record_chains`, `record_lines`) | + +**What already moved.** +- **Messages.** On an instance with `PG_HOST` set, Postgres is the only message store (#2989). + Mongo still holds history from before an install had Postgres, which + `scripts/backfill-local-messages-to-pg.ts` copies under its Mongo id (`services/legacyMessageCopy.ts`). + An instance without `PG_HOST` still writes messages to Mongo and refuses replies + (`REPLY_REQUIRES_POSTGRES`, `controllers/messageController.ts`). +- **Schema delivery.** Versioned migrations run at boot under an advisory lock (#2684, + `docs/database/schema-migrations.md`). Three tables still also create themselves at runtime with + `CREATE TABLE IF NOT EXISTS`, outside the runner: `message_claims` (`services/messageClaimService.ts`), + and `tool_calls` and `tool_call_budgets` (`models/ToolCall.ts`). `message_claims` exists only that way. +- **Repositories.** `messageRepository`, `agentPodReadCursorRepository` and `recordChainRepository` + exist. Only `AgentPodReadCursor` is fenced by lint (`backend/.eslintrc.js`, `no-restricted-imports`). +- **Self-host.** `docker-compose.local.yml` runs Postgres beside Mongo (#2806), so `./install.sh` no + longer runs chat on a fallback. It does need both databases. + +**What makes the move tractable.** No multi-document transactions (0 `startSession` or +`withTransaction` in production code), no change streams (0 `.watch(`), three `$lookup`s, and Postgres +already keys rows by the 24-character ObjectId hex (`pods.id`, `users._id`). **What makes it large.** +about 95 `.populate(` calls in production code, 27 `Mixed` fields across 14 model files, 10 model files with +TTL indexes, and atomic claims written as single-document `findOneAndUpdate` +(`services/agentEventService.ts`, the scheduler lease). + +**The image majors still differ.** Tags are exact since #2678, but the majors are not one: +Postgres 15 (helm `values.yaml`), 16 (`docker-compose.local.yml` and the backup job's `pg_dump`) and 17 +(`docker-compose.dev.yml`, `docker-compose.yml`); Mongo 7, 8.2 and 9.0.4. + +## Decisions + +### D1. Postgres is the target store, with JSONB for document-shaped fields +Every Mongoose model moves to a Postgres table. Scalar, indexed and referenced fields become columns. +`Mixed` fields and config `Map`s become **JSONB** (`AgentEvent.payload`, `AgentRun.args` and `result`, +the five on `Installable`, `AgentInstallation.config`). A JSONB column is the honest shape of a field +whose schema belongs to an agent or a manifest; normalize later only where a query needs it. + +**Ids stay the 24-character ObjectId hex, stored as `text`**, for migrated rows and new ones +(`new ObjectId().toHexString()`), so every existing reference, URL, token and log line stays valid. + +### D2. Callers reach storage through a repository +One module per aggregate under `backend/repositories/` exposes domain functions +(`findInstallation(agentName, instanceId, podId)`, `claimNextEvent(...)`), not a query builder. It +returns plain objects, so `.save()`, `.populate()` and virtuals stop at the boundary. When a model's +callers have all moved, a `no-restricted-imports` entry for it joins the `AgentPodReadCursor` one, so the +boundary holds. + +### D3. Each model moves in four reversible steps +| Step | What | Rollback | +|---|---|---| +| 1. Extract | Callers move to the repository, which still reads and writes Mongo. No behaviour change. | Revert the PR. | +| 2. Dual | Writes go to both stores. Reads stay on Mongo, and a sample is read from Postgres too, compared, and any mismatch logged. A per-model mode (`mongo`, `dual`, `pg-read`, `pg`; default `mongo`) selects the step. A backfill copies history. | Mode to `mongo`. The next backfill discards the Postgres rows. | +| 3. Read cut | Reads come from Postgres; writes still go to both. | Mode to `dual`. Mongo is still complete. | +| 4. Drop | Mongo writes stop, and the Mongo code is deleted one release later. | Before deletion: mode to `dual` plus a reverse backfill. After: restore from backup. | + +Step 4 is the only one-way door, and it is taken per model. **A model reaches step 3 when the +`commonly verify` scenarios pass against both stores and the compare log shows zero unexplained +mismatches**, not after a fixed number of days. + +### D4. No new Mongo model +Every collection added from now on is a Postgres table: a numbered file in `backend/config/migrations/` +and a repository. The three models added after the first count show the default runs the other way when +nothing stops it. `backend/__tests__/unit/models/mongoModelFreeze.test.js` lists the 70 names and fails +on a new one, on a file in `backend/models/` whose registration it cannot read, and on a +`mongoose.model(` or `new Schema(` anywhere else in production code. A removed model comes off the list +in the same PR, so the list only shrinks. A raw `connection.collection('…')` write is outside what the +test can see, so review catches that one. + +### D5. One major per engine, changed on purpose +Postgres settles on 17 and Mongo on one major until it is removed. **A major change on a running +server is a data migration, not a tag edit**: Postgres needs `pg_upgrade` or a dump and restore, and +Mongo moves one major at a time with `featureCompatibilityVersion` set before each step. Each running +deployment's change is its own planned change with a backup taken first. Compose files and fresh installs +can move in an ordinary PR. + +### D6. Order +**Wave 0, what is left.** Make Postgres required: remove the no-`PG_HOST` message mode, so an instance +without Postgres refuses to boot instead of running degraded, and Mongo `Message` keeps only the history +the backfill copies. Move the three self-creating tables into numbered migrations. Build the dual-store helper (D3's mode, +write-both, sampled compare), a shared expiry sweeper for TTL models, and a jest helper on real +Postgres for anything with claims or SQL aggregates (`ToolCall.ts` already records that `pg-mem` +cannot run a correlated `EXISTS`). + +**Waves 1 to 5** go from fewest callers to most, and lanes are split by caller-file overlap, because +step 1 is the only step that edits callers: + +| Wave | Models | Note | +|---|---|---| +| 1 | 16 self-contained models with one owning service each (wake states, first-contact, billing events, needs-you email, GitHub gig, provider keys, onboarding episodes) | no populate, TTL or inbound refs; six parallel lanes | +| 2 | 18 TTL and small-populate models (OAuth and device state, webhook deliveries, asks, verdicts, invites, audit log, the scheduler lease) | needs the expiry sweeper; the lease becomes `INSERT … ON CONFLICT … WHERE expires_at < now()` | +| 3 | 12 agent-ops models (`AgentRun`, `AgentMemory`, `Task`, `Activity`, `DecisionRequest`, `AttentionItem`, `RoomGrant`, `Machine`, …) | `aggregate` calls become hand-written SQL, tested on real Postgres | +| 4 | 14 content and catalog models (`Post`, `Summary`, `PodAsset`, the `Installable` cluster, `AgentRegistry`) | `MediaObject` is a driver swap (ADR-002); `AgentRegistry.ts` is split first so `AgentInstallation` has its own file | +| 5 | `User`, `Pod`, `AgentInstallation`, `Integration`, `AgentEvent`, `AgentCredential` | callers overlap almost completely, so step 1 is one codemod per model, serial; the `pods`, `pod_members` and `users` copies are **replaced** by the real tables, never joined by a third copy | + +The waves hold 66 models. `Message` leaves in Wave 0, and the three models added after the first count +join Wave 1, which accounts for all 70. The order inside Wave 5 is open. + +## Risks +- **Copy drift is a bug we already have.** The Postgres `pods`, `pod_members` and `users` rows are synced + by hand from Mongo (`services/pgPodSyncService.ts` and its callers). Wave 5 removes the copies. +- **Claims and leases.** Port each `findOneAndUpdate` claim as `UPDATE … RETURNING` or + `FOR UPDATE SKIP LOCKED`, and test the losing claimant on real Postgres. A transaction where Mongo had + none is allowed, and it is written down when it happens. +- **TTL.** Postgres has no TTL index. The sweeper lags, so every read of an expiring row also filters + `expires_at > now()`. +- **Document size.** JSONB values above about 2 KB are stored out of line, so a large `AgentRun.result` + slows reads long before it fails. Cap it at write. +- **ObjectId semantics.** Code that sorts by `_id`, reads `.getTimestamp()`, or compares `ObjectId` + instances breaks on text ids. Step 1 greps each model's callers for these. +- **Hot paths.** `User`, `Pod`, `AgentInstallation` and `AgentCredential` sit under `middleware/auth` and + `agentRuntimeAuth`; a slower query there slows every request. Measure p95 at step 3. + +## Effort (a 2026-10-25 estimate) +About **85 to 105 agent-days**, roughly 8 to 10 calendar weeks with parallel lanes in Waves 1 to 4. It +prices dual writes, comparison, backfill and moving the tests (475 test files import a model; 54 start +`mongodb-memory-server` directly and 47 use `pg-mem`). Parallel lanes shorten Waves 1 to 4. They do +not shorten the scenario runs at each read cut, and they barely help Wave 5, where callers overlap. diff --git a/docs/database/POSTGRESQL_MIGRATION.md b/docs/database/POSTGRESQL_MIGRATION.md index f5fb181823..b209b34f7b 100644 --- a/docs/database/POSTGRESQL_MIGRATION.md +++ b/docs/database/POSTGRESQL_MIGRATION.md @@ -1,5 +1,8 @@ # PostgreSQL Message Storage Migration +> **Where this is heading:** [ADR-034](../adr/ADR-034-postgres-single-store.md) makes Postgres the single +> data store and records the measured split as of 2026-11-02. The table below describes chat only. + For schema upgrades and the repository extraction template, see [Versioned PostgreSQL changes](schema-migrations.md). From 68265f349800eb031cf3f2e33cb435b627ac10a3 Mon Sep 17 00:00:00 2001 From: Lily Shen <115414357+lilyshen0722@users.noreply.github.com> Date: Sun, 1 Nov 2026 19:48:59 -0800 Subject: [PATCH 2/4] docs(adr-034): Mongo stays the record until step 4; the message cutover waits on the backfill - D3: in dual and pg-read a write commits to Mongo first and is acknowledged only then, so a rollback to dual never loses an acknowledged write; a failed Postgres write is repaired and counts as a mismatch. - Wave 0: an instance leaves the no-PG_HOST mode only when the backfill reports zero pending rows. - The freeze reads every model call, not only the forms it recognised: template-literal names register, a name it cannot read fails, generic `model(` and `new Schema(` outside models/ fail. Positive controls for each form. - The landing page's ADR count moves to 33 (its invariant test pins it). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015AKgpQ2pr6xRMhN5mcfoHF --- .../unit/models/mongoModelFreeze.test.js | 51 ++++++++++++++----- docs/adr/ADR-034-postgres-single-store.md | 12 ++++- frontend/src/v2/landing/V2LandingPage.tsx | 2 +- 3 files changed, 50 insertions(+), 15 deletions(-) diff --git a/backend/__tests__/unit/models/mongoModelFreeze.test.js b/backend/__tests__/unit/models/mongoModelFreeze.test.js index 2e59422499..a2ed32ded8 100644 --- a/backend/__tests__/unit/models/mongoModelFreeze.test.js +++ b/backend/__tests__/unit/models/mongoModelFreeze.test.js @@ -31,15 +31,24 @@ const MONGO_MODELS = [ 'SystemSetting', 'Task', 'User', 'WaitlistRequest', 'WebhookDelivery', ]; -// `mongoose.model('Name', …)` and `model(\n 'Name', …)` alike. -const REGISTRATION = /(?:mongoose\.)?model\s*(?:<[^>]*>)?\(\s*['"](\w+)['"]/g; +// Every model call, whatever its receiver or generics: `mongoose.model(`, +// `connection.model(`, `model(\n …`. Each must name its model with a +// string literal, or the test cannot know what it registers. +const MODEL_CALL = /\bmodel\s*(?:<[^>]*>)?\(/g; +const LITERAL_NAME = /^\s*['"`](\w+)['"`]/; +// Outside models/ any of these is a model defined where the freeze cannot read +// it. No space before `(`, so prose like "the model (fallback)" never matches. +const DEFINITION = /\bmodel(?:<[^>]*>)?\(|new\s+(?:mongoose\.)?Schema\s*(?:<[^>]*>)?\(/; -const isSource = (file) => /\.(ts|js)$/.test(file) && !file.endsWith('.d.ts'); -const modelFiles = () => fs.readdirSync(MODELS_DIR).filter(isSource); -const namesIn = (file) => [...fs.readFileSync(path.join(MODELS_DIR, file), 'utf8').matchAll(REGISTRATION)] - .map(([, name]) => name); +// One entry per model call: the name it registers, or null when it is not a literal. +const registrationsIn = (source) => [...source.matchAll(MODEL_CALL)].map((call) => { + const name = LITERAL_NAME.exec(source.slice(call.index + call[0].length)); + return name ? name[1] : null; +}); -const registeredNames = () => new Set(modelFiles().flatMap(namesIn)); +const isSource = (file) => /\.(ts|js)$/.test(file) && !file.endsWith('.d.ts'); +const modelFiles = () => fs.readdirSync(MODELS_DIR).filter(isSource) + .map((file) => ({ file, registrations: registrationsIn(fs.readFileSync(path.join(MODELS_DIR, file), 'utf8')) })); // Production source outside the top level of models/, where a model must not be defined. const SKIP_DIRS = new Set(['node_modules', '__tests__', 'scripts', 'dist', 'coverage']); @@ -52,7 +61,20 @@ const sourceOutsideModels = (dir = BACKEND_DIR) => fs.readdirSync(dir, { withFil }); describe('Mongo model freeze (ADR-034 D4)', () => { - const registered = registeredNames(); + const files = modelFiles(); + const registered = new Set(files.flatMap(({ registrations }) => registrations).filter(Boolean)); + + it('reads every registration form it is meant to catch (positive controls)', () => { + expect(registrationsIn("mongoose.model('A', s)")).toEqual(['A']); + expect(registrationsIn('mongoose.model(\n "B",\n s)')).toEqual(['B']); + expect(registrationsIn('mongoose.model(`C`, s)')).toEqual(['C']); + expect(registrationsIn("conn.model('D', s)")).toEqual(['D']); + expect(registrationsIn("(mongoose.models.E as Model) || model('E', s)")).toEqual(['E']); + expect(registrationsIn('mongoose.model(NAME, s)')).toEqual([null]); + ['mongoose.model(NAME, s)', 'model(`F`, s)', 'new Schema({})', 'new mongoose.Schema({})'] + .forEach((source) => expect(DEFINITION.test(source)).toBe(true)); + expect(DEFINITION.test('// fall back to the default model (no override).')).toBe(false); + }); it('registers no Mongo model outside the frozen list', () => { const added = [...registered].filter((name) => !MONGO_MODELS.includes(name)).sort(); @@ -61,16 +83,19 @@ describe('Mongo model freeze (ADR-034 D4)', () => { expect(added).toEqual([]); }); - it('reads a registration from every model file, so a new form cannot slip past', () => { - const unread = modelFiles() - .filter((file) => !NOT_MONGO_MODELS.includes(file) && namesIn(file).length === 0); - // Register with mongoose.model('Name', schema), or move the file out of models/. + it('can read the name of every registration, so a new form cannot slip past', () => { + const unread = files + .filter(({ file, registrations }) => (NOT_MONGO_MODELS.includes(file) + ? registrations.length > 0 + : registrations.length === 0 || registrations.includes(null))) + .map(({ file }) => file); + // Register with mongoose.model('Name', schema): a literal name. expect(unread).toEqual([]); }); it('defines no Mongo model or schema outside models/', () => { const defining = sourceOutsideModels() - .filter((file) => /mongoose\.model\(|new (mongoose\.)?Schema\(/.test(fs.readFileSync(file, 'utf8'))) + .filter((file) => DEFINITION.test(fs.readFileSync(file, 'utf8'))) .map((file) => path.relative(BACKEND_DIR, file)); expect(defining).toEqual([]); }); diff --git a/docs/adr/ADR-034-postgres-single-store.md b/docs/adr/ADR-034-postgres-single-store.md index 040749f3a3..950a67bf71 100644 --- a/docs/adr/ADR-034-postgres-single-store.md +++ b/docs/adr/ADR-034-postgres-single-store.md @@ -80,6 +80,12 @@ boundary holds. | 3. Read cut | Reads come from Postgres; writes still go to both. | Mode to `dual`. Mongo is still complete. | | 4. Drop | Mongo writes stop, and the Mongo code is deleted one release later. | Before deletion: mode to `dual` plus a reverse backfill. After: restore from backup. | +**Mongo stays the system of record until step 4.** In `dual` and `pg-read`, a write commits to Mongo +first and is acknowledged only once it has; the Postgres write follows. A Postgres write that fails is +recorded for repair, re-copied by the backfill, and counted as a mismatch, and in `pg-read` it sends +that model back to `dual` until the repair has run. So rolling back from `pg-read` to `dual` never loses +an acknowledged write: Mongo has every one of them. + Step 4 is the only one-way door, and it is taken per model. **A model reaches step 3 when the `commonly verify` scenarios pass against both stores and the compare log shows zero unexplained mismatches**, not after a fixed number of days. @@ -103,7 +109,11 @@ can move in an ordinary PR. ### D6. Order **Wave 0, what is left.** Make Postgres required: remove the no-`PG_HOST` message mode, so an instance without Postgres refuses to boot instead of running degraded, and Mongo `Message` keeps only the history -the backfill copies. Move the three self-creating tables into numbered migrations. Build the dual-store helper (D3's mode, +the backfill copies. Message reads come from Postgres alone once `PG_HOST` is set, so an instance moving +off that mode would hide its history until it is copied. The step is done on an instance only when +`scripts/backfill-local-messages-to-pg.ts` reports zero pending rows (rows whose pod is gone are +reported as orphaned and stay in Mongo). The release that removes the mode says so in its upgrade +note, and boot logs the pending count, so an instance that skipped the backfill shows. Move the three self-creating tables into numbered migrations. Build the dual-store helper (D3's mode, write-both, sampled compare), a shared expiry sweeper for TTL models, and a jest helper on real Postgres for anything with claims or SQL aggregates (`ToolCall.ts` already records that `pg-mem` cannot run a correlated `EXISTS`). diff --git a/frontend/src/v2/landing/V2LandingPage.tsx b/frontend/src/v2/landing/V2LandingPage.tsx index c97d8fb590..c262d93241 100644 --- a/frontend/src/v2/landing/V2LandingPage.tsx +++ b/frontend/src/v2/landing/V2LandingPage.tsx @@ -35,7 +35,7 @@ const X_HANDLE = 'https://x.com/sam_commonly'; // before install.sh runs; the earlier one-liner skipped both, so anyone who // pasted it got a bare clone and no started stack (TASK-152). const SELF_HOST_COMMAND = 'git clone https://github.com/Team-Commonly/commonly.git && cd commonly && ./install.sh'; -const ADR_COUNT = 32; +const ADR_COUNT = 33; // A count on a marketing page drifts silently: nothing on the page notices a // new ADR, and docs/ is outside this image's build context so the page cannot // count at build time. The TASK-167 row D test counts docs/adr/ADR-*.md and From 69d13ef5d1492b85344b9b460b4d2a251d0841fb Mon Sep 17 00:00:00 2001 From: Lily Shen <115414357+lilyshen0722@users.noreply.github.com> Date: Sun, 1 Nov 2026 19:58:08 -0800 Subject: [PATCH 3/4] docs(adr-034): the repair marker rides the Mongo write; the cutover gate excludes orphans - D3: each write sets `pgPending` in the same Mongo document and clears it after the Postgres write, so a crash between them leaves the marker; a model returns to dual while any document is flagged, restarts included. - Wave 0: the gate is an unscoped report-only run with pending equal to orphanedPending, since orphans stay unstamped by design. - The freeze reads a name only when the whole first argument is the literal: `'User' + suffix` is unreadable, not `User`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015AKgpQ2pr6xRMhN5mcfoHF --- .../unit/models/mongoModelFreeze.test.js | 9 +++++++-- docs/adr/ADR-034-postgres-single-store.md | 17 +++++++++++------ 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/backend/__tests__/unit/models/mongoModelFreeze.test.js b/backend/__tests__/unit/models/mongoModelFreeze.test.js index a2ed32ded8..555aa5d405 100644 --- a/backend/__tests__/unit/models/mongoModelFreeze.test.js +++ b/backend/__tests__/unit/models/mongoModelFreeze.test.js @@ -35,7 +35,8 @@ const MONGO_MODELS = [ // `connection.model(`, `model(\n …`. Each must name its model with a // string literal, or the test cannot know what it registers. const MODEL_CALL = /\bmodel\s*(?:<[^>]*>)?\(/g; -const LITERAL_NAME = /^\s*['"`](\w+)['"`]/; +// The whole first argument must be the literal: `'User' + suffix` is not `User`. +const LITERAL_NAME = /^\s*(['"`])(\w+)\1\s*[,)]/; // Outside models/ any of these is a model defined where the freeze cannot read // it. No space before `(`, so prose like "the model (fallback)" never matches. const DEFINITION = /\bmodel(?:<[^>]*>)?\(|new\s+(?:mongoose\.)?Schema\s*(?:<[^>]*>)?\(/; @@ -43,7 +44,7 @@ const DEFINITION = /\bmodel(?:<[^>]*>)?\(|new\s+(?:mongoose\.)?Schema\s*(?:<[^>] // One entry per model call: the name it registers, or null when it is not a literal. const registrationsIn = (source) => [...source.matchAll(MODEL_CALL)].map((call) => { const name = LITERAL_NAME.exec(source.slice(call.index + call[0].length)); - return name ? name[1] : null; + return name ? name[2] : null; }); const isSource = (file) => /\.(ts|js)$/.test(file) && !file.endsWith('.d.ts'); @@ -71,6 +72,10 @@ describe('Mongo model freeze (ADR-034 D4)', () => { expect(registrationsIn("conn.model('D', s)")).toEqual(['D']); expect(registrationsIn("(mongoose.models.E as Model) || model('E', s)")).toEqual(['E']); expect(registrationsIn('mongoose.model(NAME, s)')).toEqual([null]); + expect(registrationsIn("mongoose.model('User' + suffix, s)")).toEqual([null]); + // eslint-disable-next-line no-template-curly-in-string -- the fixture is source text + expect(registrationsIn('mongoose.model(`User${suffix}`, s)')).toEqual([null]); + expect(registrationsIn("mongoose.model('G')")).toEqual(['G']); ['mongoose.model(NAME, s)', 'model(`F`, s)', 'new Schema({})', 'new mongoose.Schema({})'] .forEach((source) => expect(DEFINITION.test(source)).toBe(true)); expect(DEFINITION.test('// fall back to the default model (no override).')).toBe(false); diff --git a/docs/adr/ADR-034-postgres-single-store.md b/docs/adr/ADR-034-postgres-single-store.md index 950a67bf71..71a68d2b1c 100644 --- a/docs/adr/ADR-034-postgres-single-store.md +++ b/docs/adr/ADR-034-postgres-single-store.md @@ -81,10 +81,14 @@ boundary holds. | 4. Drop | Mongo writes stop, and the Mongo code is deleted one release later. | Before deletion: mode to `dual` plus a reverse backfill. After: restore from backup. | **Mongo stays the system of record until step 4.** In `dual` and `pg-read`, a write commits to Mongo -first and is acknowledged only once it has; the Postgres write follows. A Postgres write that fails is -recorded for repair, re-copied by the backfill, and counted as a mismatch, and in `pg-read` it sends -that model back to `dual` until the repair has run. So rolling back from `pg-read` to `dual` never loses -an acknowledged write: Mongo has every one of them. +first and is acknowledged only once it has; the Postgres write follows. **The repair marker travels in +the same Mongo write:** the document carries a `pgPending` flag set by that write (one document, so one +atomic write), and the flag is cleared only after the Postgres write succeeds. A crash between the two +leaves the flag set, so nothing depends on recording the failure after the fact. A sparse index on +`pgPending` makes the repair a cheap scan: it re-copies each flagged document (idempotently) and clears +the flag. A failed Postgres write counts as a mismatch, and a model in `pg-read` goes back to `dual` while +any of its documents are flagged, including after a restart, until the repair finds none. So rolling back +from `pg-read` to `dual` never loses an acknowledged write: Mongo has every one of them. Step 4 is the only one-way door, and it is taken per model. **A model reaches step 3 when the `commonly verify` scenarios pass against both stores and the compare log shows zero unexplained @@ -111,8 +115,9 @@ can move in an ordinary PR. without Postgres refuses to boot instead of running degraded, and Mongo `Message` keeps only the history the backfill copies. Message reads come from Postgres alone once `PG_HOST` is set, so an instance moving off that mode would hide its history until it is copied. The step is done on an instance only when -`scripts/backfill-local-messages-to-pg.ts` reports zero pending rows (rows whose pod is gone are -reported as orphaned and stay in Mongo). The release that removes the mode says so in its upgrade +a report-only run of `scripts/backfill-local-messages-to-pg.ts`, without `--since` so no older history +is out of scope, shows `pending` equal to `orphanedPending`. That means every pending row left belongs to a +deleted pod and stays in Mongo by design. The release that removes the mode says so in its upgrade note, and boot logs the pending count, so an instance that skipped the backfill shows. Move the three self-creating tables into numbered migrations. Build the dual-store helper (D3's mode, write-both, sampled compare), a shared expiry sweeper for TTL models, and a jest helper on real Postgres for anything with claims or SQL aggregates (`ToolCall.ts` already records that `pg-mem` From 429573503bdd531c8e7bf66c9f119d82f2d57a9d Mon Sep 17 00:00:00 2001 From: Lily Shen <115414357+lilyshen0722@users.noreply.github.com> Date: Sun, 1 Nov 2026 20:04:47 -0800 Subject: [PATCH 4/4] docs(adr-034): versioned repair markers, two-phase deletes, backfill with the backend stopped Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015AKgpQ2pr6xRMhN5mcfoHF --- docs/adr/ADR-034-postgres-single-store.md | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/docs/adr/ADR-034-postgres-single-store.md b/docs/adr/ADR-034-postgres-single-store.md index 71a68d2b1c..6deed77d0b 100644 --- a/docs/adr/ADR-034-postgres-single-store.md +++ b/docs/adr/ADR-034-postgres-single-store.md @@ -82,11 +82,16 @@ boundary holds. **Mongo stays the system of record until step 4.** In `dual` and `pg-read`, a write commits to Mongo first and is acknowledged only once it has; the Postgres write follows. **The repair marker travels in -the same Mongo write:** the document carries a `pgPending` flag set by that write (one document, so one -atomic write), and the flag is cleared only after the Postgres write succeeds. A crash between the two -leaves the flag set, so nothing depends on recording the failure after the fact. A sparse index on -`pgPending` makes the repair a cheap scan: it re-copies each flagged document (idempotently) and clears -the flag. A failed Postgres write counts as a mismatch, and a model in `pg-read` goes back to `dual` while +the same Mongo write:** each write bumps a per-document version and sets `pgPending` to that version +(one document, so one atomic write). After the Postgres write succeeds, the marker is cleared with a +conditional update that matches that version, so an earlier write finishing late can never clear a later +write's marker. A crash between the two leaves the marker set, so nothing depends on recording the +failure after the fact. **A delete is two-phase:** it first marks the document deleted and pending in +Mongo, then deletes the Postgres row, and only then removes the Mongo document. A delete that crashes +halfway is therefore still a flagged document. A sparse index on `pgPending` makes the repair a cheap +scan: it re-copies each flagged document, or deletes its Postgres row if it is marked deleted, then +clears the marker the same conditional way. The dual-store helper's tests cover two writes interleaving, +and a delete crashing at each step. A failed Postgres write counts as a mismatch, and a model in `pg-read` goes back to `dual` while any of its documents are flagged, including after a restart, until the repair finds none. So rolling back from `pg-read` to `dual` never loses an acknowledged write: Mongo has every one of them. @@ -114,8 +119,10 @@ can move in an ordinary PR. **Wave 0, what is left.** Make Postgres required: remove the no-`PG_HOST` message mode, so an instance without Postgres refuses to boot instead of running degraded, and Mongo `Message` keeps only the history the backfill copies. Message reads come from Postgres alone once `PG_HOST` is set, so an instance moving -off that mode would hide its history until it is copied. The step is done on an instance only when -a report-only run of `scripts/backfill-local-messages-to-pg.ts`, without `--since` so no older history +off that mode would hide its history until it is copied. The backfill runs with the backend stopped, after one boot with `PG_HOST` has applied +the migrations (the script does not create tables), so no write or delete lands in Mongo mid-copy; a +self-host upgrade can take that window. The step is done +on an instance only when a report-only run of `scripts/backfill-local-messages-to-pg.ts`, without `--since` so no older history is out of scope, shows `pending` equal to `orphanedPending`. That means every pending row left belongs to a deleted pod and stays in Mongo by design. The release that removes the mode says so in its upgrade note, and boot logs the pending count, so an instance that skipped the backfill shows. Move the three self-creating tables into numbered migrations. Build the dual-store helper (D3's mode,