Repository navigation
refactor(db): default to PostgreSQL and refuse SQLite at boot (#4175) - #4233
Conversation
First slice of the SQLite removal. All compose files run a bundled postgres service by default and require POSTGRES_PASSWORD. Backend and scheduler images refuse to start on SQLite unless both TRINITY_ALLOW_SQLITE=1 and an empty DATABASE_URL are set. A PostgreSQL with no users beside a trinity.db holding data is always refused. `python -m db.sqlite_to_postgres` moves an install out of the refused state: it snapshots the file, brings it to the current schema, builds PostgreSQL through Alembic, copies the rows and verifies counts and sequences. start.sh makes the same check before pulling images. install.sh generates the password and waits for a healthy backend. A % in the database password no longer breaks Alembic's config. Refs #4175 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The dev scheduler waits on a healthy backend, and compose aborts `up` when the dependency has no healthcheck. Add one, plus a guard over all three compose files. Refs #4175 Co-Authored-By: Claude Opus 5.5 <[email protected]>
/review report at
|
| #4175 acceptance criterion | Status |
|---|---|
| Fresh install runs on PostgreSQL, no SQLite file | Done |
| Existing install refused, never comes up on an empty DB | Partial: the image refuses; see I1 for a stale image |
| Migration path documented and tested | Partial: see C1, C2 |
| No SQLite runner or dual-track | Not done: later phase |
| #1279 closed | Not done: later phase |
Execution coverage
Run on Python 3.13 against a throwaway postgres:16-alpine.
| Changed path | Executed by | Verdict |
|---|---|---|
refuse_sqlite_backend |
3 tests red when removed | Executed |
refuse_empty_postgres_beside_sqlite |
3 tests red when removed | Executed |
| Scheduler refusal | 1 test red when removed | Executed |
sqlite_to_postgres |
Separate reviewer run: 95 tables copied, then boot passed with TRINITY_REQUIRE_POSTGRES=1 |
Executed |
ensure_database after a copy |
No test covers this state | Gap: C1 |
env.py % escape |
No test: reverting it left all tests green | Gap: I5 |
| Dockerfile and compose pins | Source-text tests | Guard |
Critical
C1. start.sh refuses again after a successful copy (confidence 10)
scripts/deploy/start.sh:1503, ensure_database:
if [ "$url_set" = "1" ] || [ "$has_sqlite" = "1" ]; thenThe check never looks at PostgreSQL. The guide removes DATABASE_URL= and keeps trinity.db, so has_sqlite=1 still holds after the copy.
Reproduced by running the PR's real function with docker and the .env helpers stubbed, in that post-copy state. It exits 1 with "This install has a SQLite database. Copy it to PostgreSQL... then re-run this script".
- Following that message re-runs the copy, which exits 4 because the target is populated.
- Guide step 3 names
start.sh, and the tool prints "Keeptrinity.db", so the documented path loops. - Hosted
update.shgoes throughstart.sh, so it fails the same way until the file is moved.
Fix options (a design choice):
- Have the tool write a marker file beside the database for
start.shto honour. - Or add a guide step that sets a full
DATABASE_URL; the early return[ -z "$url" ] || return 0then passes.
Either way, add the post-copy case to test_3159_hosted_postgres.py.
C2. The printed copy command can run on an image that lacks the tool (confidence 8; from reading the code, not run end to end)
scripts/deploy/start.sh:1552, scripts/deploy/update.sh:757-764, and the guide's "Migrating an existing deployment".
start.sh refuses at :1573, before compose pull at :1648. Hosted images default to trinity-backend:${TRINITY_IMAGE_TAG:-latest}, and docker compose run uses a cached image by default. The guide has no pull or build step. A hosted install on cached latest, or a prod install with its old local build, should fail with No module named db.sqlite_to_postgres.
Hosted update.sh makes this worse: when start.sh fails, it restores the old checkout and the old tag, and the operator then runs the printed command from the old tree.
The PR's verification used a freshly built image, so it wouldn't catch this.
Fix:
- Print and document
compose pull backend(hosted) orcompose build backend(prod) before therun. - State how a hosted install gets onto this release, given that
update.shrolls back.
Informational
- I1. An old image with the new compose bypasses the refusal (confidence 6; not run). With
POSTGRES_PASSWORDset and no rebuild, an old image has no refusal code and sees the default PostgreSQL URL. It can seed an empty database, and once a user exists there the new refusal passes for good. C2's pull/build step narrows this. - I2. Rowcounts are verified after the commit (confidence 9). In
sqlite_to_postgres.py,pg.commit()at:243runs before the check at:245. On exit 2 the data stays committed, a re-run exits 4, and the backend boots past the refusal. This contradicts the guide's "nothing is committed". Moving the check before the commit fixes it, though a mismatch is unlikely in practice. - I3. A NUL byte aborts the copy with no context (confidence 9, reproduced).
ValueError: A string literal cannot contain NUL (0x00) characters.maincatches onlyCopyErrorandpsycopg2.Error, so this is a raw traceback that names no table or row, and it exits 1, which the guide maps to "Fix.env".coercepromises to fail with context. The transaction did roll back and a clean re-run succeeded, but one such value blocks the whole migration. - I4. Guide step 1 fails on an upgraded prod install (confidence 10, reproduced).
compose stophits thePOSTGRES_PASSWORDrender error, and setting the password is step 2, so swap them. The same render error hits devcompose down(reproduced), and devstop.shruns a plaincompose stopthat should fail the same way. The PR flags the render error forupdate.shbut not for these. - I5.
env.py%escape has no test (confidence 10).test_percent_in_password_reaches_alembic_intactonly exercises_config(). - I6. Stale public docs (confidence 10).
docs/user-docs/faq/getting-started.md:112still says a localstart.shinstall runs on SQLite and that existing installs stay on it. This directory is auto-published.- The guide's "See also" still says "optional bundled
postgresprofile". - "Minimum version" names no number, and Remove the SQLite backend: end-of-support passed 2026-09-01 and no issue owns the code removal #4175 asks for one.
- I7. Re-running
install.shcan lock out PostgreSQL (confidence 7). It regenerates.envwith a new password while the old volume stays.start.shguards this case;install.shdoesn't.
Low confidence
prepare_snapshotruns only the OSS migrations, so a pending enterprise SQLite migration or backfill is skipped. The enterprise side wasn't read. (5)- Each failed copy leaves another full
0600snapshot, with no disk check or cleanup. (5) - If SQLite has no users (for example, an unclaimed hosted install), the post-copy boot is refused and a re-run exits 4. From reading the code. (5)
Checked and clean
- Copy schema: all 96 tables on both tracks match, with no column drift or PG-only
NOT NULL. FKs are stripped from PG DDL, so alphabetical copy order is safe. The bytes-to-byteaandjsonbcolumns weren't exercised with real data. - Network:
postgresis ontrinity-platformonly (SEC: Redis has no requirepass — agent containers have unauthenticated full read/write access to platform task queue (AISEC-C1) #589). - Credentials: the URL isn't printed, and snapshots are
0600.%handling is correct by reading. - Compose: the volume name renders as
<project>_postgres-dataunder-pon v5.6.1. Older versions are untested. - Auth and SQL: no new endpoints. Identifiers interpolated into SQL come from the database catalogs.
The copy tool writes trinity.db.copied-to-postgres after a verified copy, and start.sh stops refusing once it exists. The guide keeps trinity.db, so the file alone looped operators back to a copy that exits 4. The refusal and the guide now get this release's image before the copy, since a cached image has no copy command. The guide sets the password before the first compose command, and stop.sh works without it. Rowcounts are checked before the commit, so a mismatch leaves nothing behind. A NUL byte fails with the table and row. A source with no users is refused before PostgreSQL is touched, because the copy would stay refused at boot. Re-running install.sh keeps the existing PostgreSQL password. Refs #4175 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Addressed in
Low confidence:
Re-review, please. 🤖 Generated with Claude Code |
The guard against `compose down` in stop.sh matches lines that start with `docker compose`, so an inline env prefix slips past it. Refs #4175 Co-Authored-By: Claude Opus 5.5 <[email protected]>
AndriiPasternak31
left a comment
There was a problem hiding this comment.
I ran the copy tool and the boot refusals against real inputs: two real SQLite backups (one from October at 156 migrations, one from August at 103 migrations, 1.1 GB) and a throwaway postgres:16-alpine. I also disabled each guard one at a time to see whether the tests catch it. The core holds up: all 36 combinations of DATABASE_URL × TRINITY_ALLOW_SQLITE × SQLite state × PostgreSQL state behave as described, both copies succeed, a cell-by-cell compare of every copied table shows no data loss, and the backend boots on the result. Two things to fix before merge:
1. The data-orphan guard has no test, and without it rows are dropped silently.
db/sqlite_to_postgres.py:184 (if data_orphans:) is the only thing that stops a SQLite table holding rows but absent from PostgreSQL from being skipped. With that branch disabled, copying the October backup on a checkout without the enterprise submodule gives exit 0, Copied and verified 95 tables, and writes trinity.db.copied-to-postgres. But the rows of a populated enterprise table were never copied, because that table does not exist in OSS PostgreSQL. start.sh then treats the install as migrated. All 24 tests in test_4175_sqlite_to_postgres.py still pass, with TEST_POSTGRES_URL set. With the guard in place, the same run correctly exits 3.
A requires_postgres test would pin it: a SQLite table with rows that has no PostgreSQL counterpart, asserting EXIT_SCHEMA and no marker file.
(if populated: at line 208 is in a similar position: disabling it keeps the tests green, because the second-copy test also exits 4 through the primary-key conflict. That is lower risk, since keyed tables are still protected.)
2. The enterprise % bug breaks the copy command, not just a side path.
With the enterprise submodule mounted and a password containing %, python -m db.sqlite_to_postgres fails after the snapshot step with ValueError: invalid interpolation syntax in 'postgresql://trinity:<encoded password>@…'. The traceback prints the URL with the percent-encoded password. Generated hex passwords avoid it, as the description says. But enterprise installs with a password the operator chose are exactly the installs that must run this command to upgrade. Please either fix the enterprise runner in step with this PR (it needs the same .replace("%", "%%") as alembic_runner._config), or state in SQLITE_TO_POSTGRES.md that the copy requires a password without % until it is fixed.
Repro: DATABASE_URL='postgresql://trinity:p%2540ss@…/trinity' with the enterprise submodule present, then python -m db.sqlite_to_postgres.
Not covered by this check: the built images, a full start.sh / install.sh / update.sh run, and Compose versions older than v5.5.1.
… % (#4175) A SQLite table holding rows with no PostgreSQL counterpart now has a test asserting exit 3 and no marker file. A target holding rows that do not conflict with the source has a test asserting exit 4. Each test goes red with its guard disabled. An enterprise module that cannot read a DATABASE_URL containing % now stops the copy with exit 1 and a named action. The configparser message quotes the URL with its password, so the command no longer lets it reach a traceback. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@AndriiPasternak31 both addressed in 1. Copy guards. Two new 2. An enterprise module without that fix now stops the copy with exit 1 and a message that names the action and leaves out the URL. Related local run with PostgreSQL: 92 passed ( |
|
merge-train (2026-11-04): left out of this train because the earlier review verdict was never lifted in the thread. @dolho @AndriiPasternak31, the author reports your findings as addressed in |
/review report at
|
| #4175 acceptance criterion | Status |
|---|---|
| Fresh install runs on PostgreSQL, no SQLite file | Done |
| Existing install refused, never comes up on an empty DB | Done: run on prod compose below |
| Migration path documented and tested | Done, except the gaps in I1 and I2 |
| No SQLite runner or dual-track | Not done: later phase, as declared |
| #1279 closed | Not done: later phase, as declared |
Re-check of the earlier findings
| Finding | Result | How I checked |
|---|---|---|
C1: start.sh refuses after a copy |
Fixed | Removing the marker check from the hosted or dev path turns a test red; the tool wrote the marker in the run below |
| C2: copy command on an image without the tool | Fixed in the message and guide | Printed pull/build step confirmed by running ensure_database. Not run on a real hosted upgrade |
| I1: old image with new compose | Open, as the author stated | The guide states the risk |
| I2: rowcounts checked after commit | Fixed | Mutation red |
| I3: NUL byte | Fixed | Mutation red |
I4: password step order, stop.sh |
Fixed | Mutation red |
I5: env.py % escape |
Fixed | Mutation red |
| I6: stale public docs | Mostly fixed | See I4 below for what remains outside the user docs |
I7: install.sh password |
Fixed | Mutation red |
Copy guards raised in the other review (data_orphans, populated) |
Fixed | Mutation red for each |
% in the private module's URL |
Fails cleanly until Abilityai/trinity-enterprise#1097 merges | Removing the handler turns a test red. That PR is still open |
Execution coverage
Run on the PR merged with current dev, Python 3.13, postgres:16-alpine, with the PostgreSQL-backed tests active: 152 passed across test_4175_*, test_3159, test_2280, test_2528 and test_ent873.
Mutations: 18 of 18 went red, each reverted afterwards: both boot refusals, the scheduler refusal, TRINITY_ALLOW_SQLITE handling, data_orphans, populated, check-before-commit, marker write, sequence reset, no-users guard, NUL guard, both % escapes, the private-module % handler, the hosted and dev marker checks, stop.sh and install.sh.
The source-text tests in this diff pin compose files and Dockerfiles, whose live consumer is CI, so they are guards.
End-to-end upgrade on prod compose
Neither earlier review covered this. The source was a SQLite install built by released main with its pinned enterprise module, so the private tables were in their older shape. It held real rows, and a separate copy-only run with a row in almost every table also exited 0. The target was this PR plus current enterprise main.
| Step | Result |
|---|---|
No POSTGRES_PASSWORD |
Render error naming the guide |
up backend beside SQLite |
Refused with guidance, 0 tables created |
Documented run --rm backend python -m db.sqlite_to_postgres |
Exit 0, 125 tables, marker written, snapshot mode 600 |
up backend |
Healthy in about 12s, enterprise registered, no registration failure |
| Login with the pre-copy admin password | OK; users and agent ownership match the source; next users id is above the max |
| Second copy | Exit 4, refuses to merge; backend healthy after restart |
| Wiped PostgreSQL with the marker still present | Refused, 0 tables created |
| Database password in tool or backend logs | Not found |
Limits of this run:
- It used a recent prebuilt backend image with this branch's source mounted and
TRINITY_REQUIRE_POSTGRES=1set by override, because the embedding model download was unreachable while building. CI'sprod-image-smokecovers the real image. - Backend, PostgreSQL, Redis and Vector only. The scheduler's refusal is unit-tested, not run here.
- Not run: a real hosted
update.sh,install.sh, or Compose older than v5.6.1 (COMPOSE_PROJECT_NAMEin the volume name).
Critical
None.
Informational
None of these block merge. I'd fix I1 here because it's small and every existing hosted SQLite install hits it.
I1. The refusal skips the step an existing hosted install needs (confidence 9, reproduced)
scripts/deploy/start.sh:1560-1566. The previous start.sh --hosted wrote DATABASE_URL= (empty) into .env for an install with trinity.db, so those installs are in exactly this state. The refusal prints pull and run but doesn't say to remove that line, and running the printed command then fails:
COPY FAILED: DATABASE_URL must be a postgresql:// URL
Guide step 2 does cover it, so this is recoverable, but the operator is told to set a URL rather than delete a line. Fix: when url_set=1, print the removal step, and have sqlite_to_postgres.py:291 say that an empty value selects SQLite and the line should be removed.
I2. Private-module data migrations pending at copy time are stranded (confidence 9, reproduced; narrow today)
sqlite_to_postgres.py:137-139 runs only the OSS SQLite migrations on the snapshot, and build_postgres_schema() at :299 runs the Alembic twin on an empty database before copy_data at :301. A data-moving migration therefore does nothing on either track.
I reproduced this with the acceptance move from Abilityai/trinity-enterprise#1107, with its SQLite migration not yet applied. After the copy and a boot, the source table had 1 row and the OSS table had 0, so that person is asked to accept the terms again. Exit code was 0 and nothing was logged.
Reach: that table is not in the released enterprise pin, so released installs are unaffected. It reaches only a SQLite install tracking pre-release enterprise code, or a future data-moving migration landing before SQLite is removed. This turns my earlier low-confidence note into a confirmed one. Fix: run the private SQLite migrations on the snapshot too, or exit non-zero when any are pending.
I3. update.sh can't identify a stopped prod install on PostgreSQL (confidence 7, from reading)
scripts/deploy/update.sh:145. With no backend container, the disk fallback identifies prod by trinity.db, which a fresh prod install no longer has. It stops with "Cannot tell how this install was deployed" and asks for --shape, so it fails safe. Worth a fallback on TRINITY_DATA_PATH or the PostgreSQL volume.
I4. Stale statements left after this flip (confidence 10)
CLAUDE.md:163still says "SQLite (default)". The dual-track requirement stays until a later phase, but the default no longer does.CLAUDE.md:243still says "SQLite persistence".docs/DEPLOYMENT.md:370showsrestore-database.shwith no SQLite-only note, and the script never checksDATABASE_URL. On a PostgreSQL install it would write a file nothing reads.backup-and-restore.mddoes say SQLite only.
Low confidence
- An operator-managed PostgreSQL install now also needs
POSTGRES_PASSWORDand runs an idle bundled container. The guide documents this, but it's worth a release-note line since these installs aren't SQLite. (5) - Each failed copy still leaves a full
0600snapshot, as previously noted. Disk use only. (5)
Checked and clean
- Auth and SQL: no new endpoints. Identifiers interpolated into SQL come from the database catalogs, and values are parameterized.
- Network:
postgresis ontrinity-platformonly (SEC: Redis has no requirepass — agent containers have unauthenticated full read/write access to platform task queue (AISEC-C1) #589) in prod, as in the other files. - Refusal ordering: runs inside the migration lock and before anything is built; confirmed by 0 tables after a refused boot.
- Credentials: URL hidden on the
%path; database password absent from logs in the run above. - Public docs: the enterprise-docs guard pattern has no hits in the added lines.
- Backups:
update-db.pyand the nightly job already handle PostgreSQL.
CI at this head: 22 pass, 6 skipped. e2e is among the skipped.
🤖 Generated with Claude Code
dolho
left a comment
There was a problem hiding this comment.
Approved at 413955af8: no critical findings, and my earlier verdict is lifted. Details in the /review comment above. Don't merge until the dev instance has adopted bundled PostgreSQL (trinity-ops-agent#604) and CI has re-run on a branch updated from dev.
|
merge-train (2026-11-05): not a member tonight, by the PR's own merge-order gate rather than any finding. The |
|
merge-train 2026-11-06, for the owner: the enterprise twin abilityai/trinity-enterprise#1097 (escape |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@AndriiPasternak31 merged as |
|
Regression details (head_sha: `ff2f57dc560c46c05db916a51423cddb06b297d1`)Seed Backend unit-suite regression diffPer-XML totals
❌ New failures introduced by HEAD (1)Tests failing under HEAD that did not fail under BASE in any seed:
Legend: [F] = assertion failure, [E] = collection or fixture error. Reproduce locally: |
… review follow-ups (#4175) (#4312) * fix(db): run enterprise SQLite migrations in the copy and close review follow-ups (#4175) The copy command now applies the private module's SQLite schema and migrations to the snapshot, as a SQLite boot does. Alembic builds the PostgreSQL side on an empty database, so a data-moving migration that was still pending ran on neither track. A module that fails on the snapshot stops the copy with exit 3 and names the module. An install whose .env carries an empty DATABASE_URL= line is told to remove it, in both the start.sh refusal and the copy command. update.sh identifies a stopped prod install from a non-empty data dir, since an install created on PostgreSQL has no trinity.db. CLAUDE.md and DEPLOYMENT.md no longer call SQLite the default, and restore-database.sh is marked SQLite-only. Mutations: removing the snapshot step, or the TRINITY_ALLOW_SQLITE override inside it, turns TestEnterpriseSnapshotMigrations red. The start.sh, copy-command and update.sh changes each turn their new test red when reverted. Co-Authored-By: Claude Opus 5.5 <[email protected]> * merge-train: patch the imported db.alembic_runner module, not the string path, in the percent-password test (#4175) — mechanical, per the merge-train note on the PR Same hunk as #4313: the string-form monkeypatch lands on a stale package attribute after a sibling test pops db.* from sys.modules, and the real runner then runs against the SQLite default URL (the regression diff on fe66432). Identical content on both branches so the two merge cleanly. Co-Authored-By: Claude Fable 5.1 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: trinity-ability <[email protected]>
* docs(planning): TARGET_ARCHITECTURE v3 drift review, Phase 4 status Corrects facts that no longer match dev: PostgreSQL is the default and the images refuse SQLite (#4233), the database driver is synchronous SQLAlchemy over psycopg2, the scheduler job store is in-memory, trigger idempotency uses the idempotency_keys table, and the runtime is pluggable. Open Question 2 is marked resolved. Adds a table of decisions that stand but that the code does not yet honour, and a Proposed Targets section (not adopted, not binding). PULL_MIGRATION_STATUS: Phase 4 (#2532) is merged, not in review. Co-Authored-By: Claude Fable 5.2 <[email protected]> * docs(planning): link the Proposed Targets and gap table to their tracking issues Co-Authored-By: Claude Fable 5.2 <[email protected]> --------- Co-authored-by: trinity-ability <[email protected]> Co-authored-by: Claude Fable 5.2 <[email protected]>
Refs #4175. First slice of the SQLite removal, so this PR does not close the issue. Removing the SQLite runner, the SQLite test tier and #746 are later steps.
Changes
postgresservice by default and requirePOSTGRES_PASSWORD. Prod and hosted acceptTRINITY_POSTGRES_VOLUME, so a standalone install can adopt its existing data without a copy.TRINITY_REQUIRE_POSTGRES=1is set in the Dockerfiles, so unit tiers are unaffected. Staying on SQLite for this release needs bothTRINITY_ALLOW_SQLITE=1and an emptyDATABASE_URL.trinity.dbholding data is always refused. No setting overrides this.python -m db.sqlite_to_postgresmoves an install out of the refused state: snapshot, schema bring-up, Alembic build, row copy, count and sequence checks.start.shmakes the same decision before pulling images.install.shgenerates the password and waits for a healthy backend.%in the database password no longer breaks Alembic's config or prints the URL.Merge order
Merging breaks
deploy-devuntil thedevinstance has adopted bundled PostgreSQL, because prod compose stops at thePOSTGRES_PASSWORDrender error. Adoptdevfrom this branch first (trinity-ops-agent#604).Behaviour to review
update.shaborts before touching containers in that case. A default password would break the no-default-credential rule, so this is deliberate.update.shdoes not run the SQLite check itself. A SQLite host that already hasPOSTGRES_PASSWORDset reaches the backend refusal at boot, then the update's failed health check.scripts/deploy/gcp-deploy.shis unchanged. Its generated.envalready lacks the required Redis passwords, so prod compose does not render from it today.Verification
Not verified
/verify-local: the local dev stack's container names collide, andverify-localneeds a postgres entry in the private.clauderepo. CI covers boot throughstart.sh.COMPOSE_PROJECT_NAMEin the volume name works on v5.5.1.Follow-ups
%bug, which prints the password in a traceback. Generated hex passwords do not trigger it.verify-localpostgres entry.🤖 Generated with Claude Code