diff --git a/doc/fleet-schedule-registry.md b/doc/fleet-schedule-registry.md index d93e0a5b42..8760b1d4fe 100644 --- a/doc/fleet-schedule-registry.md +++ b/doc/fleet-schedule-registry.md @@ -306,8 +306,8 @@ The OS-timer half of surface 2. Cadence is the unit's own `OnCalendar`/`OnUnitAc | `repo-universe-issue-check.timer` | `OnCalendar=*-*-* 00:00:00` | `repo-universe-issue-check.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `queue-coverage-reconcile.timer` (repo-shipped, not yet installed) | `OnCalendar=*-*-* *:41:00` | `queue-coverage-reconcile.service` | laptop (user systemd; code#7016) | not recorded | not recorded | 2026-11-08 | 2026-11-08 | | `scheduled-history.timer` | `OnCalendar=*-*-* *:0/5:00` | `scheduled-history.service` | laptop (user systemd; code#2174) | not recorded | not recorded | 2026-11-11 | 2026-11-14 | -| `supabase-backup.timer` | `OnCalendar=*-*-* 04:42:00,OnCalendar=*-*-* 16:42:00` | `supabase-backup.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | -| `supabase-turso-coord-mirror.timer` | `OnCalendar=*-*-* 04:24:00` | `supabase-turso-coord-mirror.service` | laptop (user systemd) | not recorded | not recorded | 2026-11-11 | 2026-11-11 | +| `supabase-backup.timer` | retired in config 2026-11-18 (activation pending) | `supabase-backup.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | +| `supabase-turso-coord-mirror.timer` | retired in config 2026-11-18 (activation pending) | `supabase-turso-coord-mirror.service` | laptop (user systemd) | not recorded | not recorded | 2026-11-11 | 2026-11-11 | | `sync-models.timer` | `OnCalendar=*-*-* 00:00:00` | `sync-models.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `systemd-tmpfiles-clean.timer` | `OnUnitActiveUSec=1d,OnStartupUSec=5min` | `systemd-tmpfiles-clean.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `tldr-update.timer` | `OnCalendar=Mon *-*-* 00:00:00` | `tldr-update.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | diff --git a/nixos/home/laptop-backups.nix b/nixos/home/laptop-backups.nix index cbb16e4dbd..218ec9e43e 100644 --- a/nixos/home/laptop-backups.nix +++ b/nixos/home/laptop-backups.nix @@ -101,6 +101,7 @@ let cfg = config.services.laptop-backups; home = config.home.homeDirectory; + pmAggregator = pkgs.callPackage ../../pkgs/pm-aggregator/package.nix { }; dashboardPkg = pkgs.writeShellScriptBin "pm-dashboard-backup" ( builtins.readFile ./pm-dashboard-backup.sh ); @@ -309,7 +310,7 @@ in Service = { Type = "oneshot"; ExecStart = "${dashboardPkg}/bin/pm-dashboard-backup"; - Environment = "PATH=${servicePath}:${home}/tools/bin:/run/current-system/sw/bin"; + Environment = [ "PATH=${servicePath}:${home}/tools/bin:/run/current-system/sw/bin" "PM_AGG_STORE_BACKEND=turso" "PM_AGG_TURSO_EXPORT_BIN=${pmAggregator}/bin/pm-aggregator-export-turso-stores" ]; }; }; }) diff --git a/nixos/home/pm-dashboard-backup-manifest.test.sh b/nixos/home/pm-dashboard-backup-manifest.test.sh index 9b407437e2..998c05325e 100755 --- a/nixos/home/pm-dashboard-backup-manifest.test.sh +++ b/nixos/home/pm-dashboard-backup-manifest.test.sh @@ -250,11 +250,11 @@ fi if manifest_json missing-optional | python3 -c ' import json, sys m = json.load(sys.stdin) -sys.exit(0 if len(m.get("expected", [])) == 36 else 1) +sys.exit(0 if len(m.get("expected", [])) == 46 else 1) '; then - ok "missing-optional: manifest lists all 36 expected members" + ok "missing-optional: manifest lists all 46 expected members" else - fail "missing-optional: manifest expected list is not the full 36-member set" + fail "missing-optional: manifest expected list is not the full 46-member set" fi # --- decisions ledger is required (#10293) ----------------------------------- @@ -479,6 +479,41 @@ else fail "supabase-export: log lacks the per-table counts: $(cat "$TMP_ROOT/supabase-export.log")" fi +# --- Turso exporter stages every required table, no credentials in fixtures --- +setup_home turso-export +EXPORTER="$TMP_ROOT/turso-fixture-exporter" +cat >"$EXPORTER" <<'STUBEOF' +#!/usr/bin/env bash +set -eu +[[ "$1" == --output-dir && $# == 2 ]] +mkdir -p "$2" +for table in agg_actions agg_activity_ingestion agg_activity_gaps agg_usage_snapshots agg_store_documents alerts_incidents alerts_incident_events alerts_push_subscriptions alerts_notification_sends orch_runs; do + printf '[]' >"$2/$table.json" +done +STUBEOF +chmod +x "$EXPORTER" +PATH="$BIN:$PATH" HOME="$RUN_HOME" BWS_ACCESS_TOKEN=fake-token \ + RCLONE_STUB_DIR="$TMP_ROOT/turso-export/rclone-store" \ + RCLONE_CALLS_LOG="$TMP_ROOT/turso-export/rclone-calls.log" \ + PM_DB_DUMP_SCRIPT="$DUMP_SCRIPT_ARG" PM_AGG_STORE_BACKEND=turso \ + PM_AGG_TURSO_EXPORT_BIN="$EXPORTER" \ + bash "$SCRIPT" 2026-10-28 >"$TMP_ROOT/turso-export.log" 2>&1 +RC=$? +if [[ $RC -eq 0 ]]; then ok "turso-export: completed"; else fail "turso-export: rc=$RC $(cat "$TMP_ROOT/turso-export.log")"; fi +assert_member turso-export turso/agg_actions.json required present +assert_member turso-export turso/alerts_push_subscriptions.json required present +assert_member turso-export turso/orch_runs.json required present + +setup_home turso-missing +PATH="$BIN:$PATH" HOME="$RUN_HOME" BWS_ACCESS_TOKEN=fake-token \ + RCLONE_STUB_DIR="$TMP_ROOT/turso-missing/rclone-store" \ + RCLONE_CALLS_LOG="$TMP_ROOT/turso-missing/rclone-calls.log" \ + PM_DB_DUMP_SCRIPT="$DUMP_SCRIPT_ARG" PM_AGG_STORE_BACKEND=turso \ + PM_AGG_TURSO_EXPORT_BIN=/nonexistent/turso-exporter \ + bash "$SCRIPT" 2026-10-28 >"$TMP_ROOT/turso-missing.log" 2>&1 +RC=$? +if [[ $RC -ne 0 ]] && no_upload turso-missing; then ok "turso-missing: fails without uploading"; else fail "turso-missing: did not fail closed"; fi + if ((failures > 0)); then echo "pm-dashboard-backup manifest tests: $failures failure(s)" >&2 exit 1 diff --git a/nixos/home/pm-dashboard-backup.sh b/nixos/home/pm-dashboard-backup.sh index 0f7f5df3b5..4b77f41d51 100755 --- a/nixos/home/pm-dashboard-backup.sh +++ b/nixos/home/pm-dashboard-backup.sh @@ -377,6 +377,16 @@ conditional file supabase/agg_activity_ingestion.json conditional file supabase/agg_activity_gaps.json conditional file supabase/agg_usage_snapshots.json conditional file supabase/agg_store_documents.json +conditional file turso/agg_actions.json +conditional file turso/agg_activity_ingestion.json +conditional file turso/agg_activity_gaps.json +conditional file turso/agg_usage_snapshots.json +conditional file turso/agg_store_documents.json +conditional file turso/alerts_incidents.json +conditional file turso/alerts_incident_events.json +conditional file turso/alerts_push_subscriptions.json +conditional file turso/alerts_notification_sends.json +conditional file turso/orch_runs.json conditional tree db-dumps conditional file projector/pmp_links.sql optional tree aggregator/snapshots @@ -610,13 +620,14 @@ fi # relocated project; the password and project ref come from Bitwarden by # key name only and are never logged. SUPA_RAN=0 +TURSO_RAN=0 SUPA_MODE="${PM_AGG_SUPABASE_EXPORT:-auto}" case "$SUPA_MODE" in auto | off) ;; *) fail "PM_AGG_SUPABASE_EXPORT must be auto or off, got '$SUPA_MODE'" ;; esac -SUPA_BACKEND="" -if [ -f "$AGG/.env" ]; then +SUPA_BACKEND="${PM_AGG_STORE_BACKEND:-}" +if [ -z "$SUPA_BACKEND" ] && [ -f "$AGG/.env" ]; then SUPA_BACKEND="$(grep -E '^[[:space:]]*(export[[:space:]]+)?PM_AGG_STORE_BACKEND[[:space:]]*=' "$AGG/.env" 2>/dev/null | tail -n 1 | sed -E 's/^[[:space:]]*(export[[:space:]]+)?PM_AGG_STORE_BACKEND[[:space:]]*=[[:space:]]*//')" SUPA_BACKEND="$(pmp_trim_value "$SUPA_BACKEND")" @@ -666,6 +677,21 @@ PYEOF )" || fail "Supabase export produced unreadable JSON" SUPA_RAN=1 log "canonical aggregator stores exported from Supabase: $SUPA_COUNTS" +elif [ "$SUPA_MODE" = "auto" ] && [ "$SUPA_BACKEND" = "turso" ]; then + TURSO_EXPORT_BIN="${PM_AGG_TURSO_EXPORT_BIN:-pm-aggregator-export-turso-stores}" + command -v "$TURSO_EXPORT_BIN" >/dev/null 2>&1 || fail "Turso exporter not found" + "$TURSO_EXPORT_BIN" --output-dir "$STAGE/turso" || fail "Turso canonical store export failed" + python3 - "$STAGE/turso" <<'PYEOF' +import json, pathlib, sys +root = pathlib.Path(sys.argv[1]) +for name in ('agg_actions','agg_activity_ingestion','agg_activity_gaps','agg_usage_snapshots','agg_store_documents','alerts_incidents','alerts_incident_events','alerts_push_subscriptions','alerts_notification_sends','orch_runs'): + rows = json.loads((root / (name + '.json')).read_text()) + if not isinstance(rows, list): raise SystemExit(name + ': not a JSON array') + print(name + '=' + str(len(rows))) +PYEOF + [ $? -eq 0 ] || fail "Turso export produced unreadable or missing JSON" + TURSO_RAN=1 + log "canonical aggregator stores exported from Turso" else log "aggregator store backend is '${SUPA_BACKEND:-file}' — Supabase store export not applicable" fi @@ -687,7 +713,7 @@ done # --- manifest (files as staged + the expected set's per-member status) --- AGG_DIR="$AGG" AGG_DERIVED="$AGG_DERIVED" \ EXPECTED_SET="$EXPECTED_SET" DUMP_RAN="$DUMP_RAN" PMP_RAN="$PMP_RAN" \ - SUPA_RAN="$SUPA_RAN" \ + SUPA_RAN="$SUPA_RAN" TURSO_RAN="$TURSO_RAN" \ python3 - "$STAGE" "$DATE" "$CREATED_AT" <<'PYEOF' import hashlib, json, os, sys stage, date, created = sys.argv[1], sys.argv[2], sys.argv[3] @@ -716,6 +742,8 @@ for line in os.environ.get("EXPECTED_SET", "").splitlines(): if cls == "conditional": if rel.startswith("supabase/"): ran = os.environ.get("SUPA_RAN") + elif rel.startswith("turso/"): + ran = os.environ.get("TURSO_RAN") elif rel.startswith("projector/"): ran = os.environ.get("PMP_RAN") else: diff --git a/nixos/hosts/default.nix b/nixos/hosts/default.nix index 05b2290f47..a2633b499d 100644 --- a/nixos/hosts/default.nix +++ b/nixos/hosts/default.nix @@ -147,6 +147,8 @@ in home-manager.users.user = { imports = [ ../home/laptop-backups.nix ]; services.laptop-backups.enable = true; + # muse-dev2 deleted; preserve existing dumps, retire failed source backup. + services.laptop-backups.supabase.enable = false; }; } { @@ -234,7 +236,7 @@ in # the store units below. home-manager.users.user = { imports = [ ../home/supabase-turso-coord-mirror.nix ]; - services.supabase-turso-coord-mirror.enable = true; + services.supabase-turso-coord-mirror.enable = false; # source retired 2026-11-18 }; } { diff --git a/nixos/services/pm-stack/default.nix b/nixos/services/pm-stack/default.nix index d85de134d5..8e44f3780a 100644 --- a/nixos/services/pm-stack/default.nix +++ b/nixos/services/pm-stack/default.nix @@ -299,11 +299,11 @@ in "PM_AGG_ACTIVITY_FILE=${aggState}/activity-ingestion.json" # #6815: the four aggregator stores that used to live only # in this state dir (actions, activity-ingestion, usage - # snapshots, aa-last-good) are canonical in Supabase - # muse-dev2. The local files stay as a rebuildable cache + # snapshots, aa-last-good) are canonical in Turso + # fleet-platform. The local files stay as a rebuildable cache # (see pm-stack/aggregator/README.md, "Store backend"); # switching this back to "file" is the rollback. - "PM_AGG_STORE_BACKEND=supabase" + "PM_AGG_STORE_BACKEND=turso" "PM_AGG_STORE_WRITER=pm-aggregator.service" "BWS_BIN=/run/current-system/sw/bin/bws" "BWS_ACCESS_TOKEN_FILE=${home}/.config/bws/access-token" @@ -472,10 +472,10 @@ in "BWS_BIN=/run/current-system/sw/bin/bws" "BWS_ACCESS_TOKEN_FILE=${home}/.config/bws/access-token" # #6815: the collector writes the aa-last-good canonical - # document to Supabase muse-dev2 (the local file stays a + # document to Turso fleet-platform (the local file stays a # rebuildable cache). Same writer identity as the # aggregator unit env; see "Store backend" in the README. - "PM_AGG_STORE_BACKEND=supabase" + "PM_AGG_STORE_BACKEND=turso" "PM_AGG_STORE_WRITER=fleet-feed-collector" "FLEET_FEED_OUT=${aggState}/fleet-feed.json" "PM_AGG_FRESHNESS_URL=http://127.0.0.1:4871/publish" diff --git a/pkgs/fleet-state-writers/package.nix b/pkgs/fleet-state-writers/package.nix new file mode 100644 index 0000000000..1feccbd08f --- /dev/null +++ b/pkgs/fleet-state-writers/package.nix @@ -0,0 +1,19 @@ +# Preserve the relative helper imports when deploying either operator writer. +{ stdenvNoCC, python3, makeWrapper }: +stdenvNoCC.mkDerivation { + pname = "fleet-state-writers"; + version = "2026-11-18"; + dontUnpack = true; + nativeBuildInputs = [ makeWrapper ]; + installPhase = '' + root=$out/libexec/fleet-state-writers + mkdir -p $root/scripts $root/pm-stack/shared-schema $out/bin + cp ${../../scripts/fleet_turso.py} $root/scripts/fleet_turso.py + cp ${../../scripts/ainventory-interpretation.py} $root/scripts/ainventory-interpretation.py + cp ${../../pm-stack/shared-schema/orchestration-writer.py} $root/pm-stack/shared-schema/orchestration-writer.py + makeWrapper ${python3}/bin/python3 $out/bin/orchestration-writer \ + --add-flags "$root/pm-stack/shared-schema/orchestration-writer.py" + makeWrapper ${python3}/bin/python3 $out/bin/ainventory-interpretation \ + --add-flags "$root/scripts/ainventory-interpretation.py" + ''; +} diff --git a/pkgs/pm-aggregator/package.nix b/pkgs/pm-aggregator/package.nix index e106d48168..082cd816ee 100644 --- a/pkgs/pm-aggregator/package.nix +++ b/pkgs/pm-aggregator/package.nix @@ -111,6 +111,8 @@ stdenvNoCC.mkDerivation { --add-flags "run $out/libexec/pm-aggregator/scripts/gather-quota.ts" makeWrapper ${lib.getExe bun} $out/bin/pm-aggregator-generate-digest \ --add-flags "run $out/libexec/pm-aggregator/scripts/generate-digest.ts" + makeWrapper ${lib.getExe bun} $out/bin/pm-aggregator-export-turso-stores \ + --add-flags "run $out/libexec/pm-aggregator/scripts/export-turso-stores.ts" runHook postInstall ''; diff --git a/pm-stack/shared-schema/ainventory-turso-guards.sql b/pm-stack/shared-schema/ainventory-turso-guards.sql new file mode 100644 index 0000000000..ec44b9a78b --- /dev/null +++ b/pm-stack/shared-schema/ainventory-turso-guards.sql @@ -0,0 +1,23 @@ +-- Apply after recovery creates the ainventory_* tables. Never weakens access +-- controls or rewrites recovered records. SQLite counterpart of PG event guards. +CREATE TRIGGER IF NOT EXISTS ainventory_findings_no_update BEFORE UPDATE ON ainventory_findings BEGIN SELECT RAISE(ABORT,'findings is append-only'); END; +CREATE TRIGGER IF NOT EXISTS ainventory_findings_no_delete BEFORE DELETE ON ainventory_findings BEGIN SELECT RAISE(ABORT,'findings is append-only'); END; +CREATE TRIGGER IF NOT EXISTS ainventory_interpretation_runs_no_update BEFORE UPDATE ON ainventory_interpretation_runs BEGIN SELECT RAISE(ABORT,'interpretation_runs is append-only'); END; +CREATE TRIGGER IF NOT EXISTS ainventory_interpretation_runs_no_delete BEFORE DELETE ON ainventory_interpretation_runs BEGIN SELECT RAISE(ABORT,'interpretation_runs is append-only'); END; +CREATE TRIGGER IF NOT EXISTS ainventory_notes_no_update BEFORE UPDATE ON ainventory_notes BEGIN SELECT RAISE(ABORT,'notes is append-only'); END; +CREATE TRIGGER IF NOT EXISTS ainventory_notes_no_delete BEFORE DELETE ON ainventory_notes BEGIN SELECT RAISE(ABORT,'notes is append-only'); END; +CREATE TRIGGER IF NOT EXISTS ainventory_measurement_events_no_update BEFORE UPDATE ON ainventory_measurement_events BEGIN SELECT RAISE(ABORT,'measurement_events is append-only'); END; +CREATE TRIGGER IF NOT EXISTS ainventory_measurement_events_no_delete BEFORE DELETE ON ainventory_measurement_events BEGIN SELECT RAISE(ABORT,'measurement_events is append-only'); END; +CREATE TRIGGER IF NOT EXISTS ainventory_price_events_no_update BEFORE UPDATE ON ainventory_price_events BEGIN SELECT RAISE(ABORT,'price_events is append-only'); END; +CREATE TRIGGER IF NOT EXISTS ainventory_price_events_no_delete BEFORE DELETE ON ainventory_price_events BEGIN SELECT RAISE(ABORT,'price_events is append-only'); END; +CREATE TRIGGER IF NOT EXISTS ainventory_provider_policies_no_update BEFORE UPDATE ON ainventory_provider_policies BEGIN SELECT RAISE(ABORT,'provider_policies is append-only'); END; +CREATE TRIGGER IF NOT EXISTS ainventory_provider_policies_no_delete BEFORE DELETE ON ainventory_provider_policies BEGIN SELECT RAISE(ABORT,'provider_policies is append-only'); END; + +-- Explicit identity collision guards also reject INSERT OR REPLACE when +-- recursive_triggers is off. These source tables have no other UNIQUE keys. +CREATE TRIGGER IF NOT EXISTS ainventory_findings_no_replace BEFORE INSERT ON ainventory_findings WHEN EXISTS (SELECT 1 FROM ainventory_findings WHERE id=NEW.id) BEGIN SELECT RAISE(ABORT,'findings identity already exists'); END; +CREATE TRIGGER IF NOT EXISTS ainventory_interpretation_runs_no_replace BEFORE INSERT ON ainventory_interpretation_runs WHEN EXISTS (SELECT 1 FROM ainventory_interpretation_runs WHERE id=NEW.id) BEGIN SELECT RAISE(ABORT,'interpretation_runs identity already exists'); END; +CREATE TRIGGER IF NOT EXISTS ainventory_notes_no_replace BEFORE INSERT ON ainventory_notes WHEN EXISTS (SELECT 1 FROM ainventory_notes WHERE id=NEW.id) BEGIN SELECT RAISE(ABORT,'notes identity already exists'); END; +CREATE TRIGGER IF NOT EXISTS ainventory_measurement_events_no_replace BEFORE INSERT ON ainventory_measurement_events WHEN EXISTS (SELECT 1 FROM ainventory_measurement_events WHERE id=NEW.id) BEGIN SELECT RAISE(ABORT,'measurement_events identity already exists'); END; +CREATE TRIGGER IF NOT EXISTS ainventory_price_events_no_replace BEFORE INSERT ON ainventory_price_events WHEN EXISTS (SELECT 1 FROM ainventory_price_events WHERE id=NEW.id) BEGIN SELECT RAISE(ABORT,'price_events identity already exists'); END; +CREATE TRIGGER IF NOT EXISTS ainventory_provider_policies_no_replace BEFORE INSERT ON ainventory_provider_policies WHEN EXISTS (SELECT 1 FROM ainventory_provider_policies WHERE id=NEW.id) BEGIN SELECT RAISE(ABORT,'provider_policies identity already exists'); END; diff --git a/pm-stack/shared-schema/orchestration-writer.py b/pm-stack/shared-schema/orchestration-writer.py index f803e8c11e..78f8cd8989 100644 --- a/pm-stack/shared-schema/orchestration-writer.py +++ b/pm-stack/shared-schema/orchestration-writer.py @@ -11,10 +11,8 @@ document and the item counts agree (the export regeneration step is the pass's own file write; this read-back is its parity proof). -Transport: the standing Supabase Management API SQL route (the same -route domain_append_pg.py uses) with secrets fetched by name via -`fleet secrets get` — values are never printed or written to disk. - +Transport: Turso fleet-platform Hrana, using Fleet secret resolution. +Statements and credentials stay in memory; failed batches roll back. Usage: orchestration-writer.py [path-to-orchestration.json] Exit 0 with a one-line JSON verdict on success; nonzero on any failure (the files remain authoritative — a failed write changes nothing the @@ -28,7 +26,10 @@ with exit 2. """ -import argparse, json, os, subprocess, sys, tempfile +import argparse, json, os, sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts")) +from fleet_turso import Turso DEFAULT_PATH = os.path.expanduser( @@ -53,78 +54,9 @@ def parse_args(argv): return parser.parse_args(argv) -# Strict parse first: a usage error (exit 2) must precede every secret -# fetch, subprocess, network request, and file read below. -ARGS = parse_args(sys.argv[1:]) - - -def secret(name): - fleet = "/home/hatch/tools/bin/fleet" - if not os.path.exists(fleet): - fleet = "fleet" - out = subprocess.run( - [fleet, "secrets", "get", name], capture_output=True, text=True - ) - if out.returncode != 0: - raise SystemExit(f"secret fetch failed: {name}") - return out.stdout.strip() - - -REF = secret("supabase.muse-dev2.project-ref") -TOKEN = secret("supabase.muse-dev2.access-token-muse-cli") -URL = f"https://api.supabase.com/v1/projects/{REF}/database/query" - - -def sql(query): - fd, tmp = tempfile.mkstemp(suffix=".json") - with os.fdopen(fd, "w") as f: - json.dump({"query": query}, f) - try: - out = subprocess.run( - [ - "curl", - "-sS", - "-m", - "120", - "-A", - "Mozilla/5.0", - "-X", - "POST", - "-H", - f"Authorization: Bearer {TOKEN}", - "-H", - "Content-Type: application/json", - "--data", - "@" + tmp, - URL, - "-w", - "\n%{http_code}", - ], - capture_output=True, - text=True, - ) - finally: - os.unlink(tmp) - if out.returncode != 0: - raise SystemExit(f"curl failed: {out.stderr[:200]}") - body, _, code = out.stdout.rpartition("\n") - if int(code) >= 300: - raise SystemExit(f"SQL failed (HTTP {code}): {body[:400]}") - return json.loads(body) if body.strip() else [] - - -def lit(value): - if value is None: - return "NULL" - return "'" + str(value).replace("'", "''") + "'" - - -def jsonb(obj): - return lit(json.dumps(obj)) + "::jsonb" - - def main(): - path = ARGS.path + args = parse_args(sys.argv[1:]) + path = args.path with open(path) as f: doc = json.load(f) run_id = doc["runId"] @@ -138,68 +70,32 @@ def main(): items.append((tier, item)) item_count = len(items) - prior = sql("SELECT id, first_seen_run_id FROM public.orch_items") - first_seen = {r["id"]: r["first_seen_run_id"] for r in prior} - - stmts = ["BEGIN;"] - stmts.append( - "INSERT INTO public.orch_runs (run_id, generated_at, document_version, provenance, document, item_count) VALUES (" - + ", ".join( - [ - lit(run_id), - lit(generated_at), - str(version), - jsonb(provenance), - jsonb(doc), - str(item_count), - ] - ) - + ") ON CONFLICT (run_id) DO NOTHING;" - ) - stmts.append("DELETE FROM public.orch_items;") + db = Turso() + existing = db.query("SELECT document,item_count FROM orch_runs WHERE run_id=?", [run_id]) + expected_document = json.dumps(doc) + if existing: + if len(existing) != 1 or json.loads(existing[0]["document"]) != doc or existing[0]["item_count"] != item_count: + raise SystemExit("conflicting run-id replay; no writes attempted") + # Compare JSON semantically in Python, then guard the exact observed text + # inside the transaction. This accepts restored JSONB key ordering while + # refusing any concurrent change between this read and the atomic write. + expected_document = existing[0]["document"] + stmts = [("INSERT INTO orch_runs (run_id,generated_at,document_version,provenance,document,item_count) VALUES (?,?,?,?,?,?) ON CONFLICT(run_id) DO NOTHING", [run_id, generated_at, version, provenance, doc, item_count])] + # Upsert before removing stale rows; preserve first_seen atomically. for tier, item in items: - fsr = first_seen.get(item["id"], run_id) - stmts.append( - "INSERT INTO public.orch_items (id, tier, kind, title, source, state, reason, ref, since, last_seen_at, item, first_seen_run_id, last_seen_run_id) VALUES (" - + ", ".join( - [ - lit(item["id"]), - lit(tier), - lit(item["kind"]), - lit(item["title"]), - lit(item["source"]), - lit(item.get("state")), - lit(item["reason"]), - lit(item.get("ref")), - lit(item["since"]), - lit(item["lastSeenAt"]), - jsonb(item), - lit(fsr), - lit(run_id), - ] - ) - + ");" - ) - stmts.append("COMMIT;") - sql("\n".join(stmts)) - - runs = sql( - "SELECT run_id, item_count, document FROM public.orch_runs WHERE run_id = " - + lit(run_id) - ) - if len(runs) != 1: - raise SystemExit(f"read-back: run row missing for {run_id}") - if runs[0]["item_count"] != item_count: - raise SystemExit( - f"read-back: item_count {runs[0]['item_count']} != {item_count}" - ) - if runs[0]["document"] != doc: - raise SystemExit("read-back: stored document differs from the file document") - counts = sql("SELECT count(*) AS n FROM public.orch_items") + stmts.append(("INSERT INTO orch_items (id,tier,kind,title,source,state,reason,ref,since,last_seen_at,item,first_seen_run_id,last_seen_run_id) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET tier=excluded.tier,kind=excluded.kind,title=excluded.title,source=excluded.source,state=excluded.state,reason=excluded.reason,ref=excluded.ref,since=excluded.since,last_seen_at=excluded.last_seen_at,item=excluded.item,last_seen_run_id=excluded.last_seen_run_id", [item["id"], tier, item["kind"], item["title"], item["source"], item.get("state"), item["reason"], item.get("ref"), item["since"], item["lastSeenAt"], item, run_id, run_id])) + # Exact document membership, including repeat run IDs with a changed item set. + ids = [item["id"] for _, item in items] + stmts.append(("DELETE FROM orch_items WHERE id NOT IN (SELECT value FROM json_each(?))", [ids])) + # Conflicting run-id replay aborts the transaction, never changes the snapshot. + stmts.append(("INSERT INTO orch_runs(run_id,generated_at,document_version,provenance,document,item_count) SELECT run_id,generated_at,document_version,provenance,document,item_count FROM orch_runs WHERE run_id=? AND document != ?", [run_id, expected_document])) + db.batch(stmts, transaction=True) + runs = db.query("SELECT item_count,document FROM orch_runs WHERE run_id=?", [run_id]) + if len(runs) != 1 or runs[0]["item_count"] != item_count or json.loads(runs[0]["document"]) != doc: + raise SystemExit("read-back: stored run differs from the file document") + counts = db.query("SELECT count(*) AS n FROM orch_items") if counts[0]["n"] != item_count: - raise SystemExit( - f"read-back: orch_items has {counts[0]['n']} rows, expected {item_count}" - ) + raise SystemExit("read-back: item count differs from file document") print(json.dumps({"ok": True, "run_id": run_id, "items": item_count})) diff --git a/pm-stack/shared-schema/test_ainventory_turso_guards.py b/pm-stack/shared-schema/test_ainventory_turso_guards.py new file mode 100644 index 0000000000..fc2bb10f37 --- /dev/null +++ b/pm-stack/shared-schema/test_ainventory_turso_guards.py @@ -0,0 +1,19 @@ +"""Oracle: immutable identity/content under UPDATE, DELETE and OR REPLACE.""" +import pathlib +import sqlite3 +import unittest + +TABLES=('findings','interpretation_runs','notes','measurement_events','price_events','provider_policies') +class Guards(unittest.TestCase): + def test_no_mutation_even_without_recursive_triggers(self): + with sqlite3.connect(':memory:') as db: + db.execute('PRAGMA recursive_triggers=OFF') + for t in TABLES:db.execute(f'CREATE TABLE ainventory_{t}(id INTEGER PRIMARY KEY,body TEXT)') + db.executescript(pathlib.Path(__file__).with_name('ainventory-turso-guards.sql').read_text()) + for t in TABLES: + db.execute(f'INSERT INTO ainventory_{t}(body) VALUES(?)',['original']) + for sql in (f'UPDATE ainventory_{t} SET body="changed"',f'DELETE FROM ainventory_{t}',f'INSERT OR REPLACE INTO ainventory_{t} VALUES(1,"changed")'): + with self.subTest(table=t,sql=sql),self.assertRaises(sqlite3.IntegrityError):db.execute(sql) + self.assertEqual(db.execute(f'SELECT body FROM ainventory_{t}').fetchall(),[('original',)]) + db.close() +if __name__=='__main__':unittest.main() diff --git a/pm-stack/shared-schema/test_orchestration_writer_turso.py b/pm-stack/shared-schema/test_orchestration_writer_turso.py new file mode 100644 index 0000000000..2d0e53a785 --- /dev/null +++ b/pm-stack/shared-schema/test_orchestration_writer_turso.py @@ -0,0 +1,55 @@ +"""Oracle: SQLite atomic snapshot, first-seen identity and append-only runs.""" +import importlib.util +import json +from pathlib import Path +import sqlite3 +import sys +import tempfile +import unittest +from unittest.mock import patch + +path = Path(__file__).with_name('orchestration-writer.py') +spec = importlib.util.spec_from_file_location('writer', path) +writer = importlib.util.module_from_spec(spec) +spec.loader.exec_module(writer) + +class Database: + def __init__(self): + self.db=sqlite3.connect(':memory:') + self.db.row_factory=sqlite3.Row + self.db.executescript('CREATE TABLE orch_runs(run_id TEXT PRIMARY KEY,generated_at,document_version,provenance,document,item_count); CREATE TABLE orch_items(id TEXT PRIMARY KEY,tier,kind,title,source,state,reason,ref,since,last_seen_at,item,first_seen_run_id,last_seen_run_id);') + def query(self, sql, args=()): + args=[json.dumps(a) if isinstance(a,(dict,list)) else a for a in args] + return [dict(r) for r in self.db.execute(sql,args)] + def batch(self, stmts, transaction=False): + with self.db: + return [self.query(sql,args) for sql,args in stmts] + +class WriterTests(unittest.TestCase): + def test_snapshot_and_conflicting_replay(self): + db=Database() + item=dict(id='a',kind='decision',title='a',source='test',reason='test',since='2026-11-18',lastSeenAt='2026-11-18') + doc=dict(runId='r1',generatedAt='2026-11-18',version=1,tiers={'needsDrew':[item]}) + with tempfile.TemporaryDirectory() as directory: + p=Path(directory)/'doc.json' + def run(d): + p.write_text(json.dumps(d)) + with patch.object(sys,'argv',[str(path),str(p)]),patch.object(writer,'Turso',return_value=db): + writer.main() + run(doc) + # Recovery JSONB serializes equivalent objects with a different order. + db.db.execute('UPDATE orch_runs SET document=? WHERE run_id=?',(json.dumps(doc,sort_keys=True,indent=2),'r1')) + db.db.commit() + run(doc) + nextdoc={**doc,'runId':'r2'} + run(nextdoc) + self.assertEqual(db.query('select first_seen_run_id from orch_items')[0]['first_seen_run_id'],'r1') + with self.assertRaises(SystemExit): + run({**nextdoc,'tiers':{}}) + self.assertEqual(db.query('select count(*) n from orch_items')[0]['n'],1) + run({**doc,'runId':'r3','tiers':{}}) + self.assertEqual(db.query('select count(*) n from orch_items')[0]['n'],0) + self.assertEqual(db.query('select count(*) n from orch_runs')[0]['n'],3) + db.db.close() + +if __name__=='__main__': unittest.main() diff --git a/scripts/ainventory-interpretation.py b/scripts/ainventory-interpretation.py index 1b00504a06..8b01d596d0 100755 --- a/scripts/ainventory-interpretation.py +++ b/scripts/ainventory-interpretation.py @@ -3,7 +3,7 @@ and the findings event store (issue code#1248, Phase 2 slice 2; slice tracker #10040). -Two jobs, one operator surface, against the muse-dev2 `ainventory` schema: +Two jobs, one operator surface, against the Turso fleet-platform `ainventory_*` tables: awaiting List non-empty gather batches with no interpretation run yet (`ainventory.v_batches_awaiting_interpretation`). Read only. @@ -12,7 +12,7 @@ batch note (an `ainventory.notes` row of kind 'agent_note'), the `ainventory.interpretation_runs` row saying what changed, the follow-up research trail, and any findings. These are - separate PostgREST inserts, not one transaction: if a later + separate Turso inserts, not one transaction: if a later request fails, earlier append-only rows remain and need operator review before retrying. @@ -24,10 +24,10 @@ entry heading is the identity, and an entry already present is skipped, not duplicated. -Append-only: the tables this writes are INSERT-only at the database level -(BEFORE UPDATE/DELETE triggers raise, UPDATE/DELETE grants revoked), so +Append-only deployment contract: the restored tables require SQLite +BEFORE UPDATE/DELETE refusal triggers (see ainventory-turso-guards.sql), so re-interpreting a batch is a NEW interpretation run, never an edit. The -separate PostgREST requests are not transactional; after a failed record +separate Turso requests are not transactional; after a failed record command, inspect the batch's notes, findings, and runs before retrying. Argument contract (repo #3352): the whole command line is declared below @@ -40,9 +40,8 @@ Exit codes: 0 success, 1 operational failure (network, DB refusal, an empty import), 2 usage error. -Secrets: the service-role key is read by name through `bws` -(`supabase.muse-dev2.service-role-key`), never printed, with -BWS_ACCESS_TOKEN honoured when set — the same lookup the gatherer uses. +Secrets: `fleet secrets get turso.fleet-platform-rw-token` (in memory only). +FLEET_TURSO_URL/TOKEN override the destination for controlled deployments. Run: scripts/ainventory-interpretation.py awaiting @@ -62,12 +61,11 @@ import subprocess import sys -REF = os.environ.get("AINVENTORY_SUPABASE_REF", "keihfchslgjetkmnmzra") -BASE = f"https://{REF}.supabase.co/rest/v1" -BWS = os.environ.get("BWS_BIN", "/run/current-system/sw/bin/bws") -SERVICE_ROLE_SECRET = "supabase.muse-dev2.service-role-key" -UA = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36" -PROFILE = "ainventory" +from pathlib import Path +from datetime import datetime, timezone +from urllib.parse import urlsplit, parse_qs +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from fleet_turso import Turso NOTE_KIND = "agent_note" @@ -181,78 +179,54 @@ def positive_int(text): # --------------------------------------------------------------- transport -def service_role_key(): - env = dict(os.environ) - if not env.get("BWS_ACCESS_TOKEN"): - token_file = os.path.expanduser("~/.config/bitwarden/access-token") - if os.path.exists(token_file): - with open(token_file) as f: - env["BWS_ACCESS_TOKEN"] = f.read().strip() - listing = subprocess.run( - [BWS, "secret", "list", "-o", "json"], - capture_output=True, - text=True, - env=env, - check=True, - ).stdout - try: - secret_id = next( - s["id"] for s in json.loads(listing) if s["key"] == SERVICE_ROLE_SECRET - ) - except StopIteration: - raise SystemExit(f"secret {SERVICE_ROLE_SECRET} not found in Bitwarden") - got = subprocess.run( - [BWS, "secret", "get", secret_id, "-o", "json"], - capture_output=True, - text=True, - env=env, - check=True, - ).stdout - return json.loads(got)["value"] - - -def rest(key, method, path, payload=None, prefer="return=representation"): - args = [ - "curl", - "-sS", - "-m", - "120", - "-A", - UA, - "-H", - f"apikey: {key}", - "-H", - f"Authorization: Bearer {key}", - ] +def database(): + return Turso() + + +def rest(db, method, path, payload=None, prefer="return=representation"): + """Narrow compatibility adapter for this script's four fixed operations.""" + parsed = urlsplit(path) + params = parse_qs(parsed.query) if method == "GET": - args += ["-H", f"Accept-Profile: {PROFILE}"] - else: - args += [ - "-H", - f"Content-Profile: {PROFILE}", - "-H", - "Content-Type: application/json", - "-H", - f"Prefer: {prefer}", - "-X", - method, - ] - if payload is not None: - args += ["-d", json.dumps(payload)] - args += [BASE + path, "-w", "\n%{http_code}"] - out = subprocess.run(args, capture_output=True, text=True, check=True).stdout - body, _, status = out.rpartition("\n") - if int(status) >= 400: - # A rejected write must never look like a landed one (the lesson - # from the gatherer's silent-HTTP-400 bug, #9999). - raise RuntimeError(f"{method} {path} -> HTTP {status}: {body[:400]}") - return json.loads(body) if body.strip() else None + if parsed.path == "/v_batches_awaiting_interpretation": + limit = int(params["limit"][0]) + rows = db.query("""SELECT b.id,b.source_kind,b.source_ref,b.ran_at,b.inserted_counts,b.note + FROM ainventory_ingest_batches b WHERE b.source_kind='gatherer' + AND EXISTS (SELECT 1 FROM json_each(b.inserted_counts) e + WHERE e.key IN ('measurement_events','price_events','provider_policies') + AND CAST(e.value AS REAL)>0) + AND NOT EXISTS (SELECT 1 FROM ainventory_interpretation_runs r WHERE r.ingest_batch_id=b.id) + ORDER BY b.ran_at ASC LIMIT ?""", [limit]) + elif parsed.path == "/ingest_batches": + value = params["id"][0] + if not value.startswith("eq."): raise ValueError("unsupported batch filter") + rows = db.query("SELECT id,inserted_counts FROM ainventory_ingest_batches WHERE id=?", [value[3:]]) + elif parsed.path == "/findings": + rows = db.query("SELECT source_ref FROM ainventory_findings") + else: + raise ValueError("unsupported read") + for row in rows: + if isinstance(row.get("inserted_counts"), str): + row["inserted_counts"] = json.loads(row["inserted_counts"]) + return rows + if method != "POST" or parsed.path not in ("/notes", "/findings", "/interpretation_runs"): + raise ValueError("unsupported write") + table = "ainventory_" + parsed.path[1:] + statements = [] + for source in payload: + row = {**source, "created_at": datetime.now(timezone.utc).isoformat()} + if not all(re.fullmatch(r"[a-z_]+", key) for key in row): + raise ValueError("invalid column") + columns = ",".join('"'+key+'"' for key in row) + statements.append((f"INSERT INTO {table} ({columns}) VALUES ({','.join('?' for _ in row)}) RETURNING id", list(row.values()))) + results = db.batch(statements, transaction=True) + return [row for group in results for row in group] if prefer != "return=minimal" else None # ------------------------------------------------------------------ verbs def cmd_awaiting(args): rows = rest( - service_role_key(), + database(), "GET", "/v_batches_awaiting_interpretation" "?select=id,source_kind,source_ref,ran_at,inserted_counts,note" @@ -367,12 +341,12 @@ def cmd_record(args): print(json.dumps({"dry_run": True, "would_record": plan}, indent=2)) return 0 - key = service_role_key() + key = database() batches = rest(key, "GET", batch_path) if not batches: raise SystemExit(f"no ingest batch {args.batch} in ainventory.ingest_batches") - # Each PostgREST request commits independently. If a later request + # Each Turso request commits independently. If a later request # fails, earlier append-only rows remain; the operator must inspect # this batch before retrying rather than assume rollback. note_row = rest( @@ -517,7 +491,7 @@ def cmd_import_findings(args): ) return 0 - key = service_role_key() + key = database() existing = rest(key, "GET", "/findings?select=source_ref&limit=5000") or [] seen = {r.get("source_ref") for r in existing} fresh = [r for r in rows if r["source_ref"] not in seen] diff --git a/scripts/fleet_turso.py b/scripts/fleet_turso.py new file mode 100644 index 0000000000..7664399d5e --- /dev/null +++ b/scripts/fleet_turso.py @@ -0,0 +1,119 @@ +"""Small Hrana client for fleet-platform operator scripts; no import-time I/O.""" +import json +import os +import subprocess +import urllib.request +import urllib.error +from urllib.parse import urlsplit + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + + +def open_request(request, timeout): + # Never forward the Fleet bearer token to a redirect destination. + return urllib.request.build_opener(NoRedirect()).open(request, timeout=timeout) + + +def argument(value): + if value is None: + return {"type": "null"} + if isinstance(value, bool): + return {"type": "integer", "value": str(int(value))} + if isinstance(value, int): + return {"type": "integer", "value": str(value)} + if isinstance(value, float): + return {"type": "float", "value": value} + if isinstance(value, (dict, list)): + value = json.dumps(value) + return {"type": "text", "value": str(value)} + + +class Turso: + def __init__(self): + self.url = os.environ.get("FLEET_TURSO_URL", "https://fleet-platform-dezren39.aws-us-east-1.turso.io").replace("libsql://", "https://").rstrip("/") + parsed = urlsplit(self.url) + if (parsed.scheme != "https" or parsed.hostname != "fleet-platform-dezren39.aws-us-east-1.turso.io" + or parsed.username or parsed.password or parsed.port not in (None, 443) + or parsed.path or parsed.query or parsed.fragment): + raise ValueError("FLEET_TURSO_URL must identify the fleet-platform HTTPS origin") + self.token = os.environ.get("FLEET_TURSO_TOKEN") + if not self.token: + result = subprocess.run(["fleet", "secrets", "get", "turso.fleet-platform-rw-token"], capture_output=True, text=True, timeout=60) + if result.returncode: + raise RuntimeError("could not resolve fleet-platform credential") + self.token = result.stdout.strip() + if not self.token: + raise RuntimeError("empty fleet-platform credential") + + def batch(self, statements, transaction=False): + # Single Hrana batch, conditional COMMIT and rollback on any error. + stmts = list(statements) + if transaction: + stmts = [("BEGIN IMMEDIATE", [])] + stmts + steps = [] + for i, (sql, args) in enumerate(stmts): + step = {"stmt": {"sql": sql, "args": [argument(x) for x in args], "want_rows": True}} + if i: + step["condition"] = {"type": "ok", "step": i - 1} + steps.append(step) + if transaction: + last = len(steps)-1 + steps.append({"condition": {"type": "ok", "step": last}, "stmt": {"sql": "COMMIT"}}) + steps.append({"condition": {"type": "not", "cond": {"type": "ok", "step": last + 1}}, "stmt": {"sql": "ROLLBACK"}}) + request = urllib.request.Request(self.url + "/v2/pipeline", data=json.dumps({"requests": [{"type": "batch", "batch": {"steps": steps}}, {"type": "close"}]}).encode(), headers={"Authorization": "Bearer " + self.token, "Content-Type": "application/json"}) + try: + with open_request(request, timeout=120) as response: + result = json.load(response)["results"][0] + except urllib.error.HTTPError as e: + raise RuntimeError(f"Turso HTTP {e.code}; outcome unverified, read back before retrying") from None + except (OSError, ValueError, KeyError, IndexError, TypeError) as e: + raise RuntimeError("Turso transport/response failure; outcome unverified, read back before retrying") from None + uncertain = "Turso response incomplete or rejected; outcome unverified, read back before retrying" + if not isinstance(result, dict) or result.get("type") != "ok": + raise RuntimeError(uncertain) + response = result.get("response") + if not isinstance(response, dict) or response.get("type") != "batch": + raise RuntimeError(uncertain) + batch = response.get("result") + if not isinstance(batch, dict): + raise RuntimeError(uncertain) + results, errors = batch.get("step_results"), batch.get("step_errors") + if (not isinstance(results, list) or not isinstance(errors, list) + or len(results) != len(steps) or len(errors) != len(steps)): + raise RuntimeError(uncertain) + def valid(r): + if not isinstance(r, dict) or not isinstance(r.get("cols"), list) or not isinstance(r.get("rows"), list): + return False + if not all(isinstance(c, dict) and isinstance(c.get("name"), str) for c in r["cols"]): + return False + return all(isinstance(row, list) and len(row) == len(r["cols"]) + and all(isinstance(v, dict) and v.get("type") in ("null", "integer", "float", "text", "blob") for v in row) + for row in r["rows"]) + if any(e is not None for e in errors): + rolled_back = transaction and errors[-1] is None and valid(results[-1]) + raise RuntimeError("Turso statement failed; rollback confirmed" if rolled_back else uncertain) + # Every data step (and BEGIN/COMMIT for atomic batches) must be evidenced. + expected = len(stmts) + (1 if transaction else 0) + if not all(valid(r) for r in results[:expected]) or (transaction and results[-1] is not None): + raise RuntimeError(uncertain) + try: + return [self.rows(r) for r in results[:len(stmts)]] + except (KeyError, ValueError, TypeError): + raise RuntimeError(uncertain) from None + + @staticmethod + def rows(result): + if result is None: + return [] + def value(v): + if v["type"] == "null": return None + if v["type"] == "integer": return int(v["value"]) + if v["type"] == "float": return float(v["value"]) + return v.get("value") + return [{c["name"]: value(v) for c, v in zip(result["cols"], row)} for row in result["rows"]] + + def query(self, sql, args=()): + return self.batch([(sql, args)])[0] diff --git a/scripts/tests/test_ainventory_interpretation.py b/scripts/tests/test_ainventory_interpretation.py index cd48d409f9..33fb891a31 100644 --- a/scripts/tests/test_ainventory_interpretation.py +++ b/scripts/tests/test_ainventory_interpretation.py @@ -245,3 +245,25 @@ def test_header_states_the_argument_contract(self): if __name__ == "__main__": unittest.main() + +class TursoAdapterTests(unittest.TestCase): + """Oracle: concrete SQLite selection and INSERT RETURNING semantics.""" + def test_awaiting_and_insert(self): + import sqlite3 + module=load_module() + class DB: + def __init__(self): + self.c=sqlite3.connect(':memory:');self.c.row_factory=sqlite3.Row + self.c.executescript('CREATE TABLE ainventory_ingest_batches(id,source_kind,source_ref,ran_at,inserted_counts,note); CREATE TABLE ainventory_interpretation_runs(id INTEGER PRIMARY KEY,ingest_batch_id); CREATE TABLE ainventory_notes(id INTEGER PRIMARY KEY,kind,body,author,created_at);') + def query(self,sql,args=()): return [dict(r) for r in self.c.execute(sql,args)] + def batch(self,statements,transaction=False): + with self.c: return [self.query(sql,args) for sql,args in statements] + db=DB() + for id,kind,counts in [('yes','gatherer','{"price_events":2}'),('empty','gatherer','{}'),('other','watcher','{"price_events":3}')]: + db.query('INSERT INTO ainventory_ingest_batches VALUES(?,?,NULL,?, ?,NULL)',[id,kind,'2026-11-18',counts]) + rows=module.rest(db,'GET','/v_batches_awaiting_interpretation?limit=20') + self.assertEqual([r['id'] for r in rows],['yes']) + self.assertEqual(rows[0]['inserted_counts'],{'price_events':2}) + result=module.rest(db,'POST','/notes',[{'kind':'agent_note','body':'test','author':'test'}]) + self.assertEqual(result,[{'id':1}]) + with self.assertRaises(ValueError): module.rest(db,'POST','/unknown',[{}]) diff --git a/scripts/tests/test_fleet_turso.py b/scripts/tests/test_fleet_turso.py new file mode 100644 index 0000000000..7e326f2a03 --- /dev/null +++ b/scripts/tests/test_fleet_turso.py @@ -0,0 +1,87 @@ +"""Oracle: Hrana typed values and fail-closed atomic batch structure.""" +import sys +from pathlib import Path +import json +import unittest +from unittest.mock import patch +sys.path.insert(0,str(Path(__file__).resolve().parents[1])) +from fleet_turso import Turso, argument + +class Response: + def __enter__(self): return self + def __exit__(self,*args): pass + def read(self): return json.dumps({'results':[{'type':'ok','response':{'type':'batch','result':{'step_errors':[None]*5,'step_results':[{'cols':[], 'rows':[]}]*4+[None]}}}]}).encode() + +class Tests(unittest.TestCase): + def test_types_and_rows(self): + self.assertEqual(argument(None), {'type':'null'}) + self.assertEqual(argument(5), {'type':'integer','value':'5'}) + self.assertEqual(argument({'x':1})['type'],'text') + self.assertEqual(Turso.rows({'cols':[{'name':'n'}],'rows':[[{'type':'integer','value':'5'}]]}),[{'n':5}]) + def test_atomic_batch(self): + db=Turso.__new__(Turso);db.url='https://example.invalid';db.token='test' + with patch('fleet_turso.open_request',return_value=Response()) as request: + db.batch([('INSERT INTO t VALUES (?)',[1]),('INSERT INTO t VALUES (?)',[2])],transaction=True) + steps=json.loads(request.call_args.args[0].data)['requests'][0]['batch']['steps'] + self.assertEqual(steps[0]['stmt']['sql'],'BEGIN IMMEDIATE') + self.assertEqual(steps[2]['condition'],{'type':'ok','step':1}) + self.assertEqual(steps[3]['stmt']['sql'],'COMMIT') + self.assertEqual(steps[3]['condition'],{'type':'ok','step':2}) + self.assertEqual(steps[4]['stmt']['sql'],'ROLLBACK') + self.assertEqual(steps[4]['condition'],{'type':'not','cond':{'type':'ok','step':3}}) + def test_destination_rejected_before_secret_lookup(self): + for url in ('https://other.turso.io', 'https://fleet-platform-dezren39.aws-us-east-1.turso.io@evil.example', 'https://fleet-platform-dezren39.aws-us-east-1.turso.io/x'): + with patch.dict('os.environ',{'FLEET_TURSO_URL':url}), patch('subprocess.run') as fetch: + with self.assertRaises(ValueError): Turso() + fetch.assert_not_called() + def test_ambiguous_transport_does_not_claim_rollback(self): + db=Turso.__new__(Turso);db.url='https://example.invalid';db.token='test' + with patch('fleet_turso.open_request',side_effect=TimeoutError()): + with self.assertRaisesRegex(RuntimeError,'outcome unverified'): + db.batch([('INSERT INTO t VALUES (?)',[1])],transaction=True) + def test_commit_error_rollback_proof(self): + db=Turso.__new__(Turso);db.url='https://example.invalid';db.token='test' + payload={'results':[{'type':'ok','response':{'type':'batch','result':{'step_errors':[None,None,{'message':'commit failed'},None],'step_results':[{'cols':[], 'rows':[]}, {'cols':[], 'rows':[]}, None, {'cols':[], 'rows':[]}]}}}]} + class FailedCommit(Response): + def read(self): return json.dumps(payload).encode() + with patch('fleet_turso.open_request',return_value=FailedCommit()): + with self.assertRaisesRegex(RuntimeError,'rollback confirmed'): + db.batch([('INSERT INTO t VALUES (?)',[1])],transaction=True) + payload['results'][0]['response']['result']['step_results'][-1]=None + with patch('fleet_turso.open_request',return_value=FailedCommit()): + with self.assertRaisesRegex(RuntimeError,'outcome unverified'): + db.batch([('INSERT INTO t VALUES (?)',[1])],transaction=True) + def test_missing_success_evidence_is_not_success(self): + db=Turso.__new__(Turso);db.url='https://example.invalid';db.token='test' + for results,errors in (([None]*4,[None]*4),([],[]),([{}, {}, {}, None],[None]*4),([{'cols':[],'rows':[]}]*2+[None,None],[None]*4)): + payload={'results':[{'type':'ok','response':{'type':'batch','result':{'step_errors':errors,'step_results':results}}}]} + class Incomplete(Response): + def read(self):return json.dumps(payload).encode() + with patch('fleet_turso.open_request',return_value=Incomplete()): + with self.assertRaisesRegex(RuntimeError,'outcome unverified'): + db.batch([('INSERT INTO t VALUES (?)',[1])],transaction=True) + def test_redirect_does_not_forward_bearer(self): + import http.server + import threading + import urllib.request + import urllib.error + from fleet_turso import open_request + received=[] + class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + received.append(self.path) + if self.path == '/start': + self.send_response(302) + self.send_header('Location',f'http://127.0.0.1:{self.server.server_port}/target') + else:self.send_response(200) + self.end_headers() + def log_message(self,*args): pass + server=http.server.HTTPServer(('127.0.0.1',0),Handler) + thread=threading.Thread(target=server.serve_forever,daemon=True);thread.start() + try: + req=urllib.request.Request(f'http://127.0.0.1:{server.server_port}/start',headers={'Authorization':'Bearer test'}) + with self.assertRaises(urllib.error.HTTPError) as caught:open_request(req,timeout=3) + self.assertEqual(caught.exception.code,302) + self.assertEqual(received,['/start']) + finally:server.shutdown();server.server_close();thread.join() +if __name__=='__main__':unittest.main()