From 8295a174847601d4759b49867a5c3e654f626cf7 Mon Sep 17 00:00:00 2001 From: Daniel Covington Date: Sat, 5 Dec 2026 11:38:20 -0500 Subject: [PATCH] Import keeps references valid; FK repair tool; JSON 500 for API action errors - Import creates placeholder principals (status imported, no keys or grants) for author ids unknown to the target installation, inside the transaction. - backup.asp repair [apply] (backup.cmd / ops.sh): lists foreign key violations; apply creates placeholders and deletes orphaned verifications. - Errors raised inside /api actions answer a JSON 500 (detail only in Development) and are logged as action_error; open transactions roll back. - GetAppSetting honours APPSETTING_ environment overrides; compose passes APPSETTING_Environment. - api_keys.last_used_at update is best-effort (a read-only db no longer turns valid keys into 401). - Docs: never open the WAL database from the host; repair procedure. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 6 +- README.md | 7 +- app/controllers/ApiPortabilityController.asp | 17 ++++- core/helpers.asp | 13 ++++ core/lib.Api.asp | 44 +++++++++++ core/mvc.asp | 16 ++++ docker-compose.yml | 3 + public/api/memory-v1.openapi.json | 2 +- scripts/backup.asp | 80 +++++++++++++++++++- scripts/backup.cmd | 1 + scripts/ops.sh | 5 +- tests/phase3-portability.sh | 3 + 12 files changed, 187 insertions(+), 10 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ff8b806..5f093e8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,8 +39,8 @@ When unsure about an object, ProgID, method or config key, check `/opt/axonasp/w - Semantic retrieval: `core/lib.Embeddings.asp` (Ollama client, Qdrant client, `embedding_index` bookkeeping, `Ranker_Class` used by recall/search/context; it also applies usefulness feedback on the current revision, see `ApplyFeedback`). Write paths call `Emb_MarkPending`/`Emb_MarkDelete*` inside their transaction and `Emb_AfterWrite` after commit; new write paths that change memory or chunk text must do the same. `scripts\embed.cmd status|run|reindex`. Regression suite: `bash tests/phase3-semantic.sh`. The `embed-worker` container runs `scripts/embed.asp` (`EMBED_ACTION=worker`) every 30 seconds to retry pending/failed items. - Learning loop: `ApiLearningController` (session events, `POST /learn`, candidates, review, `GET /memories/:id/sources`, `POST /feedback`) with helpers in `core/lib.Learning.asp`: `Evidence_Class` (validate, resolve and pin evidence), `Mem_Create`/`Mem_Revise`/`Mem_Verify` (memory writes shared with review; inside a transaction), `Mem_ForgetLinked` (called by forget), and `Tel_*` (retrieval telemetry: recall/search/context must record the `query_id` they return and the revision of each result, or feedback cannot reference them). Review needs `verify` and is refused to the author without `admin`. New tenant-scoped tables must also be deleted by `provision purge`. Regression suite: `bash tests/phase3-learning.sh`. - Ingestion jobs: `core/lib.Jobs.asp` (`Job_Create`, `Job_Claim`, `Job_RunIngest`, `Job_ProcessDue`), shared by `ApiDocumentsController.Ingest` and the worker (`scripts/embed.asp`, actions `jobs` and `worker`). Claim jobs only with `Job_Claim` (conditional UPDATE) and keep publishing plus the job update in one transaction. Regression suite: `bash tests/phase3-jobs.sh` (uses `tests/fixtures/job_state.asp` to simulate interruptions). -- Portability: `ApiPortabilityController` (`POST /exports`, `POST /imports`). The export format (`agent-memory-export`, `schema_version` 1) is a contract: a new canonical table or column means a new schema version (and an importer for the old one), and the import must keep ids, revisions, timestamps and principal ids, rebuild derived data (content hashes, FTS, `Emb_MarkPending`) and stay all-or-nothing. Regression suite: `bash tests/phase3-portability.sh`. -- Backup/restore: `scripts\backup.cmd backup|verify` and `scripts\restore.cmd ` (`scripts/backup.asp`; see README "Operations"). Backups go to `db/backups/` (git-ignored). `bash tests/backup-restore.sh` restores into an isolated container on port 8802 and never touches the live database. Never run `restore.cmd` against the live database without the user's go-ahead. +- Portability: `ApiPortabilityController` (`POST /exports`, `POST /imports`). The export format (`agent-memory-export`, `schema_version` 1) is a contract: a new canonical table or column means a new schema version (and an importer for the old one), and the import must keep ids, revisions, timestamps and principal ids, rebuild derived data (content hashes, FTS, `Emb_MarkPending`) and stay all-or-nothing. Author ids unknown to the target get placeholder principals (`Api_EnsureReferencedPrincipals`, status `imported`, never authenticates) inside the import transaction. Regression suite: `bash tests/phase3-portability.sh`. +- Backup/restore: `scripts\backup.cmd backup|verify|repair` and `scripts\restore.cmd ` (`scripts/backup.asp`; see README "Operations"). Backups go to `db/backups/` (git-ignored). `bash tests/backup-restore.sh` restores into an isolated container on port 8802 and never touches the live database. Never run `restore.cmd` against the live database without the user's go-ahead. - Observability: `core/lib.Observability.asp` (included before `lib.Api.asp`). `Api_Send` calls `Obs_Record` once per response (access-log line via `console.log`, counters in `Application`); `MVC_InvokeAction` sets `Obs_Action`, so metric labels are controller actions, never raw paths. A response written without `Api_Send` must call `Obs_Record status` itself (as `ApiHealthController.Metrics` does). Never log bodies, query strings or keys. `GET /api/v1/metrics` needs `AMK_METRICS_TOKEN` (`.env`, git-ignored). Regression suite: `bash tests/observability.sh`. - The AxonASP image is pinned by digest in `docker-compose.yml`. To upgrade, change the digest deliberately, `docker compose up -d`, and rerun all nine suites (`tests/*.sh`). @@ -200,6 +200,8 @@ Create objects with `Server.CreateObject("ProgID")` using exact ProgIDs from `/o - **Fixed-size array members fail.** `Private m_cnt(7)` in a Class gave "Subscript out of range" when used; declare `Private m_cnt()` and `ReDim m_cnt(7)` in a method. - **`console.log` lines are decorated.** In the HTTP server they go to stdout (`docker logs`) with ANSI colour codes, a date/time and a marker before the text, and end with the text plus a newline. Write one JSON object per call and extract it with `grep -o '{"log":.*'`. `WScript.Shell` `ExpandEnvironmentStrings` reads the container's environment in the HTTP server too. - **`VACUUM INTO` works through G3DB** and gives a consistent copy while the server is running (`scripts/backup.asp`). There is no `sqlite3` binary in the image; use the CLI with G3DB for database maintenance. `PRAGMA foreign_keys` is off, so check `PRAGMA foreign_key_check` (the backup verification fails on violations). +- **Never open the database from the host.** It runs in WAL mode; on the production VM `-wal`/`-shm` files left by a host process (uid 1000) made the database read-only for the container user, so every write and even API-key authentication failed. Stop the containers, remove the stray files, restart. Maintenance goes through the CLI tools inside the container. Updating `api_keys.last_used_at` is best-effort for this reason: a failing write there must not turn a valid key into a 401. +- **API action errors are JSON.** `HandleDispatchError` in `core/mvc.asp` answers `/api/...` requests whose action raised with a JSON 500 `internal_error` (detail only when `Environment` is Development), rolls back an open transaction and logs `{"log":"action_error",...}` with `console.error`. Settings can be overridden per environment with `APPSETTING_` environment variables (`GetAppSetting`). - **Run CLI tools as the server user.** The HTTP server runs as `axonasp`; a database file first created by a root `docker exec` was read-only to it ("attempt to write a readonly database"). `gen.cmd`, `migrate.cmd` and `provision.cmd` use `docker exec -u axonasp`. - **PowerShell splits `read,write` into two arguments.** Quote lists passed to `provision.cmd grant`: `'"read,write"'`. - **Class member vs local name clash.** Avoid a local `Dim controllerName` inside a class that also has a `ControllerName` property. diff --git a/README.md b/README.md index 2e8257a..de80151 100644 --- a/README.md +++ b/README.md @@ -70,9 +70,9 @@ Implements [Universal-Agent-Memory-Specification.md](Universal-Agent-Memory-Spec **Tooling** - `scripts\provision.cmd` (tenant, principal, key, namespace, grant, revoke, list, purge); see AGENTS.md section 1. Quote permission lists in PowerShell: `'"read,write"'`. - `scripts\export-memories.ps1` / `scripts/export-memories.sh`: dump every readable memory (set `AMK_KEY`). -- `scripts/ops.sh`: the same tools for a Linux server (migrate, provision, embed, backup, verify, restore). +- `scripts/ops.sh`: the same tools for a Linux server (migrate, provision, embed, backup, verify, restore, repair). - `scripts\embed.cmd status|run|reindex`: semantic index status, catch up on pending/failed items, or rebuild (after changing the model). -- Tests (containers must be running): `bash tests/phase1-api.sh` (79 checks), `bash tests/phase2-api.sh` (45), `bash tests/phase3-context.sh` (60), `bash tests/phase3-semantic.sh` (30; stops and restarts the ollama container once), `bash tests/phase3-learning.sh` (93), `bash tests/phase3-portability.sh` (44), `bash tests/backup-restore.sh` (21; starts a throw-away container on port 8802), `bash tests/phase3-jobs.sh` (41; stops the embed-worker container while it runs), `bash tests/observability.sh` (25; restarts the container; the metrics checks need `AMK_METRICS_TOKEN`). Each creates and purges its own tenants. +- Tests (containers must be running): `bash tests/phase1-api.sh` (79 checks), `bash tests/phase2-api.sh` (45), `bash tests/phase3-context.sh` (60), `bash tests/phase3-semantic.sh` (30; stops and restarts the ollama container once), `bash tests/phase3-learning.sh` (93), `bash tests/phase3-portability.sh` (47), `bash tests/backup-restore.sh` (21; starts a throw-away container on port 8802), `bash tests/phase3-jobs.sh` (41; stops the embed-worker container while it runs), `bash tests/observability.sh` (25; restarts the container; the metrics checks need `AMK_METRICS_TOKEN`). Each creates and purges its own tenants. **Next (not started)** 1. Consolidation of related experiences into candidates (today agents propose them by hand with `POST /learn`). @@ -86,6 +86,7 @@ SQLite (`db/app.sqlite`) is the only source of truth. The Qdrant vectors are der - **Verify** a stored copy: `scripts\backup.cmd verify db/backups/.sqlite`. - **Restore**: `scripts\restore.cmd db/backups/.sqlite`. It stops `axonasp` and `embed-worker`, verifies the backup (nothing changes if that fails), keeps the current database as `db\backups\pre-restore-.sqlite`, copies the backup into place, starts both containers and runs `scripts\embed.cmd reindex`. If the backup is older than the code's schema, run `scripts\migrate.cmd up` afterwards (once per pending migration). - **Recovery objectives**: the recovery point (RPO) is the backup interval; schedule `scripts\backup.cmd backup` (for example hourly with Task Scheduler or cron) to match the loss you can accept. The recovery time (RTO) is the restore plus the reindex. The drill `bash tests/backup-restore.sh` restores a fresh backup into an isolated container (own db folder, port 8802; the live database is not touched), checks that the restored server returns the same export as the live one, and fails if it takes longer than `RTO_SECONDS` (default 120). Measured here: about 70 to 100 seconds, almost all of it the first start of a new container; `restore.cmd` restarts the existing containers instead. The reindex time grows with the data and does not block reads: lexical retrieval works at once, semantic ranking catches up. +- **Repair after an import**: an import keeps the author ids of the source installation. Since this version it creates a placeholder principal (status `imported`, no keys or grants, cannot sign in) for each unknown one, so references stay valid. For data imported earlier, `scripts\backup.cmd repair` (Linux: `bash scripts/ops.sh repair`) lists the foreign key violations; `repair apply` creates the placeholders and deletes verifications whose memory no longer exists, then reports what is left. Take a backup first. - An export (`POST /exports`) is a portable copy per caller and namespace, not a full backup: it leaves out tenants, principals, keys, grants, sessions, feedback and audit events. ## Configuration @@ -93,6 +94,8 @@ SQLite (`db/app.sqlite`) is the only source of truth. The Qdrant vectors are der - `public/web.config`: `ConnectionString` (`sqlite:/opt/axonasp/site/db/app.sqlite`), environment and UI settings, and the `Embedding*` / `VectorStoreUrl` settings (`EmbeddingProvider` `none` turns semantic retrieval off). Settings are cached per process: `docker restart axonasp` after editing. - First start of the semantic stack: `docker compose up -d`, then `docker exec ollama ollama pull nomic-embed-text` once (the model lives in the `ollama-models` volume). The ollama image is about 6 GB. - Metrics: put `AMK_METRICS_TOKEN=` in a `.env` file in the repo root (git-ignored; compose reads it), then `docker compose up -d`. Scrape `http://:8801/api/v1/metrics` with `Authorization: Bearer `. Access logs: `docker logs axonasp 2>&1 | grep -o '{"log":"access".*'` (each line has a runtime timestamp prefix); `ApiAccessLog` in `web.config` turns them off. +- Any `web.config` setting can be overridden by an environment variable `APPSETTING_` (read by `GetAppSetting`). Compose passes `APPSETTING_Environment`: put `APPSETTING_Environment=Production` in the server's `.env` so that API errors never include internal details (SQL, error text). In development an unexpected error inside an API action is answered with a JSON 500 that includes the detail; in production only the request id, and the detail goes to `docker logs` (`{"log":"action_error",...}`). +- Never open `db/app.sqlite` from the host (sqlite3, a GUI, Python) while the containers run: the database is in WAL mode, and `-wal`/`-shm` files created by the host user are not writable by the container user, which makes every write fail ("attempt to write a readonly database"). Use `scripts/ops.sh` / the `.cmd` tools, which run inside the container as `axonasp`. - `/opt/axonasp/config/axonasp.toml` (inside the container): server settings; any key can be overridden with an environment variable (see `docker-compose.yml`). ## Rules for developers and AI agents diff --git a/app/controllers/ApiPortabilityController.asp b/app/controllers/ApiPortabilityController.asp index a12bda1..1b6e3ca 100644 --- a/app/controllers/ApiPortabilityController.asp +++ b/app/controllers/ApiPortabilityController.asp @@ -64,7 +64,7 @@ End Class Class ApiPortabilityController_Class ' import state - Private m_err, m_nsPaths(), m_nsIds(), m_nsN, m_types, m_memIds, m_cnt() + Private m_err, m_nsPaths(), m_nsIds(), m_nsN, m_types, m_memIds, m_cnt(), m_placeholders Public Property Get useLayout() useLayout = False @@ -327,6 +327,7 @@ Class ApiPortabilityController_Class m_cnt(i) = 0 Next m_err = "" + m_placeholders = 0 m_memIds = "," m_nsN = 0 ReDim m_nsPaths(15) @@ -395,6 +396,18 @@ Class ApiPortabilityController_Class Next End If + ' Author ids from another installation get placeholder principals (no keys, cannot sign in) so references + ' stay valid; the ids themselves are kept as provenance. + If Len(m_err) = 0 Then + On Error Resume Next + m_placeholders = Api_EnsureReferencedPrincipals(Api_TenantId) + If Err.Number <> 0 Then + m_err = "db:" & Err.Description + Err.Clear + End If + On Error GoTo 0 + End If + If Len(m_err) > 0 Then On Error Resume Next DAL().RollbackTransaction @@ -422,7 +435,7 @@ Class ApiPortabilityController_Class Emb_AfterWrite Api_TenantId, 8 Api_Audit "import.apply", "import", "", "ok" Api_Send 201, "{""imported"":{""namespaces"":" & m_nsN & ",""memories"":" & m_cnt(0) & ",""memory_revisions"":" & m_cnt(1) & ",""verifications"":" & m_cnt(2) & _ - ",""documents"":" & m_cnt(3) & ",""document_revisions"":" & m_cnt(4) & ",""chunks"":" & m_cnt(5) & ",""evidence_links"":" & m_cnt(6) & "}" & _ + ",""documents"":" & m_cnt(3) & ",""document_revisions"":" & m_cnt(4) & ",""chunks"":" & m_cnt(5) & ",""evidence_links"":" & m_cnt(6) & ",""placeholder_principals"":" & m_placeholders & "}" & _ ",""indexing"":{""lexical"":""indexed"",""semantic"":""pending""}}" End Sub diff --git a/core/helpers.asp b/core/helpers.asp index 32d242e..65cde89 100644 --- a/core/helpers.asp +++ b/core/helpers.asp @@ -35,6 +35,19 @@ Public Function GetAppSetting(key) Exit Function End If + ' A per-host override wins over web.config: environment variable APPSETTING_ (for example + ' APPSETTING_Environment=Production in the server's .env, passed through docker-compose.yml). + Dim envName, envVal + envName = "APPSETTING_" & key + envVal = CreateObject("WScript.Shell").ExpandEnvironmentStrings("%" & envName & "%") + If envVal <> "%" & envName & "%" And Len(envVal) > 0 Then + GetAppSetting = envVal + Application.Lock + Application(cacheKey) = envVal + Application.Unlock + Exit Function + End If + ' Load from web.config only if not cached Set xml = Server.CreateObject("Microsoft.XMLDOM") ' web.config is in the web root (public/); the CLI migration runner uses the framework folder as root diff --git a/core/lib.Api.asp b/core/lib.Api.asp index eacf4a0..7387c9f 100644 --- a/core/lib.Api.asp +++ b/core/lib.Api.asp @@ -336,7 +336,12 @@ Function Api_Authenticate() End If End If + ' Best effort: bookkeeping must not lock everyone out when the database refuses writes (for example a + ' read-only file); the write paths report such failures themselves. + On Error Resume Next DAL().Execute "UPDATE api_keys SET last_used_at = ? WHERE id = ?", Array(Api_Now(), keyId) + Err.Clear + On Error GoTo 0 Api_Authenticate = True End Function @@ -405,6 +410,45 @@ Function Api_CanAccessNamespace(namespaceId, perm) Api_CanAccessNamespace = Api_PathAllows(p, perm) End Function +'----------------------------------------------------------------------------------------------------------------------- +' Imported data keeps its original author ids (provenance), which may not exist in this installation. This creates a +' placeholder principal (type service, status imported, no keys, no grants: it can never sign in) for every author id +' that canonical memory/document data references but that does not exist, so foreign keys stay valid. +' tenantId "" covers every tenant (repair); returns the number of placeholders created. Raises on a database error. +'----------------------------------------------------------------------------------------------------------------------- +Function Api_EnsureReferencedPrincipals(tenantId) + Dim sql, rs, rows, i, n + sql = "SELECT DISTINCT pid, tid FROM (" & _ + "SELECT creator_principal_id AS pid, tenant_id AS tid FROM memories UNION ALL " & _ + "SELECT r.created_by, m.tenant_id FROM memory_revisions r JOIN memories m ON m.id = r.memory_id UNION ALL " & _ + "SELECT v.reviewer_principal_id, m.tenant_id FROM verifications v JOIN memories m ON m.id = v.memory_id UNION ALL " & _ + "SELECT created_by, tenant_id FROM documents UNION ALL " & _ + "SELECT r.created_by, d.tenant_id FROM document_revisions r JOIN documents d ON d.id = r.document_id UNION ALL " & _ + "SELECT created_by, tenant_id FROM evidence_links" & _ + ") x WHERE pid IS NOT NULL AND NOT EXISTS (SELECT 1 FROM principals p WHERE p.id = x.pid)" + If Len(tenantId) > 0 Then + Set rs = DAL().Query(sql & " AND tid = ?", tenantId) + Else + Set rs = DAL().Query(sql, Empty) + End If + rows = Empty + If Not rs.EOF Then + rows = rs.GetRows() + End If + rs.Close + n = 0 + If IsArray(rows) Then + For i = 0 To UBound(rows, 2) + If Api_IsId("" & rows(0, i)) Then + DAL().Execute "INSERT OR IGNORE INTO principals (id, tenant_id, type, name, status, created_at) VALUES (?, ?, 'service', 'imported principal', 'imported', ?)", _ + Array("" & rows(0, i), "" & rows(1, i), Api_Now()) + n = n + 1 + End If + Next + End If + Api_EnsureReferencedPrincipals = n +End Function + '----------------------------------------------------------------------------------------------------------------------- ' Audit trail (security-relevant actions; never log secrets or content) '----------------------------------------------------------------------------------------------------------------------- diff --git a/core/mvc.asp b/core/mvc.asp index 61ad975..187a97f 100644 --- a/core/mvc.asp +++ b/core/mvc.asp @@ -122,6 +122,22 @@ Class MVC_Dispatcher_Class Dim isDevelopment isDevelopment = (LCase(GetAppSetting("Environment")) = "development") + ' JSON API requests get a JSON 500 (never an HTML snippet with status 200); details only in development. + If LCase(Left(GetRequestPath(), 5)) = "/api/" Then + Dim msg + msg = "Internal error. The request was not completed." + If isDevelopment Then + msg = msg & " [dev] " & actionName & ": " & errorDesc & " (" & errorNum & ")" + End If + On Error Resume Next + DAL().RollbackTransaction + Err.Clear + On Error GoTo 0 + console.error "{""log"":""action_error"",""request_id"":" & JsonLite_Quote(Api_RequestId()) & ",""action"":" & JsonLite_Quote(actionName) & ",""error"":" & JsonLite_Quote(errorNum & " " & errorDesc) & "}" + Api_Error 500, "internal_error", msg + Exit Sub + End If + If isDevelopment Then Response.Write "
" Response.Write "Controller Action Error
" diff --git a/docker-compose.yml b/docker-compose.yml index a28a598..7d67f07 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -14,6 +14,8 @@ services: SERVER_WEB_ROOT: /opt/axonasp/site/public # GET /api/v1/metrics is enabled when this is set (16+ characters); put it in a git-ignored .env file AMK_METRICS_TOKEN: ${AMK_METRICS_TOKEN:-} + # web.config settings can be overridden per host with APPSETTING_; servers set Production in .env + APPSETTING_Environment: ${APPSETTING_Environment:-Development} volumes: - .:/opt/axonasp/site restart: unless-stopped @@ -27,6 +29,7 @@ services: environment: SERVER_WEB_ROOT: /opt/axonasp/site EMBED_ACTION: worker + APPSETTING_Environment: ${APPSETTING_Environment:-Development} command: ["/bin/sh", "-c", "while true; do ./axonasp-cli -r /opt/axonasp/site/scripts/embed.asp; sleep 30; done"] volumes: - .:/opt/axonasp/site diff --git a/public/api/memory-v1.openapi.json b/public/api/memory-v1.openapi.json index 17ccd0d..84c8d3e 100644 --- a/public/api/memory-v1.openapi.json +++ b/public/api/memory-v1.openapi.json @@ -1230,7 +1230,7 @@ "additionalProperties": { "type": "integer" }, - "description": "namespaces, memories, memory_revisions, verifications, documents, document_revisions, chunks, evidence_links" + "description": "namespaces, memories, memory_revisions, verifications, documents, document_revisions, chunks, evidence_links, placeholder_principals (author ids unknown to this installation, created without keys or grants)" }, "indexing": { "type": "object", diff --git a/scripts/backup.asp b/scripts/backup.asp index 3e97372..5b36d87 100644 --- a/scripts/backup.asp +++ b/scripts/backup.asp @@ -8,6 +8,9 @@ ' restore verifies , keeps the current database as db/backups/pre-restore-.sqlite, then copies ' over the live database. Only with the HTTP server and embed worker STOPPED ' (scripts\restore.cmd does that); afterwards run scripts\embed.cmd reindex. +' repair [apply] lists foreign key violations in the live database and what would fix them; with BACKUP_FILE=apply +' it creates placeholder principals for author ids from another installation (imported data) and +' deletes verifications whose memory no longer exists. Take a backup first. ' ' File names are relative to the framework folder (for example db/backups/app-20261205-120000.sqlite) or absolute ' under /opt/axonasp/site. The framework folder must be the web root: -e SERVER_WEB_ROOT=/opt/axonasp/site @@ -265,6 +268,79 @@ Function DoRestore() DoRestore = True End Function +' Foreign key violations of the live database grouped as "table->parent", one line each; returns the total. +Function ReportFk() + Dim rs, keys, total, k, d + Set d = Server.CreateObject("Scripting.Dictionary") + total = 0 + Set rs = DAL().Query("PRAGMA foreign_key_check", Empty) + Do While Not rs.EOF + k = rs(0) & "->" & rs(2) + If d.Exists(k) Then + d(k) = d(k) + 1 + Else + d.Add k, 1 + End If + total = total + 1 + rs.MoveNext + Loop + rs.Close + keys = d.Keys + For Each k In keys + Say " " & k & ": " & d(k) + Next + Say "foreign_key_violations: " & total + ReportFk = total +End Function + +Function ScalarOf(sql) + Dim rs + Set rs = DAL().Query(sql, Empty) + ScalarOf = CLng(rs(0)) + rs.Close +End Function + +Function DoRepair() + Dim apply, orphans, made, left + DoRepair = False + apply = (LCase(Arg("BACKUP_FILE")) = "apply") + Say "-- before" + ReportFk + orphans = ScalarOf("SELECT COUNT(*) FROM verifications v WHERE NOT EXISTS (SELECT 1 FROM memories m WHERE m.id = v.memory_id)") + Say "orphaned_verifications: " & orphans + If Not apply Then + Say "dry run: nothing changed. Placeholder principals are created for the missing author ids and the orphaned" + Say "verifications are deleted with BACKUP_FILE=apply (scripts\backup.cmd repair apply, ops.sh repair apply)." + DoRepair = True + Exit Function + End If + On Error Resume Next + DAL().BeginTransaction + made = Api_EnsureReferencedPrincipals("") + If Err.Number = 0 Then + DAL().Execute "DELETE FROM verifications WHERE NOT EXISTS (SELECT 1 FROM memories m WHERE m.id = verifications.memory_id)", Empty + End If + If Err.Number <> 0 Then + Say "ERROR: " & Err.Description + Err.Clear + DAL().RollbackTransaction + On Error GoTo 0 + Exit Function + End If + DAL().CommitTransaction + If Err.Number <> 0 Then + Say "ERROR: " & Err.Description + On Error GoTo 0 + Exit Function + End If + On Error GoTo 0 + Say "placeholder_principals_created: " & made + Say "orphaned_verifications_deleted: " & orphans + Say "-- after" + left = ReportFk() + DoRepair = (left = 0) +End Function + Dim action, ok action = LCase(Arg("BACKUP_ACTION")) ok = False @@ -275,8 +351,10 @@ Select Case action ok = DoVerify() Case "restore" ok = DoRestore() + Case "repair" + ok = DoRepair() Case Else - Say "Usage: BACKUP_ACTION=backup|verify|restore [BACKUP_FILE=db/backups/.sqlite]" + Say "Usage: BACKUP_ACTION=backup|verify|restore|repair [BACKUP_FILE=db/backups/.sqlite]" End Select If ok Then Say "RESULT: ok" diff --git a/scripts/backup.cmd b/scripts/backup.cmd index 05c5d0e..0bb029e 100644 --- a/scripts/backup.cmd +++ b/scripts/backup.cmd @@ -4,6 +4,7 @@ rem rem scripts\backup.cmd backup [file] consistent copy (VACUUM INTO) to db\backups\app-YYYYMMDD-HHMMSS.sqlite rem or [file], then integrity check and row-count comparison with the live db rem scripts\backup.cmd verify integrity check, foreign keys, latest migration, row counts per table +rem scripts\backup.cmd repair [apply] foreign key repair of the live db after an import (dry run without apply) rem rem File names are relative to the repo root, for example db/backups/app-20261205-120000.sqlite. rem To restore, use scripts\restore.cmd . The last line printed is "RESULT: ok" or "RESULT: failed". diff --git a/scripts/ops.sh b/scripts/ops.sh index 709498d..567c98b 100755 --- a/scripts/ops.sh +++ b/scripts/ops.sh @@ -8,6 +8,7 @@ # bash scripts/ops.sh backup [file] online backup to db/backups/ and verification # bash scripts/ops.sh verify verify a backup file # bash scripts/ops.sh restore stop, verify, restore, start, reindex (see README) +# bash scripts/ops.sh repair [apply] foreign key repair after an import (dry run without apply) set -eu cd "$(dirname "$0")/.." cli() { docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site "$@"; } @@ -21,7 +22,7 @@ case "$cmd" in axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/provision.asp ;; embed) cli -e "EMBED_ACTION=${1:-status}" axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/embed.asp ;; - backup|verify) + backup|verify|repair) cli -e "BACKUP_ACTION=$cmd" -e "BACKUP_FILE=${1:-}" axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/backup.asp ;; restore) [ $# -ge 1 ] || { echo "usage: ops.sh restore db/backups/.sqlite" >&2; exit 1; } @@ -36,5 +37,5 @@ case "$cmd" in fi "$0" embed reindex ;; *) - sed -n '2,11p' "$0"; exit 1 ;; + sed -n '2,12p' "$0"; exit 1 ;; esac diff --git a/tests/phase3-portability.sh b/tests/phase3-portability.sh index 0bc0192..659b5c5 100644 --- a/tests/phase3-portability.sh +++ b/tests/phase3-portability.sh @@ -124,6 +124,9 @@ docker restart axonasp >/dev/null; for i in $(seq 1 20); do curl -s -o /dev/null R=$(import_ "$RSK" "$E") check "cold: import into clean tenant -> 201" "201" "$(tail -1 <<<"$R")" check "import counts" "5 6 3 1 2" "$(head -1 <<<"$R" | jq_ "' '.join(str(d['imported'][k]) for k in ['memories','memory_revisions','evidence_links','documents','document_revisions'])")" +check "authors of the purged tenant get placeholder principals" "True" "$(head -1 <<<"$R" | jq_ "d['imported']['placeholder_principals']>0")" +check "no foreign key violations after import" "0" "$(MSYS_NO_PATHCONV=1 docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site -e BACKUP_ACTION=repair axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/backup.asp 2>&1 | tr -d '\015' | sed -n 's/^foreign_key_violations: //p' | head -1)" +check "placeholder principal gets no API key" "no" "$(prov key "$WID" | grep -q '^api_key' && echo yes || echo no)" R=$(body "$RSK" GET /memories/$M1) check "imported memory: same id, revision 2" "2" "$(echo "$R" | jq_ "d['data']['current_revision']")" check "imported memory: verified" "verified" "$(echo "$R" | jq_ "d['data']['verification_status']")"