~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
docs: correct major-release rollback guidance (#6925)
LearningCircuit1ae8e8c2c0cb
diff --git a/README.md b/README.mdindex 4b2de0f0f8..659b8daa2a 100644--- a/README.md+++ b/README.md@@ -465,6 +465,17 @@ search(query="agentic research frameworks", engine="github")## 🔄 Upgrading from Earlier Versions+For the first FastAPI-based major release, read the+[upgrade and rollback guide](docs/deployment/upgrading.md) before updating.+Back up the data first: the release's new database revisions prevent a+direct rollback to v1.10.7 against the upgraded databases. Copy each user's+automatic pre-migration backup from `encrypted_databases/backups/` to storage+outside the data directory immediately after that user's first sign-in on the+new release, and in any case before any downgrade attempt: a login backup on+a later UTC day or a password change replaces it with a copy of the upgraded+database. Never start v1.10.7 against the upgraded databases: each sign-in+attempt there also replaces that backup.+- **`llm.model` no longer has a default.** Pre-1.6.3 installs auto-filled `gemma3:12b` (Ollama) when no model was configured, which silently downloaded a multi-GB binary. The field is now empty by default — pick a model in Settings → LLM, or research will fail loudly with a clear error.- **The `auto` and `parallel` meta search engines were removed.** The default langgraph-agent strategy selects engines dynamically per query, which replaces them. Stored settings are migrated automatically (removed values become `searxng`); update any explicit `search_tool="auto"` API calls or `LDR_SEARCH_TOOL=auto` env overrides to a concrete engine such as `searxng`.- **The `llamacpp` provider now uses HTTP instead of in-process loading.** If you previously set `llm.llamacpp_model_path` to a local `.gguf` file, that setting is no longer read. Instead, run `llama-server -m <your-model.gguf>` (it ships with every modern llama.cpp build) and the default `llm.llamacpp.url` of `http://localhost:8080/v1` will pick it up. Optional API key support is available via `llm.llamacpp.api_key` if you put `llama-server` behind an auth proxy.diff --git a/changelog.d/3299.breaking.md b/changelog.d/3299.breaking.mdindex d5cd57436e..51c0a1a3ef 100644--- a/changelog.d/3299.breaking.md+++ b/changelog.d/3299.breaking.md@@ -1,5 +1,9 @@**LDR's web layer now runs on FastAPI and Uvicorn instead of Flask's WSGI-stack.** This release adds no database schema migration, but operators and+stack.** The web-layer change itself adds no database schema migration, but+the release also ships data-repair database revisions newer than `0030`, the+newest revision v1.10.7 recognizes, so take a verified offline backup before+upgrading. See the [upgrade and rollback guide](https://github.com/LearningCircuit/local-deep-research/blob/main/docs/deployment/upgrading.md),+which also shows how to find the release's newest revision. Operators andcustom API clients should prepare for these compatibility changes:- **Deployments where a trusted reverse proxy terminates TLS must set@@ -66,11 +70,30 @@ custom API clients should prepare for these compatibility changes:- **Uvicorn allows at most 10 seconds for in-flight requests to finish duringgraceful shutdown.** Long-lived streams may then be closed.-**Rollback:** Deploy an image from the last Flask-based release, or build that-release with its own lockfile. No schema downgrade is required. Rolling back-requires users to sign in again. Restore custom Socket.IO clients and-reverse-proxy rules to `/socket.io`; if you adopted `RATE_LIMIT_STORAGE_URI`,-also restore or retain `RATELIMIT_STORAGE_URL` with the same value, which the+**Rollback:** Never start v1.10.7 against the upgraded databases. Each+sign-in it attempts there makes a forced backup that keeps one file per user,+which replaces the user's automatic pre-migration backup with a copy of the+upgraded database, and then fails migration-version lookup. The new release+does not keep that pre-migration backup either: with the default+`backup.max_count` of 1, the user's login backup on a later UTC day replaces+it with a copy of the upgraded database, and a password change deletes it.+Copy each user's pre-migration backup from `encrypted_databases/backups/` to+storage outside the data directory immediately after that user's first+sign-in on the new release, and in any case before any downgrade attempt.+Raising `backup.max_count` and `backup.max_age_days` before upgrading only+delays the replacement: the user's first sign-in on the+`backup.max_count`-th later UTC day on which they sign in still deletes it,+as does the first login backup after it is older than+`backup.max_age_days`, whichever comes first, and a password change deletes+it at any time. To roll back, stop the upgraded application, restore+the matching pre-upgrade data backup and deploy the previous image or package+with its own configuration and lockfile. The new revisions' downgrades do not undo their data repairs (for example, `0031`+does not restore discarded duplicate setting rows or the original values of+repaired settings), so they are not a data-restore operation. A backup+restore also omits writes made after that backup. Rolling back requires users+to sign in again. Restore custom Socket.IO clients and reverse-proxy rules to+`/socket.io`; if you adopted `RATE_LIMIT_STORAGE_URI`, also restore or retain+`RATELIMIT_STORAGE_URL` with the same value, which theFlask release reads.`TRUST_PROXY_HEADERS` can remain set, but the Flask release ignores it; keepthe same reverse-proxy isolation and direct-access controls in place. As withdiff --git a/docs/MIGRATION_GUIDE_v1.md b/docs/MIGRATION_GUIDE_v1.mdindex dc321c743c..0dccc70ac5 100644--- a/docs/MIGRATION_GUIDE_v1.md+++ b/docs/MIGRATION_GUIDE_v1.md@@ -259,8 +259,10 @@ The server has migrated from Flask + Werkzeug to FastAPI + uvicorn.The sections below highlight the changes most likely to affect an interactiveuser. They are not the complete operator checklist, and several are permanentcontract changes rather than one-time upgrade effects. Before upgrading, read+the [upgrade and rollback guide](deployment/upgrading.md) for the backup,+verification and rollback procedure, and[`changelog.d/3299.breaking.md`](../changelog.d/3299.breaking.md) for the full-list, client/API migration details, and rollback procedure.+list and client/API migration details.### You will need to log in againdiff --git a/docs/deployment/reverse-proxy.md b/docs/deployment/reverse-proxy.mdindex 1462698418..0a202aac0b 100644--- a/docs/deployment/reverse-proxy.md+++ b/docs/deployment/reverse-proxy.md@@ -205,6 +205,26 @@ locally-trusted internal CA (browsers warn unless you trust its root).- **Single backend only.** LDR doesn't support horizontal scaling — multiplereplicas would need Socket.IO sticky sessions and a shared message queue.+- **Rate-limit storage.** LDR keeps its HTTP rate-limit counters, including+ the per-client limit on login requests, in process memory by default, so a+ restart resets them and separate processes do not share them. Set+ `RATE_LIMIT_STORAGE_URI` to a+ [`limits` storage URI](https://limits.readthedocs.io/en/stable/storage.html)+ such as `redis://redis-host:6379` to keep these counters in a shared backend+ that survives restarts. The separate per-account lockout after repeated+ failed passwords stays in process memory either way. Install that backend's+ client package yourself (`redis` is not an LDR dependency); if it is+ missing, startup fails with an error that names the variable. That error+ and the logs can include the storage URI, and LDR's redaction of+ credentials in it is best-effort, so do not rely on it to hide a password:+ keep the URI free of secrets you would not want in a log, or give the+ backend its credentials another way.+ `RATELIMIT_STORAGE_URL`, the name the Flask-based releases read, still works+ when `RATE_LIMIT_STORAGE_URI` is unset. Both are ignored when rate limiting+ is disabled. Set them in the process environment, not in a `.env` file:+ the rate limiter's library also reads `RATELIMIT_STORAGE_URL` from a `.env`+ file in the working directory, which LDR does not treat as a source of its+ own settings.- **Lock down registration** if you expose LDR publicly: it ships its own auth,but `LDR_APP_ALLOW_REGISTRATIONS` defaults to **true** (open self-signup). Set`LDR_APP_ALLOW_REGISTRATIONS=false` after creating your accounts. Proxy-leveldiff --git a/docs/deployment/upgrading.md b/docs/deployment/upgrading.mdnew file mode 100644index 0000000000..67714fa13d--- /dev/null+++ b/docs/deployment/upgrading.md@@ -0,0 +1,197 @@+# Upgrading to the first FastAPI-based major release++This guide covers upgrades from v1.10.7 to the first FastAPI-based major+release. The web-layer change itself adds no database schema migration, but+the release also ships database revisions newer than `0030`, the newest+revision v1.10.7 knows. Prepare a matching application and data backup before+upgrading; deploying the old image alone is not a working rollback.++To find the release's newest database revision, run this with the installed+release (inside its container for Docker deployments):++```bash+python -c "from local_deep_research.database.alembic_runner import get_head_revision; print(get_head_revision())"+```++Or list the migration files in the release's wheel; the newest revision is the+highest-numbered file:++```bash+unzip -l local_deep_research-*.whl | grep 'database/migrations/versions/0'+```++## Before upgrading++1. Record the installed package version or image digest and retain its+ deployment configuration. Use the selected release's dependencies when+ upgrading or rolling back; a newer lockfile does not describe the old release.+2. Let active research and indexing jobs finish, then stop the application+ and allow its shutdown to complete.+3. Take an offline backup of the complete configured LDR data directory,+ including databases and configuration, plus any separately configured+ document or vector storage. Verify that a copy can be restored before+ changing the production data. Each user database is encrypted with that+ user's password, which LDR does not store, so a restored copy opens only+ with the password the user had when it was taken. Tell users to keep+ their current passwords until a rollback is no longer possible; do not+ collect users' passwords yourself.+4. Review the release's compatibility notes and your reverse-proxy setup.+ Socket.IO now uses `/ws/socket.io`. A trusted TLS-terminating proxy requires+ `TRUST_PROXY_HEADERS=true` and must be the only way to reach the backend.+ Follow the [reverse-proxy guide](reverse-proxy.md), including its header+ overwrite and single-proxy requirements.++## Upgrade and verify++Install the selected release and start one application process against the+intended data directory. Users must sign in again after the restart.+Per-user database migrations run when those databases are opened; an+application health response alone does not verify every user's upgrade.++The revisions after `0030` repair existing data. For example, revision `0031`+repairs an allowlisted set of corrupted legacy settings, deduplicates setting+keys and restores their unique index. Its downgrade is intentionally a no-op:+it cannot reconstruct discarded rows or original values. Treat every revision+after `0030` as one-way and roll back from a backup. A data migration matters+for rollback even when no new application table is added.++Before reopening the service to users, verify on the upgraded installation:++- Sign-in and a representative settings save succeed.+- Existing research reports and uploaded documents remain readable.+- A new research run reaches completion with the configured model and search+ provider; progress still updates after reconnecting.+- Existing collection searches return results, and an indexing operation+ completes with the configured embedding provider.+- Shutdown completes and the same data remains usable after restarting.++Review the release notes for custom API-client changes, including the removed+legacy news routes and CSRF requirements. See the+[configuration reference](../CONFIGURATION.md) for current settings.++### Automatic pre-migration backups++When the new release opens a user database that needs migration, normally at+that user's first sign-in after the upgrade, it first tries to write an+encrypted copy of that database to the user's+[automatic backup directory](../security/database-backup.md),+`encrypted_databases/backups/<user hash>/` under the data directory. Only+users whose databases the new release has opened have such a backup. It is+encrypted with that user's password at the time of the upgrade. Do not rely+on it in place of the offline backup.++A failed pre-migration backup does not stop the migration. If the copy+cannot be made, for example because free space in the backup directory is+less than twice the database's size or the copy fails its integrity check,+the release logs a `Pre-migration backup failed` line and migrates the+database anyway. Look for that line after each user's first sign-in.+Treat a user with no `Pre-migration backup created` line for that sign-in+as having no pre-migration backup, and rely on the offline backup for that+user's rollback.++This pre-migration backup is not durable. Writing it removes the user's+older automatic backups, and later events replace or delete it. A sign-in+adds a login backup only when the user has no backup dated the current UTC+day, so only the first sign-in on each later UTC day adds one; further+sign-ins that day add nothing.++- With the default `backup.max_count` of `1`, the first login backup made on+ a later UTC day replaces it with a copy of the upgraded database. A+ sign-in shortly after midnight UTC can do this minutes after the upgrade.+- With that default, the first sign-in itself does this if it runs past+ midnight UTC: the pre-migration backup is named for the time its export+ started, and that sign-in's own login backup, made after the migration,+ then falls on a later UTC day. On a large database the export and+ migration can take minutes. After each user's first sign-in, check that the file named in+ that user's `Pre-migration backup created` log line still exists; if it+ does not, the pre-migration backup is already gone and the offline backup+ is the only rollback source for that user.+- With a higher `backup.max_count` of N, each of those login backups is+ added and only the newest N files are kept. Whichever comes first deletes+ the pre-migration backup: the Nth login backup made after it, which is+ the user's first sign-in on the Nth later UTC day on which they sign in,+ however young the backup is, or the first login backup made after it is+ older than `backup.max_age_days` (default `7`).+- A password change deletes all of that user's backups, this one included,+ and writes a new backup of the upgraded database.++After any of these, restoring from `encrypted_databases/backups/` restores+the upgraded database, not the pre-migration one, and v1.10.7 refuses it.++Copy the pre-migration backups out immediately. Each user's backup is+created at that user's own first sign-in, so there is no single moment that+covers everyone: copy each user's backup directory to storage outside the data+directory immediately after that user's first sign-in on the new release,+before their first sign-in on a later UTC day and before any password change.++Raising `backup.max_count` and `backup.max_age_days` before upgrading, for+example with the `LDR_BACKUP_MAX_COUNT` and `LDR_BACKUP_MAX_AGE_DAYS`+environment variables, only widens that window. The pre-migration backup+then survives until the user's first sign-in on the+`backup.max_count`-th later UTC day on which they sign in, or until the+first login backup after it is older than `backup.max_age_days`, whichever+comes first, and a password change still deletes it at any time. With+`LDR_BACKUP_MAX_COUNT=5`, a user who signs in daily loses it on the fifth+day after the upgrade even if `backup.max_age_days` is `90`; signing in+several times a day does not bring that forward. It is not a substitute for+copying the backups out.++Protect the copies you take, and the offline backup, as you protect the+data directory. Each copy opens with the password its user had when it was+taken, and keeps doing so after the user changes that password. LDR deletes+a user's automatic backups on a password change for that reason, but it+cannot reach copies made outside the data directory. Restrict access to+them, destroy them once a rollback to v1.10.7 is no longer needed, and+destroy a user's copies at once if that user changes a password because it+may have been compromised. The offline backup has the same exposure, and+that user's rollback then relies on it alone.++Backup file names start with their UTC creation time+(`ldr_backup_YYYYMMDD_HHMMSS`), and the log records each+`Pre-migration backup created` path. A backup created before the upgrade is+not a pre-migration backup, and one created at a later sign-in on the new+release is a copy of the upgraded database.++## Rollback++Never start v1.10.7 against the upgraded data directory. v1.10.7 knows+revisions only through `0030`. Each sign-in with the correct password against+a database stamped with a newer revision first makes a forced backup and keeps+only the newest backup file for that user. That replaces the user's automatic+pre-migration backup with a copy of the upgraded database. Then v1.10.7+refuses the login with `Can't locate revision identified by '<revision>'`.++1. Stop the upgraded application.+2. Before any downgrade attempt, copy every user's backups from+ `encrypted_databases/backups/` to storage outside the data directory, if+ you have not already copied the pre-migration backups. Preserve the+ upgraded data separately as well if post-upgrade work needs later+ recovery.+3. Restore the verified pre-upgrade offline backup. If you have none, restore+ each migrated user's database from the pre-migration backup you copied+ out after the upgrade; see the+ [database backup guide](../security/database-backup.md). A user whose+ first sign-in logged `Pre-migration backup failed`, or no+ `Pre-migration backup created` line, has no pre-migration backup to+ restore from.+ Check each file's timestamp first: a backup taken now from+ `encrypted_databases/backups/` is a copy of the upgraded database if a+ later daily backup or a password change has replaced the pre-migration+ one, and v1.10.7 refuses it. A database the new release never opened was+ not migrated and needs no restore. Accounts created on the new release+ have no pre-upgrade copy: the offline backup does not contain them, and+ v1.10.7 refuses their databases, which the new release created at its+ newest revision. Export anything those users need before rolling back.+ After the restore, each user signs in with the password they had when+ the restored copy was taken.+4. Deploy the matching previous application version and configuration.++Do not run the old and new versions against the same writable data directory.+Work saved after the backup will not be present in that restored copy.+Manually changing the revision marker or invoking the no-op downgrades does+not restore the previous data; use the backup for this rollback procedure.++Restore custom Socket.IO clients and proxy rules to `/socket.io`. If you adopted+`RATE_LIMIT_STORAGE_URI`, also restore or retain `RATELIMIT_STORAGE_URL` for the+old release. Keep the backend isolated behind the proxy. Users must sign in+again, and interrupted work may need to be restarted.diff --git a/docs/security/database-backup.md b/docs/security/database-backup.mdindex 194d8560ef..6a7800504c 100644--- a/docs/security/database-backup.md+++ b/docs/security/database-backup.md@@ -8,7 +8,7 @@ Local Deep Research includes an automatic database backup system that creates en- **Encrypted**: Backups use the same encryption as your main database- **Safe**: Uses SQLCipher's `sqlcipher_export()` for atomic backups that work correctly with WAL mode- **Configurable**: Enable/disable and configure retention via settings-- **Pre-migration**: A backup is automatically created before any database schema migration+- **Pre-migration**: A backup is automatically attempted before any database schema migration## How It Works@@ -17,7 +17,7 @@ Local Deep Research includes an automatic database backup system that creates en3. The backup runs in a separate thread (non-blocking)4. Uses `sqlcipher_export()` to create an encrypted copy preserving all cipher settings5. Old backups are automatically cleaned up based on your retention settings-6. Before database migrations, a backup is always created regardless of the daily limit+6. Before database migrations, a backup is always attempted regardless of the daily limit. If it fails, the log shows `Pre-migration backup failed` and the migration runs anyway. A pre-migration backup that was made is not kept: with the default **Max Backups** of `1`, the login backup on a later UTC day replaces it with a copy of the migrated database, and a password change deletes it. Copy it out of the backup directory if you may need to roll back; see the [upgrade and rollback guide](../deployment/upgrading.md#automatic-pre-migration-backups)## Backup Locationdiff --git a/tests/database/test_migration_chain_integrity.py b/tests/database/test_migration_chain_integrity.pyindex bf581613d0..134f326950 100644--- a/tests/database/test_migration_chain_integrity.py+++ b/tests/database/test_migration_chain_integrity.py@@ -1,8 +1,10 @@"""Schema-integrity guards for #3299 that no other test file holds.#3299 is a Flask -> FastAPI port that claims, in-``changelog.d/3299.breaking.md``, that it adds no schema change and can-therefore be rolled back. ``test_upgrade_from_pre_migration_install.py``+``changelog.d/3299.breaking.md``, that "the web-layer change itself adds no+database schema migration". (The release that ships it also carries later+data-repair revisions, which is why that fragment's rollback section requires+a data backup.) ``test_upgrade_from_pre_migration_install.py``already turns the *directory* form of that claim into assertions(``test_the_3299_port_added_or_edited_no_migration_revision``,``test_the_3299_port_changed_no_orm_model``, and the generalised@@ -37,10 +39,11 @@ What is left uncovered, and is what this file asserts:works: it is not a frozen 2025 DDL script, it calls``Base.metadata.create_all()``. So the baseline every fresh installreceives is whatever the model files say **today**, while an existing- user who upgrades receives only revisions ``0002..0030``. Edit a model+ user who upgrades receives only the revisions after ``0001``. Edit a modelwithout a migration and the two populations silently diverge -- freshinstalls get the new column, upgraders do not, and the changelog's- claim that the release "adds no database schema migration" becomes+ claim that "the web-layer change itself adds no database schema+ migration" becomesfalse for exactly one of them.Tests here derive the guarded file set *from the live metadata*, sothe guard cannot drift away from the schema again.@@ -112,10 +115,9 @@ from tests.database.schema_snapshot import model_edits_preserve_schemaREPO_ROOT = Path(__file__).resolve().parents[2]-# The commit that merged #3299. ``changelog.d/3299.breaking.md`` says that-# release "adds no database schema migration" and that "No schema-# downgrade is required" to roll it back -- a claim about THIS commit and-# nothing else, so it is re-verified against this commit's own range+# The commit that merged #3299. ``changelog.d/3299.breaking.md`` says "the+# web-layer change itself adds no database schema migration" -- a claim+# about THIS commit and nothing else, so it is re-verified against this commit's own range# rather than against whatever branch happens to be building.PORT_3299_COMMIT = "fb4e33b8d8cba4d62c70cc2704007765ad9f6293"DATABASE_PKG = REPO_ROOT / "src" / "local_deep_research" / "database"@@ -926,11 +928,10 @@ def test_only_files_alembic_can_load_as_revisions_count_as_revisions():def test_the_3299_port_changed_no_file_behind_the_alembic_metadata():- """The rollback claim, re-verified at the commit that made it.+ """The no-migration claim, re-verified at the commit that made it.- ``changelog.d/3299.breaking.md`` says that release "adds no database- schema migration" and that rolling it back needs no schema downgrade.- That is a fact about one merge commit, so it is checked against that+ ``changelog.d/3299.breaking.md`` says "the web-layer change itself adds+ no database schema migration". That is a fact about one merge commit, so it is checked against thatcommit's own range -- which keeps it verifiable forever AND keeps itfrom misfiring on every later branch, which the generalised rulebelow governs instead.@@ -970,10 +971,10 @@ def test_the_3299_port_changed_no_file_behind_the_alembic_metadata():assert changes == {"added": [], "removed": [], "edited": []}, (f"#3299 ({PORT_3299_COMMIT[:12]}) DID change the schema its "f"changelog says it does not touch: {changes}. Either the commit "- "sha above is wrong, or changelog.d/3299.breaking.md is false -- "- "both its 'adds no database schema migration' sentence and the "- "rollback section's 'No schema downgrade is required' -- and must "- "be rewritten to describe the downgrade an operator has to run."+ "sha above is wrong, or changelog.d/3299.breaking.md's 'The "+ "web-layer change itself adds no database schema migration' "+ "sentence is false and must be rewritten to describe that "+ "migration and its rollback.")diff --git a/tests/database/test_upgrade_from_pre_migration_install.py b/tests/database/test_upgrade_from_pre_migration_install.pyindex d7d20dd1ac..1feb9278b3 100644--- a/tests/database/test_upgrade_from_pre_migration_install.py+++ b/tests/database/test_upgrade_from_pre_migration_install.py@@ -8,16 +8,15 @@ rest of the PR's ~900 changed files are covered by behavioural tests of thenew web layer; this file covers the one thing those cannot see, because itonly happens to a database that predates them.-What makes the upgrade safe is a *negative* fact stated in-``changelog.d/3299.breaking.md``: the release "adds no database schema-migration", and its rollback section says "No schema downgrade is-required". In other words there is no schema step in either direction ---nothing to apply on the way up, nothing to reverse on the way back to the-Flask release.--That claim is load-bearing for both directions (upgrade *and* the documented-rollback to the Flask release), and a changelog sentence cannot enforce-itself. The first group of tests turns it into an assertion -- but it is a+What makes the port itself safe for existing databases is a *negative*+fact stated in ``changelog.d/3299.breaking.md``: "the web-layer change+itself adds no database schema migration". The release that ships the port+also carries later data-repair revisions, so its documented rollback restores+a data backup (see ``docs/deployment/upgrading.md``); this file does not+claim the release as a whole can be rolled back without one.++The claim about the port is load-bearing for the upgrade, and a changelog+sentence cannot enforce itself. The first group of tests turns it into an assertion -- but it is aclaim about ONE commit, so it is checked against that commit's own range(``fb4e33b8d^..fb4e33b8d``): no migration file added or edited there, and --the other half, which the changelog does not state -- no ORM model changed@@ -443,13 +442,14 @@ def _schema_fingerprint(engine):# ----------------------------------------------------------------------------# 1. schema-change gates: the #3299 rollback claim, re-verified at the commit-# that made it, and the general rule every later branch must satisfy+# 1. schema-change gates: the #3299 no-migration claim, re-verified at the+# commit that made it, and the general rule every later branch must satisfy# ---------------------------------------------------------------------------def test_the_3299_port_added_or_edited_no_migration_revision():- """``changelog.d/3299.breaking.md``: "adds no database schema migration".+ """``changelog.d/3299.breaking.md``: "the web-layer change itself adds no+ database schema migration".Checked against the range of the commit that made the claim, notagainst the branch under test: the sentence is a fact about #3299,@@ -475,11 +475,10 @@ def test_the_3299_port_added_or_edited_no_migration_revision():changes = classify(baseline, _tracked_files(after, MIGRATIONS_SUBTREE))assert changes == {"added": [], "removed": [], "edited": []}, (f"#3299 ({PORT_3299_COMMIT[:12]}) changed the Alembic migrations, "- "which contradicts changelog.d/3299.breaking.md -- both its "- "'adds no database schema migration' sentence and the rollback "- f"section's 'No schema downgrade is required': {changes}. Either "- "the commit sha above is wrong, or those must be rewritten to "- "describe the downgrade an operator now has to run."+ "which contradicts changelog.d/3299.breaking.md's 'The web-layer "+ f"change itself adds no database schema migration': {changes}. "+ "Either the commit sha above is wrong, or that sentence must be "+ "rewritten to describe the migration and its rollback.")diff --git a/tests/deployment/test_upgrade_rollback_docs.py b/tests/deployment/test_upgrade_rollback_docs.pynew file mode 100644index 0000000000..39e15f277d--- /dev/null+++ b/tests/deployment/test_upgrade_rollback_docs.py@@ -0,0 +1,416 @@+"""Contracts for the v1.10.7 rollback guidance after the FastAPI release.++Three facts about the rollback are easy to lose in an edit, and each one+costs operators data when it is wrong:++1. v1.10.7 must never be started against the upgraded databases. Its+ ``encrypted_db`` calls ``needs_migration()``, which is true for any+ revision it does not know, and then takes a forced backup with+ ``BackupService``'s default ``max_backups=1``. Every sign-in attempt+ therefore replaces the user's automatic pre-migration backup with a copy+ of the upgraded database before the login fails. The guide, the README+ and the changelog fragment must all say so, and must tell operators to+ copy that backup out of the data directory first.+2. The new release does not keep the pre-migration backup either. The+ post-login backup (``auth.py`` -> ``submit_backup`` ->+ ``create_backup(force=False)``) uses ``backup.max_count``, default 1, so+ the user's first sign-in on a later UTC day replaces it with a copy of+ the upgraded database, and a password change deletes it+ (``purge_and_refresh``). The docs must say to copy it out immediately+ after each user's first sign-in, not merely before a downgrade.+3. The release can ship more than one revision after ``0030``, so the docs+ must not pin the rollback to one revision number. The guide tells+ operators to read the newest revision from ``get_head_revision()`` or+ from the highest-numbered migration file; both must agree.+"""++from __future__ import annotations++import re+from pathlib import Path++import pytest++REPO_ROOT = Path(__file__).resolve().parents[2]+GUIDE = REPO_ROOT / "docs" / "deployment" / "upgrading.md"+README = REPO_ROOT / "README.md"+CHANGELOG = REPO_ROOT / "changelog.d" / "3299.breaking.md"+VERSIONS_DIR = (+ REPO_ROOT+ / "src"+ / "local_deep_research"+ / "database"+ / "migrations"+ / "versions"+)++ROLLBACK_DOCS = {+ "upgrading.md": GUIDE,+ "README.md": README,+ "3299.breaking.md": CHANGELOG,+}+++def _prose(path: Path) -> str:+ return re.sub(r"\s+", " ", path.read_text(encoding="utf-8"))++[email protected]("name", sorted(ROLLBACK_DOCS))+def test_rollback_docs_warn_about_the_pre_migration_backup(name):+ if name == "3299.breaking.md" and not CHANGELOG.exists():+ pytest.skip("fragment consumed by towncrier at release prep")+ text = _prose(ROLLBACK_DOCS[name])+ lowered = text.lower()+ assert "never start v1.10.7 against the upgraded" in lowered, (+ f"{name} must forbid starting v1.10.7 against upgraded data: each "+ "sign-in attempt there overwrites the pre-migration backup"+ )+ assert "before any downgrade attempt" in lowered, name+ assert "encrypted_databases/backups/" in text, (+ f"{name} must say where the pre-migration backup lives"+ )+ assert "outside the data directory" in lowered, name++[email protected]("name", sorted(ROLLBACK_DOCS))+def test_rollback_docs_say_the_new_release_replaces_the_backup(name):+ if name == "3299.breaking.md" and not CHANGELOG.exists():+ pytest.skip("fragment consumed by towncrier at release prep")+ lowered = _prose(ROLLBACK_DOCS[name]).lower()+ for phrase in (+ "immediately after that user's first sign-in",+ "later utc day",+ "password change",+ ):+ assert phrase in lowered, (+ f"{name} must say that the new release's own daily login backup "+ "and password changes replace the pre-migration backup, so it "+ f"must be copied out at once; missing {phrase!r}"+ )+++def test_guide_explains_how_to_keep_the_pre_migration_backup():+ text = _prose(GUIDE)+ lowered = text.lower()+ assert "soon after the upgrade" not in lowered, (+ "'soon after the upgrade' is too late: each user's backup is made "+ "at their first sign-in and replaced at a later-day sign-in"+ )+ # _cleanup_old_backups deletes by count (index >= max_backups) as well+ # as by age, so a raised max_count is never age-only protection.+ assert "does not protect them from a password change" not in text, (+ "a raised backup.max_count is not 'safe except for a password "+ "change': the Nth later-day login backup evicts it by count"+ )+ for phrase in (+ "Copy the pre-migration backups out immediately",+ "restores the upgraded database, not the pre-migration one",+ "`backup.max_count`",+ "`backup.max_age_days`",+ "`LDR_BACKUP_MAX_COUNT`",+ "`LDR_BACKUP_MAX_AGE_DAYS`",+ "only widens that window",+ "the Nth login backup made after it",+ "however young the backup is",+ "until the user's first sign-in on the `backup.max_count`-th later "+ "UTC day on which they sign in",+ "only the first sign-in on each later UTC day adds one",+ "a password change still deletes it at any time",+ "It is not a substitute for copying the backups out",+ "Check each file's timestamp first",+ ):+ assert phrase in text, f"upgrading.md lost {phrase!r}"+ # create_backup(force=False) skips while a backup dated the current UTC+ # day exists, so later sign-ins on the same day add no login backup.+ for wrong in (+ "each sign-in on a later UTC day still adds",+ "Nth sign-in on a later UTC day",+ ):+ assert wrong not in text, (+ f"upgrading.md says {wrong!r}: only the first sign-in on each "+ "UTC day adds a login backup"+ )+++def test_guide_warns_that_a_first_sign_in_past_midnight_loses_the_backup():+ """The pre-migration backup's file name is stamped before its export.++ ``_create_backup_impl`` takes the timestamp before ``sqlcipher_export``+ runs, and the migration plus the login's own backup follow. If the first+ sign-in crosses midnight UTC, that login backup finds no file for the+ new day and, with ``max_count`` 1, deletes the pre-migration backup+ before anyone can copy it.+ """+ text = _prose(GUIDE)+ for phrase in (+ "the first sign-in itself does this if it runs past midnight UTC",+ "named for the time its export started",+ "the file named in that user's `Pre-migration backup created` log "+ "line still exists",+ ):+ assert phrase in text, f"upgrading.md lost {phrase!r}"+++def test_guide_says_a_failed_pre_migration_backup_does_not_stop_migration():+ """The pre-migration backup is best-effort, not a precondition.++ ``encrypted_db`` logs ``Pre-migration backup failed`` when+ ``create_backup(force=True)`` fails or raises, and then runs+ ``initialize_database`` anyway. The guide must not promise that the+ copy is always written, and must tell operators how to spot a user who+ has none.+ """+ text = _prose(GUIDE)+ assert "it first writes an encrypted copy" not in text, (+ "the pre-migration backup can fail and the migration still runs; "+ "the guide must not say the copy is always written"+ )+ for phrase in (+ "it first tries to write an encrypted copy",+ "A failed pre-migration backup does not stop the migration",+ "less than twice the database's size",+ "logs a `Pre-migration backup failed` line and migrates the database "+ "anyway",+ "Treat a user with no `Pre-migration backup created` line for that "+ "sign-in as having no pre-migration backup",+ "first sign-in logged `Pre-migration backup failed`, or no "+ "`Pre-migration backup created` line, has no pre-migration backup to "+ "restore from",+ ):+ assert phrase in text, f"upgrading.md lost {phrase!r}"+ backup_doc = _prose(REPO_ROOT / "docs" / "security" / "database-backup.md")+ assert "a backup is always created regardless" not in backup_doc+ assert "the migration runs anyway" in backup_doc+++def test_guide_backup_references_do_not_pin_one_backup_doc_layout():+ """Keep the guide valid across backup-format changes.++ Backup names may gain a suffix after the timestamp (for example a+ unique suffix and a ``.db.salt`` sidecar), and the backup guide's+ restore section may be restructured. The rollback guide must describe+ the name by its timestamp prefix and link to the backup page itself.+ """+ text = _prose(GUIDE)+ assert "(`ldr_backup_YYYYMMDD_HHMMSS`)" in text+ assert "`ldr_backup_YYYYMMDD_HHMMSS.db`" not in text+ assert "database-backup.md#" not in text+++def test_pre_migration_backup_fails_when_disk_space_is_short(+ tmp_path, monkeypatch+):+ """Pin the failure the guide names: under 2x the database size free."""+ import shutil+ from collections import namedtuple++ from local_deep_research.database.backup.backup_service import (+ BackupService,+ )++ db = tmp_path / "ldr_user_test.db"+ db.write_bytes(b"x" * 100)+ usage = namedtuple("usage", "total used free")+ monkeypatch.setattr(shutil, "disk_usage", lambda *_: usage(1000, 801, 199))+ svc = object.__new__(BackupService)+ svc.username = "rollback-doc-user"+ svc.db_path = db+ svc.backup_dir = tmp_path / "backups"+ svc.backup_dir.mkdir()++ result = svc.create_backup(force=True)++ assert not result.success+ assert "Insufficient disk space" in (result.error or "")+ assert list(svc.backup_dir.iterdir()) == []+++def test_guide_says_to_protect_and_destroy_copied_out_backups():+ """Copies taken outside the data directory escape the password-change purge.++ ``purge_and_refresh`` deletes every backup on a password change because+ old-password backups are a risk. Copies the guide tells operators to+ take keep opening with the old password, so the guide must say to+ protect and destroy them, and must not ask operators to hold users'+ passwords.+ """+ text = _prose(GUIDE)+ for phrase in (+ "keeps doing so after the user changes that password",+ "cannot reach copies made outside the data directory",+ "destroy them once a rollback to v1.10.7 is no longer needed",+ "destroy a user's copies at once",+ "do not collect users' passwords yourself",+ ):+ assert phrase in text, f"upgrading.md lost {phrase!r}"+ assert "Retain the users' database passwords" not in text, (+ "LDR does not store user passwords; the guide must not tell "+ "operators to collect them"+ )+++def test_guide_covers_accounts_created_after_the_upgrade():+ """New accounts' databases are created at the head revision.++ ``create_user_database`` runs ``initialize_database``, so v1.10.7+ refuses those databases, and no pre-upgrade copy of them exists.+ """+ text = _prose(GUIDE)+ assert (+ "Accounts created on the new release have no pre-upgrade copy" in text+ )+ assert "Export anything those users need before rolling back" in text+++def test_login_backup_is_skipped_while_a_backup_dated_today_exists(+ tmp_path, monkeypatch+):+ """Pin the day gate the guide's counting rests on.++ The guide counts login backups per later UTC day, not per sign-in. That+ holds only while ``create_backup(force=False)`` skips when a file dated+ the current UTC day exists, and runs when the newest file is from an+ earlier day (the midnight case).+ """+ from datetime import UTC, datetime, timedelta++ from local_deep_research.database.backup.backup_service import (+ BackupResult,+ BackupService,+ )++ calls = []++ def fake_impl(self):+ calls.append(self.username)+ return BackupResult(success=True)++ from local_deep_research.database.backup import backup_service++ # Freeze the clock create_backup reads, so a run crossing midnight UTC+ # cannot disagree with the dates written below.+ frozen = datetime(2026, 10, 3, 12, 0, tzinfo=UTC)++ class _FrozenDatetime(datetime):+ @classmethod+ def now(cls, tz=None):+ return frozen if tz is not None else frozen.replace(tzinfo=None)++ monkeypatch.setattr(backup_service, "datetime", _FrozenDatetime)+ monkeypatch.setattr(BackupService, "_create_backup_impl", fake_impl)+ # This test is about the calendar-day gate, not backup integrity. A later+ # backup-service hardening may verify today's file before using it as a gate.+ monkeypatch.setattr(BackupService, "_verify_backup", lambda *_: True)+ svc = object.__new__(BackupService)+ svc.username = "rollback-doc-user"+ svc.backup_dir = tmp_path++ yesterday = (frozen - timedelta(days=1)).strftime("%Y%m%d")+ (tmp_path / f"ldr_backup_{yesterday}_235959.db").write_bytes(b"x")+ svc.create_backup(force=False)+ assert calls == ["rollback-doc-user"], (+ "a login backup must run when the newest file is from an earlier "+ "UTC day"+ )++ today = frozen.strftime("%Y%m%d")+ (tmp_path / f"ldr_backup_{today}_000001.db").write_bytes(b"x")+ svc.create_backup(force=False)+ assert calls == ["rollback-doc-user"], (+ "a second sign-in on the same UTC day made another login backup; "+ "the guide's per-day counting is then wrong"+ )+++def test_changelog_says_a_raised_max_count_only_delays_eviction():+ if not CHANGELOG.exists():+ pytest.skip("fragment consumed by towncrier at release prep")+ text = _prose(CHANGELOG)+ for phrase in (+ "only delays the replacement",+ "the user's first sign-in on the `backup.max_count`-th later UTC "+ "day on which they sign in still deletes it",+ "a password change deletes it at any time",+ ):+ assert phrase in text, f"3299.breaking.md lost {phrase!r}"+ assert "user's sign-in on the `backup.max_count`-th later UTC day" not in (+ text+ ), "only the first sign-in on each UTC day adds a login backup"+ assert "(a password change still deletes it)" not in text, (+ "the fragment must not present a raised max_count as protection "+ "that only a password change defeats"+ )++[email protected]("name", sorted(ROLLBACK_DOCS))+def test_rollback_docs_do_not_pin_one_new_revision(name):+ if name == "3299.breaking.md" and not CHANGELOG.exists():+ pytest.skip("fragment consumed by towncrier at release prep")+ text = _prose(ROLLBACK_DOCS[name])+ pinned = re.findall(+ r"(?:includes|ships alongside|stamped|the new) database revision "+ r"`?\d{4}`?|identified by '\d{4}'|stamped `\d{4}`",+ text,+ )+ assert not pinned, (+ f"{name} names a single post-0030 revision as the release's "+ f"revision: {pinned}. The release may ship several; describe them "+ "as the revisions newer than 0030."+ )+++def test_documented_head_lookup_matches_highest_numbered_file():+ from local_deep_research.database.alembic_runner import get_head_revision++ numbered = sorted(+ p.name.split("_", 1)[0]+ for p in VERSIONS_DIR.glob("[0-9][0-9][0-9][0-9]_*.py")+ )+ assert numbered, "no migration files found"+ assert get_head_revision() == numbered[-1], (+ "the guide says the newest revision is the highest-numbered "+ "migration file; that no longer matches get_head_revision()"+ )+ guide = _prose(GUIDE)+ assert "get_head_revision()" in guide+ assert "database/migrations/versions/" in guide+++def test_raised_max_count_evicts_the_pre_migration_backup_by_count(tmp_path):+ """Pin the code fact the guide's max_count warning rests on.++ The guide says a raised ``backup.max_count`` of N still deletes the+ pre-migration backup at the user's first sign-in on the Nth later UTC+ day on which they sign in, however young+ it is. That holds only while ``_cleanup_old_backups`` evicts by count+ as well as by age.+ """+ import os+ import time++ from local_deep_research.database.backup.backup_service import (+ BackupService,+ )++ svc = object.__new__(BackupService)+ svc.backup_dir = tmp_path+ svc.max_backups = 3+ svc.max_age_days = 90++ now = time.time()+ pre_migration = tmp_path / "ldr_backup_20260101_000000.db"+ names = [pre_migration.name] + [+ f"ldr_backup_2026010{day}_000000.db" for day in (2, 3, 4)+ ]+ for age_hours, name in zip((72, 48, 24, 0), names):+ path = tmp_path / name+ path.write_bytes(b"x")+ os.utime(path, (now - age_hours * 3600, now - age_hours * 3600))++ svc._cleanup_old_backups()++ assert not pre_migration.exists(), (+ "a three-day-old backup survived max_count=3 with max_age_days=90; "+ "if cleanup no longer evicts by count, update the guide's warning"+ )+ assert sorted(p.name for p in tmp_path.iterdir()) == names[1:]diff --git a/tests/test_config_env_var_contracts.py b/tests/test_config_env_var_contracts.pyindex a93345f4d1..dfed2d65a5 100644--- a/tests/test_config_env_var_contracts.py+++ b/tests/test_config_env_var_contracts.py@@ -313,12 +313,60 @@ _KNOWN_UNDOCUMENTED = {"DISABLE_RATE_LIMITING","LDR_TEST_MODE","LDR_LOG_SETTINGS",- "RATE_LIMIT_STORAGE_URI",- "RATELIMIT_STORAGE_URL","LDR_STRICT_TEMPLATE_LINKS",}+def test_rate_limit_storage_vars_are_explained_not_just_named():+ """Naming a variable is not documenting it.++ ``RATE_LIMIT_STORAGE_URI`` and ``RATELIMIT_STORAGE_URL`` left+ ``_KNOWN_UNDOCUMENTED`` when the upgrade guide named them in a rollback+ reminder. The corpus check above only looks for the name, so pin the+ explanation in the reverse-proxy guide's notes as well.+ """+ doc = " ".join(+ (REPO_ROOT / "docs" / "deployment" / "reverse-proxy.md")+ .read_text(encoding="utf-8")+ .split()+ )+ for phrase in (+ "`RATE_LIMIT_STORAGE_URI`",+ "`RATELIMIT_STORAGE_URL`",+ "including the per-client limit on login requests, in process "+ "memory by default",+ "survives restarts",+ "still works when `RATE_LIMIT_STORAGE_URI` is unset",+ "per-account lockout after repeated failed passwords stays in "+ "process memory either way",+ # The storage-URI redaction details differ between current main and+ # the rate-limit redaction rework (#4870), so the guide gives only+ # guidance that holds on both: the error names the variable, the+ # redaction is best-effort, and the variables belong in the process+ # environment rather than a .env file (slowapi reads that file itself).+ "startup fails with an error that names the variable",+ "redaction of credentials in it is best-effort",+ "Set them in the process environment, not in a `.env` file",+ ):+ assert phrase in doc, f"reverse-proxy.md lost {phrase!r}"+ # Redaction behaviour is version-dependent (see above); never promise+ # what it covers or what it misses.+ assert "redacts any password" not in doc, (+ "reverse-proxy.md overclaims the storage-URI redaction"+ )+ for stale in (+ "replaced by `***@`",+ "neither names the variable nor redacts the URI",+ "appears in that error and the logs",+ ):+ assert stale not in doc, (+ f"reverse-proxy.md pins storage-URI redaction detail {stale!r}"+ )+ assert "including the login-attempt limit" not in doc, (+ "the account lockout is not stored in the rate-limit backend"+ )++def test_hand_rolled_security_vars_are_all_still_read_by_the_code():"""Pin the premise of the documentation test that follows.