From c65869191c06282ef038f8c2c758f449d290926e Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 10:12:20 -0800 Subject: [PATCH 01/18] feat(learning): import Hub SQLite history into PostgreSQL Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 836fcecf-e7a9-4975-acd2-bf761098f711 --- packages/learning/README.md | 5 +- packages/learning/src/cli.mjs | 25 + packages/learning/src/config.mjs | 118 +++++ .../src/providers/postgres-database.mjs | 17 + packages/learning/src/providers/postgres.mjs | 149 ++++++ packages/learning/src/providers/sqlite.mjs | 32 +- .../learning/test-database/postgres.test.mjs | 444 +++++++++++++++++- 7 files changed, 771 insertions(+), 19 deletions(-) diff --git a/packages/learning/README.md b/packages/learning/README.md index 378660be..046371a9 100644 --- a/packages/learning/README.md +++ b/packages/learning/README.md @@ -39,6 +39,7 @@ node /packages/learning/bin/replica-learning.mjs doctor | --- | --- | | `doctor` | Shows the scope, the provider, where data goes, and why each was chosen | | `migrate` | Sets up the package-owned PostgreSQL schema using a privileged environment-supplied URL | +| `import-sqlite --offline` | Copies a stopped Hub SQLite store and its migration mappings into PostgreSQL | | `grants add`, `grants list`, `grants withdraw` | Records, lists, and ends consent for purposes | | `redact ` | Removes a comment's text when a person asks: every version and its labels | | `redact --comment ` | Removes the same text for a Hub comment named by its Hub ID. It imports and labels nothing and needs no active grant. `--reason` defaults to the comment being deleted at its source. `removed` in the `--json` output counts the events whose text it removed, 0 when none was left. Run it only while no import or labeling of the same store is in progress | @@ -158,7 +159,9 @@ An operator can store learnings in an existing PostgreSQL database instead of a Before a runtime login uses the database, an operator runs `replica-learning migrate` with `REPLICA_LEARNING_MIGRATION_DATABASE_URL` set to a privileged connection URL. This command does not read the runtime URL or learning config. It creates the `replica_learning` schema, tables, indexes, and its migration ledger in a transaction. Retrying, including concurrent retries, is safe. Run it again before using a package version with new migrations. The runtime checks the ledger but never creates or migrates schema objects. -The migration login needs permission to create the schema and own its objects. Give a separate runtime login only `USAGE` on `replica_learning`, `SELECT` on its migration ledger, `SELECT`, `INSERT`, and `UPDATE` on records, `SELECT` and `INSERT` on memory versions, and `USAGE` on their identity sequences. After each migration, grant these privileges on newly created objects as needed. Restrict database access to trusted hosts: scope is a package-level boundary, not database row-level authorization. +The migration login needs permission to create the schema and own its objects. Give a separate runtime login only `USAGE` on `replica_learning`, `SELECT` on its migration ledger, `SELECT`, `INSERT`, and `UPDATE` on records, `SELECT` and `INSERT` on memory versions and its scope-mapping and SQLite-import tables, and `USAGE` on their identity sequences. After each migration, grant these privileges on newly created objects as needed. Restrict database access to trusted hosts: scope is a package-level boundary, not database row-level authorization. + +To move an existing Hub SQLite store, stop Hub and every older client, set the runtime URL in a protected environment, and run `replica-learning import-sqlite --offline --dir --repository github.com/repositories/ --legacy-repository github.com/repositories/`. The command verifies and reconciles the source scope, then copies its records, version history, and historical mappings in one PostgreSQL transaction. A retry of the same source is safe; a changed source or an occupied destination scope is refused. Other repository scopes in the database are unaffected. Verify the destination before switching Hub. Keep older clients offline: the retained SQLite copy is not synchronized and can still contain private or later-redacted text. PostgreSQL stores the exact record JSON and indexes scope, IDs, time, episode, and audit operation. A write locks every affected scope until its transaction ends, and stores records and their audit entries together. Memory versions also check the expected prior digest. Redaction removes the payload from the current row, but old row versions may retain it until vacuum. Write-ahead logs and backups can retain it longer. Operators must set vacuum, WAL, backup, and replica retention policies to meet their deletion requirements; redaction does not erase those copies immediately. diff --git a/packages/learning/src/cli.mjs b/packages/learning/src/cli.mjs index e75548a1..331e248c 100644 --- a/packages/learning/src/cli.mjs +++ b/packages/learning/src/cli.mjs @@ -5,6 +5,7 @@ import { parseArgs } from "node:util" import { decodeUtf8, parseJson } from "./canonical-json.mjs" import { LearningError } from "./errors.mjs" import { + importSqliteStore, openConsolidator, openLabeler, openLegacyRedactionStore, @@ -44,6 +45,7 @@ Inspect migrate Set up PostgreSQL using REPLICA_LEARNING_MIGRATION_DATABASE_URL migrate-scope --offline Confirm and migrate a legacy store after stopping older clients [--empty] Confirm that a new custom-provider store is empty + import-sqlite --offline Copy a stopped Hub SQLite store into PostgreSQL copilot status Whether Copilot answers here, as whom, and with which models Consent (a person decides; --by github:) @@ -209,6 +211,19 @@ export async function main( out(result, `PostgreSQL learning schema is at migration ${result.version}.`) return 0 } + if ( + positionals[0] === "import-sqlite" && + (positionals.length !== 1 || + !values.offline || + !values.dir || + !values.repository || + !/^github\.com\/repositories\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test( + values["legacy-repository"] ?? "", + )) + ) + throw new UsageError( + "Stop older clients, then use import-sqlite --offline with --dir, --repository, and the Hub UUID as --legacy-repository.", + ) if ( values["legacy-redaction"] && (positionals.length !== 1 || @@ -309,6 +324,16 @@ async function run(session) { return doctor(session) case "migrate-scope": return migrateScope(session) + case "import-sqlite": { + const result = await importSqliteStore(session.environment, { clock: session.clock }) + session.out( + result, + result.alreadyImported + ? "SQLite history was already imported." + : "SQLite history was imported.", + ) + return 0 + } case "grants": if (sub === "list") return listGrants(session) if (sub === "withdrawals") return listWithdrawals(session) diff --git a/packages/learning/src/config.mjs b/packages/learning/src/config.mjs index a77c9232..23961caa 100644 --- a/packages/learning/src/config.mjs +++ b/packages/learning/src/config.mjs @@ -435,6 +435,22 @@ export async function openLearningStore(environment, { clock = Date.now } = {}) ) const { provider, source } = await openProvider(environment) try { + if ( + environment.config.memory?.requireImport && + !(await provider.hasSqliteImport?.(environment.scope)) + ) + throw new LearningError( + "conflict", + "This repository has existing learning files. Import its SQLite history before using PostgreSQL.", + ) + if ( + environment.hosted && + environment.legacyScope && + /^repositories\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test( + environment.legacyScope.repository, + ) + ) + await provider.registerLegacyScope?.(environment.legacyScope, environment.scope) let result = null if ( !environment.hosted && @@ -549,6 +565,15 @@ export async function openLegacyRedactionStore(environment, { clock = Date.now } "The store cannot identify the migrated repository scope for redaction.", ) const migration = await provider.scopeMigrationFrom?.(environment.scope) + if ( + (!migration && typeof provider.hasSqliteImport === "function") || + (environment.config.memory?.requireImport && + (!migration || !(await provider.hasSqliteImport?.(migration.newScope)))) + ) + throw new LearningError( + "conflict", + "The repository's SQLite history has not been imported for legacy redaction.", + ) if (migration) { const target = scopeFromName(`github.com/${migration.newScope?.repository}`) if ( @@ -607,6 +632,99 @@ export async function openProvider(environment) { return { provider, source: `module ${choice.module}` } } +/** + * Copy one stopped Hub SQLite store into PostgreSQL without removing the source. Its numeric + * scope and historical mappings must be intact before the destination is made visible. + */ +export async function importSqliteStore(environment, { clock = Date.now } = {}) { + const choice = environment.config.memory?.provider ?? "sqlite" + if ( + !environment.hosted || + !environment.scope || + !environment.legacyScope || + !environment.configFound || + (choice !== "sqlite" && choice?.builtin !== "sqlite") + ) + throw new LearningError( + "invalid_input", + "Import needs an existing Hub SQLite store, its numeric repository ID, and its old Hub scope.", + ) + const destination = createPostgresMemoryProvider({ + connectionString: environment.env.REPLICA_LEARNING_DATABASE_URL, + }) + let source + async function snapshot() { + const scopes = await source.storedScopes() + if (scopes.some((scope) => canonicalJson(scope) !== canonicalJson(environment.scope))) + throw new LearningError( + "conflict", + "The SQLite store contains another repository scope. Reconcile it before import.", + ) + return { + records: Object.fromEntries( + await Promise.all( + Object.keys(STREAMS).map(async (stream) => [ + stream, + await source.readRecords(stream, { scope: environment.scope }), + ]), + ), + ), + memories: await source.readMemoryVersions({ scope: environment.scope }), + migrations: await source.scopeMigrations(environment.scope), + } + } + try { + await destination.hasSqliteImport(environment.scope) + const { store } = await openLearningStore(environment, { clock }) + try { + const verified = await store.verify({ + scope: environment.scope, + principal: { kind: "system", id: "system:sqlite-import" }, + }) + if (!verified.ok) + throw new LearningError( + "storage_corrupt", + `SQLite import refused: ${verified.problems.join("; ")}`, + ) + } finally { + await store.close() + } + source = (await openProvider(environment)).provider + const original = await snapshot() + if ( + !original.migrations.some( + (migration) => canonicalJson(migration.oldScope) === canonicalJson(environment.legacyScope), + ) + ) + throw new LearningError( + "conflict", + "The SQLite store has no mapping for this Hub repository.", + ) + return await destination.importSqlite({ + scope: environment.scope, + ...original, + sourceDigest: digestOf(original), + beforeCommit: async () => { + if ( + canonicalJson(await snapshot()) !== canonicalJson(original) || + canonicalJson(await readConfig(environment.configPath)) !== + canonicalJson(environment.config) + ) + throw new LearningError( + "conflict", + "The SQLite source changed during import. Try again offline.", + ) + }, + }) + } finally { + try { + await source?.close() + } finally { + await destination.close() + } + } +} + /** * Copy one offline legacy store into SQLite without changing the source. The caller must stop * older clients first; provider contracts cannot prevent an old client from writing later. diff --git a/packages/learning/src/providers/postgres-database.mjs b/packages/learning/src/providers/postgres-database.mjs index ccb0fa32..12151c1a 100644 --- a/packages/learning/src/providers/postgres-database.mjs +++ b/packages/learning/src/providers/postgres-database.mjs @@ -41,6 +41,23 @@ const MIGRATIONS = [ create index memory_versions_by_operation on replica_learning.memory_versions (scope_key, operation); `, }, + { + version: 2, + sql: ` + create table replica_learning.scope_migrations ( + seq bigint generated always as identity primary key, + old_scope_key text collate "C" not null unique, + new_scope_key text collate "C" not null, + metadata text not null + ); + create index scope_migrations_by_target + on replica_learning.scope_migrations (new_scope_key, seq); + create table replica_learning.sqlite_imports ( + scope_key text collate "C" primary key, + source_digest text not null + ); + `, + }, ] function checksum(migration) { diff --git a/packages/learning/src/providers/postgres.mjs b/packages/learning/src/providers/postgres.mjs index 3da115e0..3a91de93 100644 --- a/packages/learning/src/providers/postgres.mjs +++ b/packages/learning/src/providers/postgres.mjs @@ -181,6 +181,7 @@ export function createPostgresMemoryProvider({ connectionString } = {}) { return { atomicCollectionImport: true, + atomicMigrationRedactions: true, manifest() { return { @@ -272,6 +273,154 @@ export function createPostgresMemoryProvider({ connectionString } = {}) { return select(queryOptions, { table: "memory_versions", time: "updated_at" }) }, + async scopeMigrations(scope) { + const { rows } = await query( + "select metadata from replica_learning.scope_migrations where new_scope_key = $1 order by seq", + [canonicalJson(scope)], + ) + try { + return rows.map((row) => JSON.parse(row.metadata)) + } catch { + throw new LearningError("storage_corrupt", "A PostgreSQL migration mapping is invalid.") + } + }, + + async scopeMigrationFrom(scope) { + const { rows } = await query( + "select metadata from replica_learning.scope_migrations where old_scope_key = $1", + [canonicalJson(scope)], + ) + try { + return rows.length ? JSON.parse(rows[0].metadata) : null + } catch { + throw new LearningError("storage_corrupt", "A PostgreSQL migration mapping is invalid.") + } + }, + + async registerLegacyScope(oldScope, newScope) { + const oldKey = canonicalJson(oldScope) + const newKey = canonicalJson(newScope) + const saved = await query( + "select new_scope_key from replica_learning.scope_migrations where old_scope_key = $1", + [oldKey], + ) + if (saved.rows.length) { + if (saved.rows[0].new_scope_key !== newKey) + throw new LearningError("conflict", "The old scope belongs to another repository.") + return + } + return transaction([oldKey, newKey], async (client) => { + const previous = await client.query( + "select new_scope_key from replica_learning.scope_migrations where old_scope_key = $1", + [oldKey], + ) + if (previous.rows.length) { + if (previous.rows[0].new_scope_key !== newKey) + throw new LearningError("conflict", "The old scope belongs to another repository.") + return + } + const old = await client.query( + `select 1 from replica_learning.records where scope_key = $1 + union all select 1 from replica_learning.memory_versions where scope_key = $1 + limit 1`, + [oldKey], + ) + if (old.rows.length) + throw new LearningError("conflict", "The old repository scope still contains data.") + await client.query( + `insert into replica_learning.scope_migrations (old_scope_key, new_scope_key, metadata) + values ($1, $2, $3)`, + [oldKey, newKey, JSON.stringify({ oldScope, newScope, digestMappings: [] })], + ) + }) + }, + + async hasSqliteImport(scope) { + const { rows } = await query( + "select 1 from replica_learning.sqlite_imports where scope_key = $1", + [canonicalJson(scope)], + ) + return rows.length > 0 + }, + + async importSqlite({ scope, records, memories, migrations, sourceDigest, beforeCommit }) { + const key = canonicalJson(scope) + const writes = batchWrites(records) + assertStorable(memories) + for (const items of writes.values()) + if (items.some((record) => canonicalJson(record.scope) !== key)) + throw new LearningError("storage_corrupt", "The source contains another scope.") + if (memories.some((record) => canonicalJson(record.scope) !== key)) + throw new LearningError("storage_corrupt", "The source contains another scope.") + for (const migration of migrations) + if ( + !migration.oldScope || + canonicalJson(migration.oldScope) === key || + canonicalJson(migration.newScope) !== key + ) + throw new LearningError("storage_corrupt", "A repository migration mapping is invalid.") + return transaction([key], async (client) => { + const prior = await client.query( + "select source_digest from replica_learning.sqlite_imports where scope_key = $1", + [key], + ) + if (prior.rows.length) { + if (prior.rows[0].source_digest !== sourceDigest) + throw new LearningError( + "conflict", + "The SQLite source changed after import. Keep it offline and investigate.", + ) + return { alreadyImported: true } + } + const occupied = await client.query( + `select 1 from replica_learning.records where scope_key = $1 + union all select 1 from replica_learning.memory_versions where scope_key = $1 + union all select 1 from replica_learning.scope_migrations where new_scope_key = $1 + limit 1`, + [key], + ) + if (occupied.rows.length) + throw new LearningError("conflict", "The PostgreSQL repository already contains data.") + for (const [stream, items] of writes) await insert(client, stream, items) + const latest = new Map() + for (const record of memories) { + const previous = latest.get(record.id) + if ( + record.version !== (previous?.version ?? 0) + 1 || + (record.previousDigest ?? null) !== (previous?.digest ?? null) + ) + throw new LearningError("storage_corrupt", "A source memory history is invalid.") + await client.query( + `insert into replica_learning.memory_versions + (id, version, scope_key, updated_at, operation, digest, body) + values ($1, $2, $3, $4, $5, $6, $7)`, + [ + record.id, + record.version, + key, + text(record.updatedAt), + text(record.operation), + record.digest, + JSON.stringify(record), + ], + ) + latest.set(record.id, record) + } + for (const migration of migrations) + await client.query( + `insert into replica_learning.scope_migrations (old_scope_key, new_scope_key, metadata) + values ($1, $2, $3)`, + [canonicalJson(migration.oldScope), key, JSON.stringify(migration)], + ) + await beforeCommit() + await client.query( + "insert into replica_learning.sqlite_imports (scope_key, source_digest) values ($1, $2)", + [key, sourceDigest], + ) + return { alreadyImported: false } + }) + }, + async redactRecord(stream, record) { if (stream !== "events") throw new LearningError("invalid_input", "Only events can be redacted.") diff --git a/packages/learning/src/providers/sqlite.mjs b/packages/learning/src/providers/sqlite.mjs index 074ec4c8..d00bddb8 100644 --- a/packages/learning/src/providers/sqlite.mjs +++ b/packages/learning/src/providers/sqlite.mjs @@ -229,6 +229,15 @@ export function createSqliteMemoryProvider({ directory, file = "learning.sqlite" }) } + function storedScopes() { + const database = connect({ create: false }) + if (!database) return [] + return database + .prepare("select scope_key from records union select scope_key from memory_versions") + .all() + .map((row) => JSON.parse(row.scope_key)) + } + return { atomicMigrationRedactions: true, atomicMigrationFence: true, @@ -336,19 +345,16 @@ export function createSqliteMemoryProvider({ directory, file = "learning.sqlite" }, async legacyScopes() { - const database = connect({ create: false }) - if (!database) return [] - const rows = database - .prepare("select scope_key from records union select scope_key from memory_versions") - .all() - return rows - .map((row) => JSON.parse(row.scope_key)) - .filter( - (scope) => - scope.host === "github.com" && - typeof scope.repository === "string" && - !/^repositories\/[1-9][0-9]*$/.test(scope.repository), - ) + return storedScopes().filter( + (scope) => + scope.host === "github.com" && + typeof scope.repository === "string" && + !/^repositories\/[1-9][0-9]*$/.test(scope.repository), + ) + }, + + async storedScopes() { + return storedScopes() }, async scopeMigrations(scope) { diff --git a/packages/learning/test-database/postgres.test.mjs b/packages/learning/test-database/postgres.test.mjs index bc7806c0..7e2fa0d9 100644 --- a/packages/learning/test-database/postgres.test.mjs +++ b/packages/learning/test-database/postgres.test.mjs @@ -1,7 +1,17 @@ import assert from "node:assert/strict" -import { spawnSync } from "node:child_process" +import { execFileSync, spawnSync } from "node:child_process" import { randomBytes } from "node:crypto" +import { + chmodSync, + copyFileSync, + mkdirSync, + readFileSync, + readdirSync, + rmSync, + writeFileSync, +} from "node:fs" import { createConnection, createServer } from "node:net" +import path from "node:path" import { after, afterEach, it } from "node:test" import { fileURLToPath } from "node:url" import pg from "pg" @@ -14,8 +24,11 @@ import { } from "../conformance/index.mjs" import { main } from "../src/cli.mjs" import { openProvider } from "../src/config.mjs" +import { STREAMS } from "../src/provider-contract.mjs" import { migratePostgres, postgresPool } from "../src/providers/postgres-database.mjs" import { createPostgresMemoryProvider } from "../src/providers/postgres.mjs" +import { createSqliteMemoryProvider } from "../src/providers/sqlite.mjs" +import { migrateRepositoryScope } from "../src/scope-migration.mjs" import { createLearningStore } from "../src/store.mjs" import { validateRecord } from "../src/validate.mjs" @@ -26,6 +39,53 @@ const admin = new pg.Pool({ connectionString: baseUrl }) const databases = [] const roles = [] const providers = [] +const workspaces = [] + +function importWorkspace() { + const root = path.resolve(`.learning-import-tests-${randomBytes(12).toString("hex")}`) + mkdirSync(root, { mode: 0o700 }) + workspaces.push(root) + execFileSync("git", ["init", "-q", root]) + writeFileSync(path.join(root, ".gitignore"), ".replica/\n") + const source = path.join(root, ".replica", "source") + const reference = path.join(root, ".replica", "reference") + for (const directory of [source, reference]) { + mkdirSync(directory, { recursive: true, mode: 0o700 }) + copyFileSync( + new URL("../test/fixtures/legacy-hub-scope.sqlite", import.meta.url), + path.join(directory, "learning.sqlite"), + ) + chmodSync(path.join(directory, "learning.sqlite"), 0o600) + writeFileSync( + path.join(directory, "config.json"), + JSON.stringify({ + schemaVersion: "replica.learning-config/v1", + memory: { provider: "sqlite" }, + }), + ) + } + return { root, source, reference } +} + +async function learningCommand(root, url, args) { + let stdout = "" + let stderr = "" + const code = await main(args, { + cwd: root, + env: { REPLICA_LEARNING_DATABASE_URL: url, PATH: "" }, + stdout: { write: (text) => (stdout += text) }, + stderr: { write: (text) => (stderr += text) }, + }) + return { code, stdout, stderr } +} + +async function snapshot(opened, scope) { + const query = { scope } + const records = {} + for (const stream of Object.keys(STREAMS)) + records[stream] = await opened.readRecords(stream, query) + return { records, versions: await opened.readMemoryVersions(query) } +} async function database({ migrate = true } = {}) { const name = `replica_test_${randomBytes(12).toString("hex")}` @@ -66,6 +126,7 @@ afterEach(async () => { errors.push(error) } } + for (const root of workspaces.splice(0)) rmSync(root, { recursive: true, force: true }) if (errors.length) throw new AggregateError(errors, "Could not remove test resources.") }) after(async () => admin.end()) @@ -75,6 +136,363 @@ memoryProviderConformance({ createProvider: async () => provider(await database()), }) +it("redacts a new PostgreSQL repository using its old Hub UUID", async () => { + const root = path.resolve(`.learning-hub-tests-${randomBytes(12).toString("hex")}`) + mkdirSync(root, { mode: 0o700 }) + workspaces.push(root) + execFileSync("git", ["init", "-q", root]) + writeFileSync(path.join(root, ".gitignore"), ".replica/\n") + const directory = path.join(root, ".replica", "learning") + mkdirSync(directory, { recursive: true, mode: 0o700 }) + writeFileSync( + path.join(directory, "config.json"), + JSON.stringify({ + schemaVersion: "replica.learning-config/v1", + memory: { provider: "postgres" }, + }), + ) + const hubId = "11111111-2222-4333-8444-555555555555" + const log = weekOneLog({ repository: `repositories/${hubId}` }) + for (const call of log.calls) call.result.target.repositoryId = hubId + writeFileSync(path.join(root, "log.json"), JSON.stringify(log)) + const url = await database() + const scope = { host: "github.com", repository: "repositories/123456" } + const flags = [ + "--dir", + directory, + "--repository", + `github.com/${scope.repository}`, + "--legacy-repository", + `github.com/repositories/${hubId}`, + "--json", + ] + const grant = await learningCommand(root, url, [ + "grants", + "add", + "--purpose", + "review", + "--basis", + "Synthetic consent for review.", + "--by", + "github:ana-designer", + ...flags, + ]) + assert.equal(grant.code, 0, grant.stderr) + const imported = await learningCommand(root, url, [ + "import", + "hub-comments", + "log.json", + "--grant", + JSON.parse(grant.stdout).id, + "--actor", + "agent:copilot", + ...flags, + ]) + assert.equal(imported.code, 0, imported.stderr) + const opened = provider(url) + const events = await opened.readRecords("events", { scope }) + const comment = events.find((event) => event.payload?.commentId === 103) + const other = events.find((event) => event.payload?.commentId === 101) + assert.ok(comment?.payload?.body) + assert.ok(other?.payload?.body) + + const redact = [ + "redact", + "--comment", + "103", + "--by", + "github:ana-designer", + "--dir", + directory, + "--legacy-repository", + `github.com/repositories/${hubId}`, + "--legacy-redaction", + "--json", + ] + const removed = await learningCommand(root, url, redact) + assert.equal(removed.code, 0, removed.stderr) + assert.ok(JSON.parse(removed.stdout).removed > 0) + const after = await opened.readRecords("events", { scope }) + assert.equal(after.find((event) => event.id === comment.id).payload, undefined) + assert.deepEqual( + after.find((event) => event.id === other.id), + other, + ) + const repeated = await learningCommand(root, url, redact) + assert.equal(repeated.code, 0, repeated.stderr) + assert.equal(JSON.parse(repeated.stdout).removed, 0) +}) + +it("leaves legacy SQLite unchanged when PostgreSQL is unavailable", async () => { + const { root, source, reference } = importWorkspace() + const oldScope = { + host: "github.com", + repository: "repositories/11111111-2222-4333-8444-555555555555", + } + const original = createSqliteMemoryProvider({ directory: reference }) + try { + assert.ok((await original.readRecords("events", { scope: oldScope })).length > 0) + assert.equal(await original.scopeMigrationFrom(oldScope), null) + } finally { + await original.close() + } + const names = readdirSync(source).sort() + const contents = names.map((name) => readFileSync(path.join(source, name))) + let attempts = 0 + const server = createServer((socket) => { + attempts++ + socket.destroy() + }) + await new Promise((resolve, reject) => { + server.once("error", reject) + server.listen(0, "127.0.0.1", resolve) + }) + try { + const url = `postgresql://test:test@127.0.0.1:${server.address().port}/postgres` + const result = await learningCommand(root, url, [ + "import-sqlite", + "--offline", + "--dir", + source, + "--repository", + "github.com/repositories/123456", + "--legacy-repository", + `github.com/${oldScope.repository}`, + ]) + assert.notEqual(result.code, 0) + assert.match(result.stderr, /unavailable/i) + assert.ok(attempts > 0) + assert.deepEqual(readdirSync(source).sort(), names) + assert.deepEqual( + names.map((name) => readFileSync(path.join(source, name))), + contents, + ) + } finally { + await new Promise((resolve, reject) => + server.close((error) => (error ? reject(error) : resolve())), + ) + } +}) + +it("imports Hub history offline, preserves mappings and redactions, and refuses a changed retry", async () => { + const { root, source, reference } = importWorkspace() + const url = await database() + const oldScope = { + host: "github.com", + repository: "repositories/11111111-2222-4333-8444-555555555555", + } + const scope = { host: "github.com", repository: "repositories/123456" } + const flags = [ + "--dir", + source, + "--repository", + `github.com/${scope.repository}`, + "--legacy-repository", + `github.com/${oldScope.repository}`, + ] + const target = provider(url) + const expected = createSqliteMemoryProvider({ directory: reference }) + const sourceProvider = createSqliteMemoryProvider({ directory: source }) + try { + const original = await snapshot(sourceProvider, oldScope) + assert.ok(original.records.events.some((event) => event.redaction && !event.payload)) + assert.deepEqual( + original.versions.map((version) => version.state), + ["proposed", "accepted"], + ) + await migrateRepositoryScope({ + provider: expected, + oldScope, + newScope: scope, + }) + const expectedHistory = await snapshot(expected, scope) + const expectedMapping = await expected.scopeMigrationFrom(oldScope) + assert.ok(expectedMapping.digestMappings.length > 0) + + const online = await learningCommand(root, url, ["import-sqlite", ...flags]) + assert.notEqual(online.code, 0) + assert.deepEqual(await snapshot(target, scope), { + records: Object.fromEntries(Object.keys(STREAMS).map((stream) => [stream, []])), + versions: [], + }) + + const imported = await learningCommand(root, url, ["import-sqlite", "--offline", ...flags]) + assert.equal(imported.code, 0, imported.stderr) + assert.deepEqual(await snapshot(target, scope), expectedHistory) + assert.deepEqual(await target.scopeMigrationFrom(oldScope), expectedMapping) + const oldSource = await snapshot(sourceProvider, oldScope) + const newSource = await snapshot(sourceProvider, scope) + if (newSource.records.events.length) assert.deepEqual(newSource, expectedHistory) + else assert.deepEqual(oldSource, original) + + const retry = await learningCommand(root, url, ["import-sqlite", "--offline", ...flags]) + assert.equal(retry.code, 0, retry.stderr) + assert.deepEqual(await snapshot(target, scope), expectedHistory) + assert.deepEqual(await target.scopeMigrationFrom(oldScope), expectedMapping) + + const sourceScope = newSource.records.events.length ? scope : oldScope + const store = await createLearningStore({ provider: sourceProvider }) + await store.addGrant( + { scope: sourceScope, principal: { kind: "human", id: "github:later" } }, + { + purposes: ["review"], + sources: ["hub_review_comments"], + basis: "Later consent.", + }, + ) + const changed = await learningCommand(root, url, ["import-sqlite", "--offline", ...flags]) + assert.notEqual(changed.code, 0) + assert.deepEqual(await snapshot(target, scope), expectedHistory) + assert.deepEqual(await target.scopeMigrationFrom(oldScope), expectedMapping) + + const pgConfig = path.join(root, ".replica", "postgres") + mkdirSync(pgConfig, { recursive: true, mode: 0o700 }) + writeFileSync( + path.join(pgConfig, "config.json"), + JSON.stringify({ + schemaVersion: "replica.learning-config/v1", + memory: { provider: "postgres" }, + }), + ) + const redaction = await learningCommand(root, url, [ + "redact", + "--comment", + "103", + "--by", + "github:ana-designer", + "--json", + "--dir", + pgConfig, + "--legacy-repository", + `github.com/${oldScope.repository}`, + "--legacy-redaction", + ]) + assert.equal(redaction.code, 0, redaction.stderr) + assert.ok(JSON.parse(redaction.stdout).removed > 0) + const after = await snapshot(target, scope) + const beforeEvent = expectedHistory.records.events.find( + (event) => event.payload?.commentId === 103, + ) + assert.ok(beforeEvent) + assert.equal( + after.records.events.find((event) => event.id === beforeEvent.id).payload, + undefined, + ) + const repeatedRedaction = await learningCommand(root, url, [ + "redact", + "--comment", + "103", + "--by", + "github:ana-designer", + "--json", + "--dir", + pgConfig, + "--legacy-repository", + `github.com/${oldScope.repository}`, + "--legacy-redaction", + ]) + assert.equal(repeatedRedaction.code, 0, repeatedRedaction.stderr) + assert.equal(JSON.parse(repeatedRedaction.stdout).removed, 0) + } finally { + await expected.close() + await sourceProvider.close() + } +}) + +it("refuses unrelated history in the same scope but preserves other scopes", async () => { + const { root, source } = importWorkspace() + const url = await database() + const secondUrl = await database() + const target = provider(url) + const second = provider(secondUrl) + const scope = { host: "github.com", repository: "repositories/123456" } + const other = { host: "github.com", repository: "repositories/987654" } + await target.appendRecords("grants", [{ id: "unrelated-same", digest: "sha256:same", scope }]) + await second.appendRecords("grants", [ + { id: "unrelated-other", digest: "sha256:other", scope: other }, + ]) + const before = await snapshot(target, scope) + const otherBefore = await snapshot(second, other) + const result = await learningCommand(root, url, [ + "import-sqlite", + "--offline", + "--dir", + source, + "--repository", + "github.com/repositories/123456", + "--legacy-repository", + "github.com/repositories/11111111-2222-4333-8444-555555555555", + ]) + assert.notEqual(result.code, 0) + assert.match(result.stderr, /conflict|populated|destination/i) + assert.deepEqual(await snapshot(target, scope), before) + const differentScope = await learningCommand(root, secondUrl, [ + "import-sqlite", + "--offline", + "--dir", + source, + "--repository", + "github.com/repositories/123456", + "--legacy-repository", + "github.com/repositories/11111111-2222-4333-8444-555555555555", + ]) + assert.equal(differentScope.code, 0, differentScope.stderr) + assert.deepEqual(await snapshot(second, other), otherBefore) + const imported = await snapshot(second, scope) + assert.ok(imported.records.events.length > 0) + assert.equal(imported.versions.length, 2) +}) + +it("rolls back a failed PostgreSQL import and permits a retry", async () => { + const { root, source } = importWorkspace() + const url = await database() + const db = new pg.Client({ connectionString: url }) + await db.connect() + try { + await db.query("create sequence replica_learning.test_import_attempt") + await db.query(` + create function replica_learning.test_refuse_events() returns trigger language plpgsql as $$ + begin + perform nextval('replica_learning.test_import_attempt'); + raise exception 'test import failure'; + end $$ + `) + await db.query(` + create trigger test_refuse_events before insert on replica_learning.records + for each row when (new.stream = 'events') execute function replica_learning.test_refuse_events() + `) + const args = [ + "import-sqlite", + "--offline", + "--dir", + source, + "--repository", + "github.com/repositories/123456", + "--legacy-repository", + "github.com/repositories/11111111-2222-4333-8444-555555555555", + ] + const failed = await learningCommand(root, url, args) + assert.notEqual(failed.code, 0) + const attempt = await db.query("select is_called from replica_learning.test_import_attempt") + assert.equal(attempt.rows[0].is_called, true) + const records = await db.query("select count(*)::int as count from replica_learning.records") + const versions = await db.query( + "select count(*)::int as count from replica_learning.memory_versions", + ) + assert.equal(records.rows[0].count, 0) + assert.equal(versions.rows[0].count, 0) + await db.query("drop trigger test_refuse_events on replica_learning.records") + const retried = await learningCommand(root, url, args) + assert.equal(retried.code, 0, retried.stderr) + const target = provider(url) + const scope = { host: "github.com", repository: "repositories/123456" } + assert.ok((await target.readRecords("events", { scope })).length > 0) + assert.equal((await target.readMemoryVersions({ scope })).length, 2) + } finally { + await db.end() + } +}) + it("migrates only with the migration URL and lets a limited runtime login use the store", async () => { const url = await database({ migrate: false }) const role = `replica_test_${randomBytes(12).toString("hex")}` @@ -123,7 +541,21 @@ it("migrates only with the migration URL and lets a limited runtime login use th await db.query(`grant select on replica_learning.schema_migrations to "${role}"`) await db.query(`grant select, insert, update on replica_learning.records to "${role}"`) await db.query(`grant select, insert on replica_learning.memory_versions to "${role}"`) + await db.query( + `grant select on replica_learning.scope_migrations, replica_learning.sqlite_imports to "${role}"`, + ) await db.query(`grant usage on all sequences in schema replica_learning to "${role}"`) + const oldScope = { repository: "old" } + const scope = { repository: "a" } + const mapping = { oldScope, newScope: scope, digestMappings: [] } + await db.query( + "insert into replica_learning.scope_migrations (old_scope_key, new_scope_key, metadata) values ($1, $2, $3)", + [JSON.stringify(oldScope), JSON.stringify(scope), JSON.stringify(mapping)], + ) + await db.query( + "insert into replica_learning.sqlite_imports (scope_key, source_digest) values ($1, $2)", + [JSON.stringify(scope), "sha256:source"], + ) const restricted = new pg.Client({ connectionString: runtimeUrl.href }) await restricted.connect() try { @@ -164,6 +596,10 @@ it("migrates only with the migration URL and lets a limited runtime login use th } assert.deepEqual(await runtime.redactRecord("events", redacted), { redacted: true }) assert.deepEqual(await runtime.readRecords("events", { scope: record.scope }), [redacted]) + assert.deepEqual(await runtime.scopeMigrations(scope), [mapping]) + assert.deepEqual(await runtime.scopeMigrationFrom(oldScope), mapping) + assert.equal(await runtime.hasSqliteImport(scope), true) + assert.equal(await runtime.hasSqliteImport(oldScope), false) } finally { await db.end() } @@ -182,10 +618,8 @@ it("refuses a changed migration ledger rather than using or repairing it", async }) await assert.rejects(migratePostgres({ connectionString: url }), { code: "storage_corrupt" }) const { rows } = await db.query("select checksum from replica_learning.schema_migrations") - assert.deepEqual( - rows.map((row) => row.checksum), - ["changed"], - ) + assert.ok(rows.length > 0) + assert.ok(rows.every((row) => row.checksum === "changed")) } finally { await db.end() } From 958b7f2e3eb37b7e7ce7798f5a09517d7d173adb Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 10:13:10 -0800 Subject: [PATCH 02/18] feat(hub): use a dedicated learning database Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 836fcecf-e7a9-4975-acd2-bf761098f711 --- hub/.devcontainer/compose.yaml | 4 + .../decision-walkthrough.compose.yaml | 1 + hub/.devcontainer/learning-role.sql | 2 + hub/docs/deployment.md | 13 +- hub/docs/development.md | 4 +- hub/docs/learning-foundation.md | 14 +- .../index.ts | 1 + .../index.test.ts | 41 +++- .../index.ts | 3 + .../index.test.ts | 32 ++- .../create-learning-job-processors/index.ts | 7 + .../execute-learning-decision/index.test.ts | 34 ++- .../execute-learning-decision/index.ts | 14 +- .../get-learning-overview/index.test.ts | 45 ++++ .../learning/get-learning-overview/index.ts | 29 ++- .../prepare-learning-store/index.test.ts | 19 ++ .../learning/prepare-learning-store/index.ts | 3 + .../index.test.ts | 29 ++- .../process-review-comment-redaction/index.ts | 13 +- .../read-learning-configuration/index.ts | 2 + .../redact-legacy-review-comment/index.ts | 8 +- hub/server/index.ts | 1 + .../run-learning-command/index.test.ts | 222 +++++++++++++++++- .../learning/run-learning-command/index.ts | 64 ++++- .../azure-entrypoint/run/index.test.ts | 35 +++ .../scripts/azure-entrypoint/run/index.ts | 23 +- .../grant-learning-database-access/index.ts | 48 ++++ .../provision-database-access/index.ts | 20 +- .../index.ts | 53 +++++ hub/server/scripts/setup/index.test.ts | 48 +++- hub/server/scripts/setup/index.ts | 47 +++- .../index.test.ts | 140 +++++++++-- .../parse-azure-secret-configuration/index.ts | 16 +- .../parse-azure-secret-configuration/types.ts | 2 +- hub/test/fixtures/learning/report-runtime.mjs | 39 ++- 35 files changed, 982 insertions(+), 94 deletions(-) create mode 100644 hub/.devcontainer/learning-role.sql create mode 100644 hub/server/scripts/grant-learning-database-access/index.ts create mode 100644 hub/server/scripts/provision-learning-database-access/index.ts diff --git a/hub/.devcontainer/compose.yaml b/hub/.devcontainer/compose.yaml index 90c91021..a448babd 100644 --- a/hub/.devcontainer/compose.yaml +++ b/hub/.devcontainer/compose.yaml @@ -11,6 +11,9 @@ services: environment: DATABASE_URL: postgresql://replica:replica@db:5432/replica TEST_DATABASE_URL: postgresql://replica:replica@db:5432/postgres + REPLICA_LEARNING_DATABASE_URL: postgresql://replica_learning_runtime:replica-learning-dev@db:5432/replica + REPLICA_LEARNING_MIGRATION_DATABASE_URL: postgresql://replica:replica@db:5432/replica + REPLICA_LEARNING_RUNTIME_ROLE: replica_learning_runtime REPLICA_DEVCONTAINER: "true" depends_on: db: @@ -26,6 +29,7 @@ services: - "127.0.0.1:5432:5432" volumes: - postgres-data:/var/lib/postgresql + - ./learning-role.sql:/docker-entrypoint-initdb.d/learning-role.sql:ro healthcheck: test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U replica -d replica"] interval: 5s diff --git a/hub/.devcontainer/decision-walkthrough.compose.yaml b/hub/.devcontainer/decision-walkthrough.compose.yaml index b8362fd1..f8e21fc8 100644 --- a/hub/.devcontainer/decision-walkthrough.compose.yaml +++ b/hub/.devcontainer/decision-walkthrough.compose.yaml @@ -11,6 +11,7 @@ services: ARTIFACT_STORAGE_PROVIDER: filesystem ARTIFACT_STORAGE_DIRECTORY: /workspaces/replica/hub/storage/decision-walkthrough-artifacts REPLICA_LEARNING_ROOT: /workspaces/replica/hub/storage/decision-walkthrough-learning + REPLICA_LEARNING_DATABASE_URL: "" REPLICA_LEARNING_CLI: /workspaces/replica/packages/learning/bin/replica-learning.mjs REPLICA_DECISION_RUNTIME_URL: http://127.0.0.1:8010 REPLICA_DECISION_RUNTIME_AUTHENTICATION: environment-token diff --git a/hub/.devcontainer/learning-role.sql b/hub/.devcontainer/learning-role.sql new file mode 100644 index 00000000..06ef280e --- /dev/null +++ b/hub/.devcontainer/learning-role.sql @@ -0,0 +1,2 @@ +CREATE ROLE replica_learning_runtime LOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS PASSWORD 'replica-learning-dev'; +GRANT CONNECT ON DATABASE replica TO replica_learning_runtime; diff --git a/hub/docs/deployment.md b/hub/docs/deployment.md index c2617cad..4968bc18 100644 --- a/hub/docs/deployment.md +++ b/hub/docs/deployment.md @@ -4,7 +4,7 @@ The Hub image runs the frontend, API, and both workers together. It can expose G ## Image and runtime -Build from the repository root with `docker build -f hub/Dockerfile -t replica-hub:check .`. When an npm proxy is required, add `--build-arg NPM_REGISTRY=https://YOUR_PROXY/`. This resolves locked dependency versions through that registry without changing the source lockfiles; the registry URL must not contain credentials. The image runs as a non-root user and contains compiled application code, migration tooling, and the separately installed `replica-learning` command. Mount persistent local storage at `/app/storage` before repository learning stores are enabled. Publish and deploy the same image digest for setup and Hub. +Build from the repository root with `docker build -f hub/Dockerfile -t replica-hub:check .`. When an npm proxy is required, add `--build-arg NPM_REGISTRY=https://YOUR_PROXY/`. This resolves locked dependency versions through that registry without changing the source lockfiles; the registry URL must not contain credentials. The image runs as a non-root user and contains compiled application code, migration tooling, and the separately installed `replica-learning` command. SQLite learning stores need persistent local storage at `/app/storage`; PostgreSQL learning stores do not. Publish and deploy the same image digest for setup and Hub. Host npm configuration is not inherited by the image build. Without `NPM_REGISTRY`, the container needs public npm access. Where that access is not allowed, supply your approved proxy using the build argument above. Explicit scoped registry mappings in copied `.npmrc` files still apply. @@ -16,6 +16,9 @@ Publishing is an explicit operator step, not a side effect of CI. From the appro | `HOST`, `PORT` | Source defaults to `127.0.0.1:3001`; the image binds `0.0.0.0:3001`. | | `DATABASE_URL` | PostgreSQL connection URL, required for combined, worker, and setup modes. Configure verified TLS for remote databases. | | `DATABASE_RUNTIME_ROLE` | Setup-only opt-in for separate database roles: exactly `replica_runtime`. See [database access](database.md#deployment-database-roles). | +| `REPLICA_LEARNING_DATABASE_URL` | Optional protected URL for the separate learning runtime login. See [learning storage](learning-foundation.md#private-storage). | +| `REPLICA_LEARNING_MIGRATION_DATABASE_URL` | Setup-only privileged URL for the package's learning schema migration. Never supply it to the running Hub. | +| `REPLICA_LEARNING_RUNTIME_ROLE` | Setup-only learning grants role: exactly `replica_learning_runtime`. | | `CLIENT_DIRECTORY` | Absolute directory containing built frontend assets and `index.html`; the image uses `/app/dist/client`. Leave unset for the development API. | | `SHUTDOWN_TIMEOUT_MS` | Request and worker drain deadline, default 30000 milliseconds. Allow another five seconds for telemetry flushing. | | `ON_DEMAND_JOB_CONCURRENCY`, `SCHEDULED_JOB_CONCURRENCY` | Independent worker concurrency, as described in [Background jobs](background-jobs.md). | @@ -50,9 +53,9 @@ On termination, combined mode stops all three roles and drains work within the c ### Azure startup secret retrieval -The Azure installation invokes `node dist/server/scripts/azure-entrypoint/index.js runtime`, `setup`, or `provision` instead of using platform-managed Key Vault references. Rebuild and publish the image from this source before applying these commands; earlier images do not contain this entrypoint. `AZURE_CLIENT_ID` explicitly selects the assigned workload identity. `AZURE_KEY_VAULT_SECRET_REFERENCES` is a non-secret JSON map of destination environment names to public-cloud HTTPS Key Vault secret URLs. The entrypoint validates all references, reads their values through the selected identity, and populates the workload's in-memory environment before importing its existing entrypoint. Retrieved secret values never enter Terraform inputs, Azure container configuration, or startup logs. +The Azure installation invokes `node dist/server/scripts/azure-entrypoint/index.js runtime`, `setup`, `provision`, or `provision-learning` instead of using platform-managed Key Vault references. Rebuild and publish the image from this source before applying these commands; earlier images do not contain this entrypoint. `AZURE_CLIENT_ID` explicitly selects the assigned workload identity. `AZURE_KEY_VAULT_SECRET_REFERENCES` is a non-secret JSON map of destination environment names to public-cloud HTTPS Key Vault secret URLs. The entrypoint validates all references, reads their values through the selected identity, and populates the workload's in-memory environment before importing its existing entrypoint. Retrieved secret values never enter Terraform inputs, Azure container configuration, or startup logs. -Runtime and setup require `DATABASE_URL`; setup accepts no additional references. Provisioning requires exactly `DATABASE_URL`, `HUB_MIGRATION_PASSWORD`, and `HUB_RUNTIME_PASSWORD`, with versioned URLs. Runtime may additionally reference validated configuration names, but references cannot replace deployment-owned fields or already-defined values. Retrieval has a shared 30-second startup deadline and cancellation support. Failure prevents workload imports and database work; it does not fall back to operator credentials, a system-assigned identity, or old environment values. +Runtime and setup require `DATABASE_URL`; setup may also receive `REPLICA_LEARNING_MIGRATION_DATABASE_URL`. Fresh provisioning requires exactly `DATABASE_URL`, `HUB_MIGRATION_PASSWORD`, `HUB_RUNTIME_PASSWORD`, and `HUB_LEARNING_PASSWORD`, with versioned URLs. Existing-install learning provisioning requires only `DATABASE_URL` and `HUB_LEARNING_PASSWORD`. Runtime may additionally reference validated configuration names, but references cannot replace deployment-owned fields or already-defined values. Retrieval has a shared 30-second startup deadline and cancellation support. Failure prevents workload imports and database work; it does not fall back to operator credentials, a system-assigned identity, or old environment values. Versioned references make rotation explicit. An unversioned runtime/setup URL is resolved once at startup; there is no background refresh or automatic revision restart. Use the installation's serialized release procedure to load a rotated value. Source development, local image runs with directly supplied protected environment values, and the existing setup/provisioning scripts retain their original entrypoints and behavior. @@ -62,11 +65,11 @@ The Azure entrypoint also supports the scoped [GitHub author repair and webhook Run `npm run setup` from `hub/`, or invoke `node dist/server/scripts/setup/index.js` inside the image. Normal API and worker startup never runs setup. -The script holds a PostgreSQL session advisory lock across Prisma migrations, BullMQ migrations, and schedule registration. While the lock connection is healthy, a competing setup fails without starting those steps. Losing that connection releases the lock immediately and requests termination of the current step; child termination can take up to five seconds. The lock alone cannot exclude another invocation during that interval. Setup waits for child cleanup and exits unsuccessfully; logs identify the step without exposing migration-tool diagnostics that could contain secrets. +The script holds a PostgreSQL session advisory lock across Prisma migrations, BullMQ migrations, schedule registration, and the optional learning schema migration and grants. While the lock connection is healthy, a competing setup fails without starting those steps. Losing that connection releases the lock immediately and requests termination of the current step; child termination can take up to five seconds. The lock alone cannot exclude another invocation during that interval. Setup waits for child cleanup and exits unsuccessfully; logs identify the step without exposing migration-tool diagnostics that could contain secrets. Only setup scripts should modify migration and schedule state during a release. `npm run jobs:setup` remains a development-only shortcut that does not acquire the full release lock. Operational entry points live under `server/scripts/`; domains do not invoke them. -Migrations are not one transaction across both schemas. Fix the failed step and retry setup before starting the new image. This repository-access upgrade requires a maintenance window: stop all old API and worker processes before setup and the new deployment. Older binaries do not enforce the new access fence. Application rollback changes the image, not the database schema; a rollback must also preserve the access policy. +Migrations are not one transaction across schemas. Fix the failed step and retry setup before starting the new image. This repository-access upgrade requires a maintenance window: stop all old API and worker processes before setup and the new deployment. Older binaries do not enforce the new access fence. Application rollback changes the image, not the database schema; a rollback must also preserve the access policy. The deployment orchestrator owns serialization of the complete release, including setup and rollout. It must retain exclusion after failure and confirm that prior setup executions and database work have stopped before allowing a retry. Do not invoke production setup outside that serialized procedure. The advisory lock is an additional check for concurrent setup, not a replacement for release serialization or a guarantee of exactly-once jobs. Release orchestration must also define old/new worker overlap. See [Background jobs](background-jobs.md#schedules-and-delivery-guarantees). diff --git a/hub/docs/development.md b/hub/docs/development.md index 3d33ff9b..4e6d01b7 100644 --- a/hub/docs/development.md +++ b/hub/docs/development.md @@ -16,6 +16,8 @@ The repository is mounted at `/workspaces/replica`, with `hub/` as the working d After the container opens and PostgreSQL is healthy, install the separate learning runtime with `npm ci --prefix ../packages/learning --engine-strict`, then run `npm run setup` before starting `npm run dev:api`. Run setup again after pulling new migrations. +New devcontainer databases create a separate local learning login. Setup migrates the learning schema and grants that login access. If the PostgreSQL volume predates this configuration and the login is absent, run `docker compose -f .devcontainer/compose.yaml exec db psql -U replica -d replica -f /docker-entrypoint-initdb.d/learning-role.sql` once from `hub/`, then run setup. The included password is for this local container only. + ## Local Node.js Use npm and a Node.js version supported by `engines.node` in `hub/package.json`. From `hub/`, start only the database and copy the local configuration: @@ -149,7 +151,7 @@ The scheduled worker reconciles the configured GitHub installation every 15 minu This walkthrough uses the real Hub API, PostgreSQL, workers, artifact and learning stores, and the customer-operated reference runtime. Its deterministic fixture backend ignores image content. Use it to check orchestration and interface behavior only; do not treat its metrics or findings as model-quality evidence. -The filesystem artifact provider requires Linux. The walkthrough Compose override runs Hub and the fixture runtime on one private Docker network, so the same commands work with Docker Desktop and native Linux Docker Engine. From the repository root, create a private runtime token and state directory: +The filesystem artifact provider requires Linux. The walkthrough Compose override runs Hub and the fixture runtime on one private Docker network, so the same commands work with Docker Desktop and native Linux Docker Engine. It uses a separate SQLite learning store so the fixture can be reset without changing PostgreSQL learning history. From the repository root, create a private runtime token and state directory: ```sh mkdir -p hub/.local/decision-runtime diff --git a/hub/docs/learning-foundation.md b/hub/docs/learning-foundation.md index 5c98a5ad..f8769e77 100644 --- a/hub/docs/learning-foundation.md +++ b/hub/docs/learning-foundation.md @@ -22,15 +22,19 @@ Disconnecting removes the connection record and advances the generation. It does `REPLICA_LEARNING_ROOT` defaults to `storage/learning`. It must be a dedicated directory outside every configured static-file root. Hub rejects the filesystem root, the Hub application root, the shared `storage` root, the source public directory, the configured built-client directory and their descendants, files, and paths containing symbolic links. The check runs at startup and again when a repository store is prepared. -Hub uses the persisted GitHub repository ID as the package scope, `github.com/repositories/`. The private directory remains `/repositories/`. The store primitive creates that directory with mode `0700` and writes the package's default `config.json` with mode `0600` only when it is absent. Existing configuration remains operator-owned. +Hub uses the persisted GitHub repository ID as the package scope, `github.com/repositories/`. With SQLite, the private directory is `/repositories/`. The store primitive creates that directory with mode `0700` and writes the package's default `config.json` with mode `0600` only when it is absent. Existing configuration remains operator-owned. + +Set `REPLICA_LEARNING_DATABASE_URL` to select the package's PostgreSQL provider. Hub gives each command a private temporary config and does not create a repository store directory. Setup migrates the package schema with a separate privileged URL and grants the learning runtime login access only to that schema. See [PostgreSQL storage](../../packages/learning/README.md#postgresql-storage). + +Before switching an existing installation, stop Hub and older clients, inventory every repository's existing store, and import each one offline using the package's `import-sqlite` command. Convert a non-SQLite store using `migrate-scope` first. Do not remove the old storage until every destination has been verified, and never restart older clients against the retained copies. If a local repository directory still contains files, Hub refuses to open the PostgreSQL scope until its import receipt exists. A directory that is no longer mounted cannot provide this check, so inventory and import it before removing the mount or activating PostgreSQL. Commands for an ID-backed store supply the former UUID-based scope as `--legacy-repository`. SQLite migrates existing records and their lifecycle to the numeric scope before opening them. Other existing providers require the [offline migration](../../packages/learning/README.md#rules). Hub review imports retain the original `repositories/` source separately from the numeric learning scope. This preserves existing evidence and snapshot identities. A repository without a GitHub ID cannot open its learning store for users, run learning, or prepare learning-backed decision-model data. Hub does not infer an ID from a name or expose its stored records. To migrate a non-SQLite Hub store, stop Hub and all older clients that can write it. Run `replica-learning migrate-scope --offline --dir /repositories/ --repository github.com/repositories/ --legacy-repository github.com/repositories/`. Verify the copied store before removing any source data. The package guide explains how to restore the previous provider for another repository. -Decision commands use an existing store and never create one implicitly. The first complete review import prepares the store. +In SQLite mode, decision commands use an existing store and never create one implicitly. The first complete review import prepares the store. -An ID-less legacy repository remains unavailable for learning. A queued learning run without an ID fails visibly, and decision reconciliation remains pending. Under the learning execution lock, deletion jobs can redact the original UUID-scoped store without making its records available to users. The redaction-only command follows a durable SQLite migration mapping when present and fails closed if ownership is uncertain. Recovery retries failures. It does not assign a GitHub ID, create a repository mapping, or infer ownership from a name. +An ID-less legacy repository remains unavailable for learning. A queued learning run without an ID fails visibly, and decision reconciliation remains pending. Under the learning execution lock, deletion jobs can redact the original UUID-scoped store without making its records available to users. The redaction-only command follows the durable SQLite or PostgreSQL mapping when present and fails closed if ownership is uncertain. Recovery retries failures. It does not assign a GitHub ID or infer ownership from a name. When combining histories reveals an earlier redaction, the Learnings page tells repository administrators which exports may still contain removed text and which accepted learnings need rebuilding. The migration command also reports these follow-ups, including on retry; `replica-learning status` retains them for later review. @@ -44,9 +48,10 @@ The runner starts Node.js with the configured CLI entry point, appends `--json`, - `PATH`, `HOME`, `LANG`, `LC_ALL`, and `TZ`. - `COPILOT_GITHUB_TOKEN` only for an explicitly token-backed command. +- `REPLICA_LEARNING_DATABASE_URL` only when Hub explicitly selected PostgreSQL. - A new private `TMPDIR`. -Hub passes store paths and repository scope as command arguments, not inherited `REPLICA_LEARNING_*` variables. It does not pass database, authentication, workload-identity, storage, or other deployment credentials. Standard output is limited to 16 MiB, standard error to 1 MiB, and the default deadline is 60 seconds. A timeout, output overflow, cancellation, or surviving descendant kills the command's process group before Hub removes the temporary directory. +Hub passes store paths and repository scope as command arguments. It never inherits ambient `REPLICA_LEARNING_*` variables or passes Hub's database, migration, authentication, workload-identity, storage, or other deployment credentials. Standard output is limited to 16 MiB, standard error to 1 MiB, and the default deadline is 60 seconds. A timeout, output overflow, cancellation, or surviving descendant kills the command's process group before Hub removes the temporary directory. Repository decisions, runs, and redactions use the PostgreSQL advisory-lock primitive for one Hub-wide learning execution at a time and hold the shared repository-authority lock around authority-sensitive package work. Decisions additionally hold a shared session-authority lock from the final live-session check through command exit. Session-ending transactions take only the matching exclusive session lock unless they can also change repository grants, in which case they acquire the repository lock first and the session lock second. A decision that wins keeps both boundaries until its command exits; a competing user-facing authority change returns retryable feedback after a bounded wait. Runs do not hold the session lock, so sign-out and global revocation can proceed during their long work. Runs release the repository lock during labeling, then reacquire it and retry the requester's repository-authority check before consolidation. Losing the execution-lock database connection aborts the operation and its command through the shared signal. This preserves the CLI process boundary without moving package policy into Hub. @@ -89,6 +94,7 @@ Soft deletion queues an idempotent package redaction job after the review transa | `REPLICA_COPILOT_GITHUB_INSTALLATION_ID` | Numeric installation ID for that organization. | | `REPLICA_COPILOT_TOKEN` | Required only with `environment-token`; used only for Copilot-backed package commands. Usage is attributed to the GitHub identity represented by this credential. | | `REPLICA_LEARNING_ROOT` | Private learning-store root. Defaults to `storage/learning`. | +| `REPLICA_LEARNING_DATABASE_URL` | Optional protected URL for the separate learning runtime login. When set, Hub uses PostgreSQL. | | `REPLICA_LEARNING_CLI` | Optional package CLI path. Source development defaults to `../packages/learning/bin/replica-learning.mjs` from `hub/`; the image sets `/opt/replica/learning/bin/replica-learning.mjs`. | | `REPLICA_LEARNING_NODE` | Optional Node.js executable. Defaults to the running Node.js executable. | | `REPLICA_LEARNING_AUTOMATIC_RUNS` | Optional `true` / `false` switch. Defaults to `false`. When enabled, due repositories are discovered daily at 02:00 UTC, but no runs are created unless the saved Copilot connection is usable. | diff --git a/hub/server/domains/decision-model/create-configured-decision-model-job-processors/index.ts b/hub/server/domains/decision-model/create-configured-decision-model-job-processors/index.ts index 79cf065d..c083ec9e 100644 --- a/hub/server/domains/decision-model/create-configured-decision-model-job-processors/index.ts +++ b/hub/server/domains/decision-model/create-configured-decision-model-job-processors/index.ts @@ -40,6 +40,7 @@ export function createConfiguredDecisionModelJobProcessors( database: prisma, databaseUrl, hubOrigin, + learningDatabaseUrl: learning.learningDatabaseUrl, learningRoot: learning.root, nodePath: learning.nodePath, staticDirectories: learning.staticDirectories, diff --git a/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.test.ts b/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.test.ts index a4928045..ed39b518 100644 --- a/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.test.ts +++ b/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.test.ts @@ -89,7 +89,11 @@ function storage( } } -function hubSource(artifactStorage: ArtifactStorage, githubRepositoryId: bigint | null = 123n) { +function hubSource( + artifactStorage: ArtifactStorage, + githubRepositoryId: bigint | null = 123n, + learningDatabaseUrl?: string, +) { return createHubDecisionTasksetSource({ applicationRoot: process.cwd(), artifactStorage, @@ -99,6 +103,7 @@ function hubSource(artifactStorage: ArtifactStorage, githubRepositoryId: bigint } as never, databaseUrl: "postgresql://test", hubOrigin: "https://hub.example.test", + learningDatabaseUrl, learningRoot: "server/domains/decision-model/create-hub-decision-taskset-source/.learning", staticDirectories: [], stabilizeSnapshot: vi.fn().mockResolvedValue({ @@ -147,6 +152,40 @@ function decodeArchive(bytes: Uint8Array) { } describe("createHubDecisionTasksetSource()", () => { + it("reads training consent from the configured database", async () => { + const learningDatabaseUrl = "postgresql://learning.example/replica" + vi.mocked(prepareLearningStore).mockResolvedValue({ + directory: "/private/learning/repository", + repositoryScope: "github.com/repositories/123", + repositoryId, + }) + vi.mocked(runLearningCommand).mockResolvedValue([ + { + grant: { id: "grant-training", sources: ["hub_review_comments"] }, + activePurposes: ["training"], + expired: false, + }, + ]) + + const result = await hubSource( + storage({}), + 123n, + learningDatabaseUrl, + ).tasksetSource.hasTrainingConsent({ + repositoryId, + actorMembershipId: "44444444-4444-4444-8444-444444444444", + consentGrantId: "grant-training", + }) + + expect(result).toBe(true) + expect(prepareLearningStore).toHaveBeenCalledWith( + expect.objectContaining({ learningDatabaseUrl }), + ) + const [arguments_, options] = vi.mocked(runLearningCommand).mock.calls[0]! + expect(arguments_).not.toContain(learningDatabaseUrl) + expect(options).toMatchObject({ learningDatabaseUrl }) + }) + it("does not open a learning store for a repository without a GitHub ID", async () => { const taskset = hubSource(storage({}), null).tasksetSource diff --git a/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.ts b/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.ts index 3f76beba..07b09595 100644 --- a/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.ts +++ b/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.ts @@ -170,6 +170,7 @@ interface HubDecisionTasksetSourceOptions { database: PrismaClient databaseUrl: string hubOrigin: string + learningDatabaseUrl?: string learningRoot: string nodePath?: string staticDirectories: string[] @@ -458,6 +459,7 @@ export function createHubDecisionTasksetSource(options: HubDecisionTasksetSource async function command(arguments_: string[], timeoutMs = 60_000, signal?: AbortSignal) { return runLearningCommand(arguments_, { cliPath: options.cliPath, + learningDatabaseUrl: options.learningDatabaseUrl, nodePath: options.nodePath, signal, timeoutMs, @@ -483,6 +485,7 @@ export function createHubDecisionTasksetSource(options: HubDecisionTasksetSource async function learningStore(repositoryId: string) { return prepareLearningStore({ applicationRoot, + learningDatabaseUrl: options.learningDatabaseUrl, repositoryKey: repositoryId, repositoryScope: await learningScope(repositoryId), root: options.learningRoot, diff --git a/hub/server/domains/learning/create-learning-job-processors/index.test.ts b/hub/server/domains/learning/create-learning-job-processors/index.test.ts index 4b735b92..e71feda6 100644 --- a/hub/server/domains/learning/create-learning-job-processors/index.test.ts +++ b/hub/server/domains/learning/create-learning-job-processors/index.test.ts @@ -1,10 +1,12 @@ -import { chmod, copyFile, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises" +import { randomUUID } from "node:crypto" +import { chmod, copyFile, mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises" import { join, resolve } from "node:path" import { DatabaseSync } from "node:sqlite" import { describe, expect, it, vi } from "vitest" import { enqueueRecoverableJob } from "../../../integrations/bullmq/enqueue-recoverable-job" +import * as learningCommand from "../../../integrations/learning/run-learning-command" import { deleteExpiredLearningRuns } from "../../../repositories/learning-runs/delete-expired-learning-runs" import { redactReviewCommentJob } from "../jobs/redact-review-comment" import { createLearningJobProcessors } from "." @@ -32,6 +34,34 @@ vi.mock("../../../integrations/bullmq/enqueue-recoverable-job", () => ({ })) describe("createLearningJobProcessors()", () => { + it("redacts database comments without creating a local store", async () => { + const root = resolve(`server/domains/learning/.redaction-worker-${randomUUID()}`) + const repositoryId = "11111111-2222-4333-8444-555555555555" + const learningDatabaseUrl = "postgresql://learning.example/replica" + const command = vi.spyOn(learningCommand, "runLearningCommand").mockResolvedValue({}) + prisma.repository.findUnique.mockResolvedValue({ githubRepositoryId: 123n }) + prisma.reviewComment.updateMany.mockResolvedValue({ count: 1 }) + const processors = createLearningJobProcessors( + { + DATABASE_URL: "postgresql://unused.example/replica", + HUB_APPLICATION_ORIGIN: "https://hub.example.com", + REPLICA_LEARNING_DATABASE_URL: learningDatabaseUrl, + REPLICA_LEARNING_ROOT: root, + }, + {} as never, + ) + + await processors.redact.process({ repositoryId, commentId: 101, actor: "human:mona" }) + + expect(command).toHaveBeenCalledOnce() + const [arguments_, options] = command.mock.calls[0]! + expect(arguments_).toEqual(expect.arrayContaining(["redact", "--comment", "101"])) + expect(arguments_).not.toContain(learningDatabaseUrl) + expect(options).toMatchObject({ learningDatabaseUrl }) + expect(prisma.reviewComment.updateMany).toHaveBeenCalledOnce() + await expect(stat(root)).rejects.toMatchObject({ code: "ENOENT" }) + }) + it("prunes run history without initializing learning or Copilot when scheduling is disabled", async () => { const processors = createLearningJobProcessors( { diff --git a/hub/server/domains/learning/create-learning-job-processors/index.ts b/hub/server/domains/learning/create-learning-job-processors/index.ts index e1102f57..37b93378 100644 --- a/hub/server/domains/learning/create-learning-job-processors/index.ts +++ b/hub/server/domains/learning/create-learning-job-processors/index.ts @@ -154,6 +154,7 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg prepare: async (repositoryId) => prepareLearningStore({ applicationRoot: process.cwd(), + learningDatabaseUrl: configuration.learningDatabaseUrl, repositoryKey: repositoryId, repositoryScope: await getLearningRepositoryScope(prisma, repositoryId), root: configuration.root, @@ -199,6 +200,7 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg runCommand: (arguments_, options) => runLearningCommand(arguments_, { cliPath: configuration.cliPath, + learningDatabaseUrl: configuration.learningDatabaseUrl, nodePath: configuration.nodePath, ...options, }), @@ -326,6 +328,7 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg prepare: async (repositoryId) => prepareLearningStore({ applicationRoot: process.cwd(), + learningDatabaseUrl: configuration.learningDatabaseUrl, repositoryKey: repositoryId, repositoryScope: await getLearningRepositoryScope(prisma, repositoryId), root: configuration.root, @@ -334,6 +337,7 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg runCommand: (arguments_, options) => runLearningCommand(arguments_, { cliPath: configuration.cliPath, + learningDatabaseUrl: configuration.learningDatabaseUrl, nodePath: configuration.nodePath, ...options, }), @@ -423,6 +427,7 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg const redact = createJobProcessor(redactReviewCommentJob, async (input) => { const { configuration, databaseUrl, prisma } = await dependencies() await processReviewCommentRedaction(input, { + learningDatabaseUrl: configuration.learningDatabaseUrl, root: configuration.root, markComplete: (completed) => markReviewCommentLearningRedacted(prisma, completed), now: () => new Date(), @@ -433,6 +438,7 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg return null return await prepareLearningStore({ applicationRoot: process.cwd(), + learningDatabaseUrl: configuration.learningDatabaseUrl, repositoryKey: repositoryId, repositoryScope: `github.com/repositories/${repository.githubRepositoryId}`, root: configuration.root, @@ -444,6 +450,7 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg runCommand: (arguments_, options) => runLearningCommand(arguments_, { cliPath: configuration.cliPath, + learningDatabaseUrl: configuration.learningDatabaseUrl, nodePath: configuration.nodePath, ...options, }), diff --git a/hub/server/domains/learning/execute-learning-decision/index.test.ts b/hub/server/domains/learning/execute-learning-decision/index.test.ts index f4b3bb23..9f7bb488 100644 --- a/hub/server/domains/learning/execute-learning-decision/index.test.ts +++ b/hub/server/domains/learning/execute-learning-decision/index.test.ts @@ -1,6 +1,7 @@ -import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises" +import { randomUUID } from "node:crypto" +import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises" import { tmpdir } from "node:os" -import { join } from "node:path" +import { join, resolve } from "node:path" import { describe, expect, it, vi } from "vitest" import { runLearningCommand } from "../../../integrations/learning/run-learning-command" @@ -15,6 +16,35 @@ vi.mock("../../../utils/validate-private-storage-root", () => ({ })) describe("executeLearningDecision()", () => { + it("accepts a database learning without creating a local store", async () => { + const directory = resolve(`server/domains/learning/.decision-test-${randomUUID()}`) + const learningDatabaseUrl = "postgresql://learning.example/replica" + vi.mocked(validatePrivateStorageRoot).mockResolvedValue(directory) + vi.mocked(runLearningCommand).mockResolvedValue({}) + + const result = await executeLearningDecision({ + actor: "human:mona", + applicationRoot: "/app", + cliPath: "/app/replica-learning.mjs", + decision: { decision: "accept", digest: `sha256:${"a".repeat(64)}` }, + learningDatabaseUrl, + learningId: "mem_1", + nodePath: "/node", + operationId: "22222222-2222-4222-8222-222222222222", + repositoryId: "11111111-2222-4333-8444-555555555555", + repositoryScope: "github.com/repositories/123", + root: "/private/learning", + staticDirectories: [], + }) + + expect(result.notice).toBe("Learning accepted.") + const [arguments_, options] = vi.mocked(runLearningCommand).mock.calls[0]! + expect(arguments_).toEqual(expect.arrayContaining(["accept", "mem_1"])) + expect(arguments_).not.toContain(learningDatabaseUrl) + expect(options).toMatchObject({ learningDatabaseUrl }) + await expect(stat(directory)).rejects.toMatchObject({ code: "ENOENT" }) + }) + it("passes a dash-leading reason through a private file instead of process arguments", async () => { const directory = await mkdtemp(join(tmpdir(), "replica-learning-decision-test-")) try { diff --git a/hub/server/domains/learning/execute-learning-decision/index.ts b/hub/server/domains/learning/execute-learning-decision/index.ts index 98d1f1e2..86d02911 100644 --- a/hub/server/domains/learning/execute-learning-decision/index.ts +++ b/hub/server/domains/learning/execute-learning-decision/index.ts @@ -14,6 +14,7 @@ export async function executeLearningDecision(input: { cliPath: string decision: LearningDecision learningId: string + learningDatabaseUrl?: string nodePath: string operationId: string repositoryId: string @@ -32,11 +33,13 @@ export async function executeLearningDecision(input: { publicRoot: resolve(applicationRoot, "public"), }, ) - try { - await access(resolve(directory, "config.json")) - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error - throw new LearningCommandError("not_found", "That learning no longer exists.") + if (!input.learningDatabaseUrl) { + try { + await access(resolve(directory, "config.json")) + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error + throw new LearningCommandError("not_found", "That learning no longer exists.") + } } const arguments_ = [input.decision.decision, input.learningId] arguments_.push("--operation-id", input.operationId) @@ -69,6 +72,7 @@ export async function executeLearningDecision(input: { ], { cliPath: input.cliPath, + ...(input.learningDatabaseUrl ? { learningDatabaseUrl: input.learningDatabaseUrl } : {}), nodePath: input.nodePath, signal: input.signal, }, diff --git a/hub/server/domains/learning/get-learning-overview/index.test.ts b/hub/server/domains/learning/get-learning-overview/index.test.ts index 92d286c4..a8492292 100644 --- a/hub/server/domains/learning/get-learning-overview/index.test.ts +++ b/hub/server/domains/learning/get-learning-overview/index.test.ts @@ -19,6 +19,51 @@ describe("getLearningOverview()", () => { vi.mocked(access).mockResolvedValue(undefined) }) + it("reads database learnings without a local configuration", async () => { + vi.mocked(access).mockRejectedValue(Object.assign(new Error("missing"), { code: "ENOENT" })) + vi.mocked(runLearningCommand) + .mockResolvedValueOnce([]) + .mockResolvedValueOnce({ text: "Useful guidance", memories: [] }) + const learningDatabaseUrl = "postgresql://learning.example/replica" + + const result = await getLearningOverview({ + applicationRoot: "/app", + cliPath: "/app/replica-learning.mjs", + learningDatabaseUrl, + nodePath: "/node", + repositoryId: "11111111-2222-4333-8444-555555555555", + repositoryScope: "github.com/repositories/123", + root: "/private/learning", + staticDirectories: [], + viewer: "human:mona", + }) + + expect(result.recall.text).toBe("Useful guidance") + expect(runLearningCommand).toHaveBeenCalledTimes(2) + for (const [arguments_, options] of vi.mocked(runLearningCommand).mock.calls) { + expect(arguments_).not.toContain(learningDatabaseUrl) + expect(options).toMatchObject({ learningDatabaseUrl }) + } + }) + + it("returns an empty overview for a missing local store", async () => { + vi.mocked(access).mockRejectedValue(Object.assign(new Error("missing"), { code: "ENOENT" })) + + const result = await getLearningOverview({ + applicationRoot: "/app", + cliPath: "/app/replica-learning.mjs", + nodePath: "/node", + repositoryId: "11111111-2222-4333-8444-555555555555", + repositoryScope: "github.com/repositories/123", + root: "/private/learning", + staticDirectories: [], + viewer: "human:mona", + }) + + expect(result.suggestions).toEqual([]) + expect(runLearningCommand).not.toHaveBeenCalled() + }) + it("uses only the review source's exact event resolution for displayed evidence", async () => { vi.mocked(runLearningCommand) .mockResolvedValueOnce([ diff --git a/hub/server/domains/learning/get-learning-overview/index.ts b/hub/server/domains/learning/get-learning-overview/index.ts index b3bee20e..6067e485 100644 --- a/hub/server/domains/learning/get-learning-overview/index.ts +++ b/hub/server/domains/learning/get-learning-overview/index.ts @@ -119,6 +119,7 @@ export async function getLearningOverview(input: { applicationRoot?: string cliPath: string evidenceSource?: Pick + learningDatabaseUrl?: string nodePath: string repositoryId: string repositoryScope: string @@ -136,19 +137,25 @@ export async function getLearningOverview(input: { publicRoot: resolve(applicationRoot, "public"), }, ) - try { - await access(resolve(directory, "config.json")) - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error - return { - loadError: null, - identityReviewCount: 0, - suggestions: [], - learnings: [], - recall: { text: "", count: 0 }, + if (!input.learningDatabaseUrl) { + try { + await access(resolve(directory, "config.json")) + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error + return { + loadError: null, + identityReviewCount: 0, + suggestions: [], + learnings: [], + recall: { text: "", count: 0 }, + } } } - const commandOptions = { cliPath: input.cliPath, nodePath: input.nodePath } + const commandOptions = { + cliPath: input.cliPath, + nodePath: input.nodePath, + ...(input.learningDatabaseUrl ? { learningDatabaseUrl: input.learningDatabaseUrl } : {}), + } const commonArguments = learningStoreArguments({ directory, repositoryId: input.repositoryId, diff --git a/hub/server/domains/learning/prepare-learning-store/index.test.ts b/hub/server/domains/learning/prepare-learning-store/index.test.ts index 2253914a..d34e51b1 100644 --- a/hub/server/domains/learning/prepare-learning-store/index.test.ts +++ b/hub/server/domains/learning/prepare-learning-store/index.test.ts @@ -6,6 +6,25 @@ import { describe, expect, it, onTestFinished } from "vitest" import { prepareLearningStore } from "." describe("prepareLearningStore()", () => { + it("uses a database store without creating a local learning directory", async () => { + const applicationRoot = resolve(`server/domains/learning/.store-test-${randomUUID()}`) + const root = resolve(applicationRoot, "learning") + const repositoryKey = randomUUID() + onTestFinished(() => rm(applicationRoot, { force: true, recursive: true })) + + const result = await prepareLearningStore({ + applicationRoot, + learningDatabaseUrl: "postgresql://learning.example/replica", + repositoryKey, + repositoryScope: "github.com/repositories/123", + root, + staticDirectories: [], + }) + + expect(result.repositoryScope).toBe("github.com/repositories/123") + await expect(stat(root)).rejects.toMatchObject({ code: "ENOENT" }) + }) + it.each([ ["source public directory", 0], ["configured client directory", 1], diff --git a/hub/server/domains/learning/prepare-learning-store/index.ts b/hub/server/domains/learning/prepare-learning-store/index.ts index a797c2b0..a5655be9 100644 --- a/hub/server/domains/learning/prepare-learning-store/index.ts +++ b/hub/server/domains/learning/prepare-learning-store/index.ts @@ -14,12 +14,14 @@ const repositoryScopeSchema = z export async function prepareLearningStore({ applicationRoot = process.cwd(), + learningDatabaseUrl, repositoryKey, repositoryScope, root, staticDirectories, }: { applicationRoot?: string + learningDatabaseUrl?: string repositoryKey: string repositoryScope: string root: string @@ -33,6 +35,7 @@ export async function prepareLearningStore({ name: "REPLICA_LEARNING_ROOT", publicRoot: resolve(applicationRoot, "public"), }) + if (learningDatabaseUrl) return { directory, repositoryScope: scope, repositoryId: key } await mkdir(directory, { mode: 0o700, recursive: true }) await validatePrivateStorageRoot(directory, { applicationRoot, diff --git a/hub/server/domains/learning/process-review-comment-redaction/index.test.ts b/hub/server/domains/learning/process-review-comment-redaction/index.test.ts index ea1169ab..f76f3e99 100644 --- a/hub/server/domains/learning/process-review-comment-redaction/index.test.ts +++ b/hub/server/domains/learning/process-review-comment-redaction/index.test.ts @@ -1,4 +1,5 @@ -import { chmod, copyFile, mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises" +import { randomUUID } from "node:crypto" +import { chmod, copyFile, mkdtemp, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises" import { tmpdir } from "node:os" import { join, resolve } from "node:path" import { DatabaseSync } from "node:sqlite" @@ -22,6 +23,32 @@ async function withLearningLock(run: (signal: AbortSignal) => Promise) { } describe("processReviewCommentRedaction()", () => { + it("redacts an ID-less database repository without a local configuration", async () => { + const root = resolve(`server/domains/learning/.redaction-${randomUUID()}`) + const input = { repositoryId, commentId: 101, actor: "human:mona" } + const redactLegacy = vi.fn().mockResolvedValue(undefined) + const markComplete = vi.fn().mockResolvedValue(undefined) + + await processReviewCommentRedaction(input, { + learningDatabaseUrl: "postgresql://learning.example/replica", + root, + prepare: vi.fn().mockResolvedValue(null), + redactLegacy, + runCommand: vi.fn(), + markComplete, + now: () => new Date("2026-11-13T10:00:00Z"), + withLock: withLearningLock, + }) + + expect(redactLegacy).toHaveBeenCalledOnce() + expect(redactLegacy.mock.calls[0]?.[0]).toEqual(input) + expect((redactLegacy.mock.calls[0]?.[1] as { signal: AbortSignal }).signal).toBeInstanceOf( + AbortSignal, + ) + expect(markComplete).toHaveBeenCalledOnce() + await expect(stat(root)).rejects.toMatchObject({ code: "ENOENT" }) + }) + it("serializes redaction through the learning lock and does nothing without a store", async () => { let lockCalls = 0 async function withLock(run: (signal: AbortSignal) => Promise) { diff --git a/hub/server/domains/learning/process-review-comment-redaction/index.ts b/hub/server/domains/learning/process-review-comment-redaction/index.ts index 70b46c9e..79ef8211 100644 --- a/hub/server/domains/learning/process-review-comment-redaction/index.ts +++ b/hub/server/domains/learning/process-review-comment-redaction/index.ts @@ -7,6 +7,7 @@ import { learningStoreArguments } from "../learning-store-arguments/index.ts" export async function processReviewCommentRedaction( input: { repositoryId: string; commentId: number; actor: string }, dependencies: { + learningDatabaseUrl?: string root: string prepare(repositoryId: string): Promise<{ directory: string @@ -30,11 +31,13 @@ export async function processReviewCommentRedaction( const repositoryId = z.uuid().parse(input.repositoryId) await dependencies.withLock(async (signal) => { const directory = resolve(dependencies.root, "repositories", repositoryId) - try { - await access(resolve(directory, "config.json")) - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error - return + if (!dependencies.learningDatabaseUrl) { + try { + await access(resolve(directory, "config.json")) + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error + return + } } const store = await dependencies.prepare(input.repositoryId) if (store) { diff --git a/hub/server/domains/learning/read-learning-configuration/index.ts b/hub/server/domains/learning/read-learning-configuration/index.ts index dbb4afd6..2604d670 100644 --- a/hub/server/domains/learning/read-learning-configuration/index.ts +++ b/hub/server/domains/learning/read-learning-configuration/index.ts @@ -33,6 +33,7 @@ export async function readLearningConfiguration( environment.REPLICA_LEARNING_CLI ?? "../packages/learning/bin/replica-learning.mjs", ) const nodePath = environment.REPLICA_LEARNING_NODE?.trim() || process.execPath + const learningDatabaseUrl = environment.REPLICA_LEARNING_DATABASE_URL?.trim() || undefined let copilotCredentialProvider try { copilotCredentialProvider = createCopilotCredentialProvider(environment) @@ -46,6 +47,7 @@ export async function readLearningConfiguration( automaticRuns, cliPath, copilotCredentialProvider, + learningDatabaseUrl, nodePath, root, staticDirectories: [ diff --git a/hub/server/domains/learning/redact-legacy-review-comment/index.ts b/hub/server/domains/learning/redact-legacy-review-comment/index.ts index a46a53f3..1134f3bc 100644 --- a/hub/server/domains/learning/redact-legacy-review-comment/index.ts +++ b/hub/server/domains/learning/redact-legacy-review-comment/index.ts @@ -10,6 +10,7 @@ export async function redactLegacyReviewComment( root: string staticDirectories: string[] cliPath: string + learningDatabaseUrl?: string nodePath: string signal: AbortSignal }, @@ -37,6 +38,11 @@ export async function redactLegacyReviewComment( `github.com/repositories/${repositoryId}`, "--legacy-redaction", ], - { cliPath: options.cliPath, nodePath: options.nodePath, signal: options.signal }, + { + cliPath: options.cliPath, + nodePath: options.nodePath, + signal: options.signal, + ...(options.learningDatabaseUrl ? { learningDatabaseUrl: options.learningDatabaseUrl } : {}), + }, ) } diff --git a/hub/server/index.ts b/hub/server/index.ts index 679b22cc..d8663308 100644 --- a/hub/server/index.ts +++ b/hub/server/index.ts @@ -201,6 +201,7 @@ try { database: (await import("./integrations/prisma/index.ts")).prisma, databaseUrl, hubOrigin: applicationOrigin, + learningDatabaseUrl: learningConfiguration.learningDatabaseUrl, learningRoot: learningConfiguration.root, nodePath: learningConfiguration.nodePath, staticDirectories: learningConfiguration.staticDirectories, diff --git a/hub/server/integrations/learning/run-learning-command/index.test.ts b/hub/server/integrations/learning/run-learning-command/index.test.ts index 1b394b24..57351fa9 100644 --- a/hub/server/integrations/learning/run-learning-command/index.test.ts +++ b/hub/server/integrations/learning/run-learning-command/index.test.ts @@ -1,6 +1,6 @@ import { randomUUID } from "node:crypto" -import { mkdir, readFile, rm, stat } from "node:fs/promises" -import { resolve } from "node:path" +import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises" +import { isAbsolute, relative, resolve, sep } from "node:path" import { describe, expect, it, onTestFinished } from "vitest" import { runLearningCommand } from "." @@ -18,6 +18,8 @@ describe("runLearningCommand()", () => { LANG: "en_US.UTF-8", LC_ALL: "C", PATH: process.env.PATH, + REPLICA_LEARNING_DATABASE_URL: "ambient-database-url-must-not-leak", + REPLICA_LEARNING_MIGRATION_DATABASE_URL: "migration-url-must-not-leak", REPLICA_LEARNING_ROOT: "/private/learning", REPLICA_LEARNING_SECRET: "must-not-leak", SECRET_FROM_HUB: "must-not-leak", @@ -59,6 +61,222 @@ describe("runLearningCommand()", () => { expect(result.environment.COPILOT_GITHUB_TOKEN).toBeUndefined() }) + it("uses a private Postgres config and passes only explicitly supplied credentials", async () => { + const databaseUrl = "postgres://learning-user:learning-password@localhost/learning" + const nonexistentDirectory = resolve( + `server/integrations/learning/.process-test-${randomUUID()}`, + ) + const result = (await runLearningCommand( + ["consolidate", "--dir", nonexistentDirectory, "--repository", "github.com/repositories/123"], + { + cliPath: resolve(fixtures, "report-runtime.mjs"), + learningDatabaseUrl: databaseUrl, + githubToken: "explicit-token", + environment: { + PATH: process.env.PATH, + COPILOT_GITHUB_TOKEN: "ambient-token-must-not-leak", + REPLICA_LEARNING_DATABASE_URL: "ambient-url-must-not-leak", + REPLICA_LEARNING_MIGRATION_DATABASE_URL: "migration-url-must-not-leak", + DATABASE_URL: "hub-database-url-must-not-leak", + SECRET_FROM_HUB: "hub-secret-must-not-leak", + }, + }, + )) as { + arguments: string[] + config: string + environment: NodeJS.ProcessEnv + temporaryDirectory: string + temporaryDirectoryMode: number + } + + const storeDirectory = result.arguments[2] + if (storeDirectory === undefined) throw new Error("Missing store directory argument.") + const relativeStore = relative(result.temporaryDirectory, storeDirectory) + expect(isAbsolute(storeDirectory)).toBe(true) + expect(isAbsolute(relativeStore)).toBe(false) + expect(relativeStore === ".." || relativeStore.startsWith(`..${sep}`)).toBe(false) + expect(result.arguments).toEqual([ + "consolidate", + "--dir", + storeDirectory, + "--repository", + "github.com/repositories/123", + "--json", + ]) + expect(result.environment).toEqual({ + PATH: process.env.PATH, + TMPDIR: result.temporaryDirectory, + COPILOT_GITHUB_TOKEN: "explicit-token", + REPLICA_LEARNING_DATABASE_URL: databaseUrl, + }) + expect(JSON.parse(result.config)).toMatchObject({ + memory: { provider: "postgres" }, + consolidation: { + options: { + signals: ["visual_quality", "accessibility", "usability", "content", "interaction"], + }, + }, + }) + expect(JSON.parse(result.config).memory.requireImport).toBeUndefined() + for (const secret of [ + databaseUrl, + "learning-password", + "explicit-token", + "migration-url-must-not-leak", + "hub-secret-must-not-leak", + ]) { + expect(result.config).not.toContain(secret) + expect(result.arguments.join(" ")).not.toContain(secret) + } + expect(result.temporaryDirectoryMode).toBe(0o700) + await expect(stat(result.temporaryDirectory)).rejects.toMatchObject({ code: "ENOENT" }) + }) + + it("requires import when the original store directory is nonempty", async () => { + const directory = resolve(`server/integrations/learning/.process-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { force: true, recursive: true })) + const history = resolve(directory, "history.sqlite") + await writeFile(history, "existing learning history") + + const result = (await runLearningCommand( + ["consolidate", "--dir", directory, "--repository", "github.com/repositories/123"], + { + cliPath: resolve(fixtures, "report-runtime.mjs"), + learningDatabaseUrl: "postgres://learning-user:learning-password@localhost/learning", + environment: { PATH: process.env.PATH }, + }, + )) as { arguments: string[]; config: string; temporaryDirectory: string } + + const storeDirectory = result.arguments[2] + if (storeDirectory === undefined) throw new Error("Missing store directory argument.") + const relativeStore = relative(result.temporaryDirectory, storeDirectory) + expect(isAbsolute(storeDirectory)).toBe(true) + expect(isAbsolute(relativeStore)).toBe(false) + expect(relativeStore === ".." || relativeStore.startsWith(`..${sep}`)).toBe(false) + expect(result.arguments).toEqual([ + "consolidate", + "--dir", + storeDirectory, + "--repository", + "github.com/repositories/123", + "--json", + ]) + expect(JSON.parse(result.config)).toMatchObject({ + memory: { provider: "postgres", requireImport: true }, + }) + expect(await readFile(history, "utf8")).toBe("existing learning history") + await expect(stat(result.temporaryDirectory)).rejects.toMatchObject({ code: "ENOENT" }) + }) + + it("requires import for a nonempty store supplied with an equals sign", async () => { + const directory = resolve(`server/integrations/learning/.process-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { force: true, recursive: true })) + await writeFile(resolve(directory, "history.sqlite"), "existing learning history") + + const result = (await runLearningCommand( + ["consolidate", `--dir=${directory}`, "--repository", "github.com/repositories/123"], + { + cliPath: resolve(fixtures, "report-runtime.mjs"), + learningDatabaseUrl: "postgres://learning-user:learning-password@localhost/learning", + environment: { PATH: process.env.PATH }, + }, + )) as { arguments: string[]; config: string; temporaryDirectory: string } + + const directoryArgument = result.arguments[1] + if (directoryArgument === undefined) throw new Error("Missing store directory argument.") + const storeDirectory = directoryArgument.slice("--dir=".length) + const relativeStore = relative(result.temporaryDirectory, storeDirectory) + expect(isAbsolute(storeDirectory)).toBe(true) + expect(isAbsolute(relativeStore)).toBe(false) + expect(relativeStore === ".." || relativeStore.startsWith(`..${sep}`)).toBe(false) + expect(result.arguments).toEqual([ + "consolidate", + `--dir=${storeDirectory}`, + "--repository", + "github.com/repositories/123", + "--json", + ]) + expect(JSON.parse(result.config)).toMatchObject({ + memory: { provider: "postgres", requireImport: true }, + }) + await expect(stat(result.temporaryDirectory)).rejects.toMatchObject({ code: "ENOENT" }) + }) + + it("passes an explicitly supplied learning database URL to a command without a store", async () => { + const databaseUrl = "postgres://learning-user:learning-password@localhost/learning" + const result = (await runLearningCommand(["copilot", "status"], { + cliPath: resolve(fixtures, "report-runtime.mjs"), + learningDatabaseUrl: databaseUrl, + environment: { + PATH: process.env.PATH, + COPILOT_GITHUB_TOKEN: "ambient-token-must-not-leak", + REPLICA_LEARNING_MIGRATION_DATABASE_URL: "migration-url-must-not-leak", + }, + })) as { arguments: string[]; environment: NodeJS.ProcessEnv; temporaryDirectory: string } + + expect(result.arguments).toEqual(["copilot", "status", "--json"]) + expect(result.environment).toEqual({ + PATH: process.env.PATH, + TMPDIR: result.temporaryDirectory, + REPLICA_LEARNING_DATABASE_URL: databaseUrl, + }) + await expect(stat(result.temporaryDirectory)).rejects.toMatchObject({ code: "ENOENT" }) + }) + + it("retains the original store directory without an explicit learning database URL", async () => { + const result = (await runLearningCommand( + ["consolidate", "--dir", "/existing/sqlite", "--repository", "github.com/repositories/123"], + { + cliPath: resolve(fixtures, "report-runtime.mjs"), + environment: { PATH: process.env.PATH, REPLICA_LEARNING_DATABASE_URL: "ambient-url" }, + }, + )) as { arguments: string[]; environment: NodeJS.ProcessEnv } + + expect(result.arguments).toEqual([ + "consolidate", + "--dir", + "/existing/sqlite", + "--repository", + "github.com/repositories/123", + "--json", + ]) + expect(result.environment.REPLICA_LEARNING_DATABASE_URL).toBeUndefined() + }) + + it("removes the private Postgres config after a failed command", async () => { + const directory = resolve(`server/integrations/learning/.process-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { force: true, recursive: true })) + const marker = resolve(directory, "command.json") + + await expect( + runLearningCommand( + ["consolidate", "--dir", "/existing/sqlite", "--fixture-fail-report", marker], + { + cliPath: resolve(fixtures, "report-runtime.mjs"), + learningDatabaseUrl: "postgres://learning-user:learning-password@localhost/learning", + environment: { PATH: process.env.PATH }, + }, + ), + ).rejects.toMatchObject({ code: "invalid_request" }) + + const result = JSON.parse(await readFile(marker, "utf8")) as { + arguments: string[] + config: string + temporaryDirectory: string + } + const storeDirectory = result.arguments[2] + if (storeDirectory === undefined) throw new Error("Missing store directory argument.") + const relativeStore = relative(result.temporaryDirectory, storeDirectory) + expect(isAbsolute(storeDirectory)).toBe(true) + expect(isAbsolute(relativeStore)).toBe(false) + expect(relativeStore === ".." || relativeStore.startsWith(`..${sep}`)).toBe(false) + expect(JSON.parse(result.config)).toMatchObject({ memory: { provider: "postgres" } }) + await expect(stat(result.temporaryDirectory)).rejects.toMatchObject({ code: "ENOENT" }) + }) + it("preserves valid JSON progress from a failed command", async () => { await expect( runLearningCommand(["label"], { diff --git a/hub/server/integrations/learning/run-learning-command/index.ts b/hub/server/integrations/learning/run-learning-command/index.ts index 51251976..659c5cb0 100644 --- a/hub/server/integrations/learning/run-learning-command/index.ts +++ b/hub/server/integrations/learning/run-learning-command/index.ts @@ -1,4 +1,4 @@ -import { chmod, mkdtemp, rm, stat } from "node:fs/promises" +import { chmod, mkdtemp, readdir, rm, stat, writeFile } from "node:fs/promises" import { tmpdir } from "node:os" import { join } from "node:path" import { spawn } from "node:child_process" @@ -6,7 +6,12 @@ import { spawn } from "node:child_process" import { LearningCommandError } from "./errors.ts" const passedVariables = new Set(["PATH", "HOME", "LANG", "LC_ALL", "TZ"]) -const childVariables = [...passedVariables, "COPILOT_GITHUB_TOKEN", "TMPDIR"] +const childVariables = [ + ...passedVariables, + "COPILOT_GITHUB_TOKEN", + "REPLICA_LEARNING_DATABASE_URL", + "TMPDIR", +] const bootstrap = ` import { pathToFileURL } from "node:url"; const allowed = new Set(${JSON.stringify(childVariables)}); @@ -24,6 +29,7 @@ function commandEnvironment( source: NodeJS.ProcessEnv, temporaryDirectory: string, githubToken?: string, + learningDatabaseUrl?: string, ) { const environment: NodeJS.ProcessEnv = { TMPDIR: temporaryDirectory } for (const [name, value] of Object.entries(source)) { @@ -32,6 +38,7 @@ function commandEnvironment( } } if (githubToken) environment.COPILOT_GITHUB_TOKEN = githubToken + if (learningDatabaseUrl) environment.REPLICA_LEARNING_DATABASE_URL = learningDatabaseUrl return environment } @@ -69,6 +76,7 @@ export async function runLearningCommand( environment = process.env, errorLimit = 1024 * 1024, githubToken, + learningDatabaseUrl, nodePath = process.execPath, outputLimit = 16 * 1024 * 1024, signal, @@ -79,6 +87,7 @@ export async function runLearningCommand( environment?: NodeJS.ProcessEnv errorLimit?: number githubToken?: string + learningDatabaseUrl?: string nodePath?: string outputLimit?: number signal?: AbortSignal @@ -97,14 +106,61 @@ export async function runLearningCommand( const temporaryDirectory = await mkdtemp(join(tmpdir(), "replica-learning-")) await chmod(temporaryDirectory, 0o700) try { + const commandArguments = [...arguments_] + if (learningDatabaseUrl) { + let hasDirectory = false + let requireImport = false + async function preserveExistingStore(directory: string) { + try { + if ((await readdir(directory)).length) requireImport = true + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error + } + } + for (let index = 0; index < commandArguments.length; index += 1) { + const argument = commandArguments[index] + if (argument === "--dir") { + const directory = commandArguments[index + 1] + if (!directory || directory.startsWith("--")) + throw new LearningCommandError("invalid_request", "The learning directory is missing.") + await preserveExistingStore(directory) + commandArguments[++index] = temporaryDirectory + hasDirectory = true + } else if (argument?.startsWith("--dir=")) { + await preserveExistingStore(argument.slice("--dir=".length)) + commandArguments[index] = `--dir=${temporaryDirectory}` + hasDirectory = true + } + } + if (hasDirectory) { + await writeFile( + join(temporaryDirectory, "config.json"), + JSON.stringify({ + schemaVersion: "replica.learning-config/v1", + memory: { provider: "postgres", ...(requireImport ? { requireImport: true } : {}) }, + consolidation: { + options: { + signals: ["visual_quality", "accessibility", "usability", "content", "interaction"], + }, + }, + }), + { mode: 0o600, flag: "wx" }, + ) + } + } return await new Promise((resolve, reject) => { const child = spawn( nodePath, - ["--input-type=module", "--eval", bootstrap, cliPath, ...arguments_, "--json"], + ["--input-type=module", "--eval", bootstrap, cliPath, ...commandArguments, "--json"], { cwd: directory ?? temporaryDirectory, detached: true, - env: commandEnvironment(environment, temporaryDirectory, githubToken), + env: commandEnvironment( + environment, + temporaryDirectory, + githubToken, + learningDatabaseUrl, + ), stdio: ["ignore", "pipe", "pipe"], }, ) diff --git a/hub/server/scripts/azure-entrypoint/run/index.test.ts b/hub/server/scripts/azure-entrypoint/run/index.test.ts index 8ff0ac77..2690468f 100644 --- a/hub/server/scripts/azure-entrypoint/run/index.test.ts +++ b/hub/server/scripts/azure-entrypoint/run/index.test.ts @@ -1,6 +1,7 @@ import { beforeEach, describe, expect, it, onTestFinished, vi } from "vitest" import type { provisionDatabaseAccess } from "../../provision-database-access" +import type { provisionLearningDatabaseAccess } from "../../provision-learning-database-access" import type { loadAzureSecretEnvironment } from "../load-secret-environment" const mocks = vi.hoisted(() => ({ @@ -11,6 +12,8 @@ const mocks = vi.hoisted(() => ({ loggerImported: vi.fn(), setup: vi.fn<() => Promise>(), provision: vi.fn(), + provisionLearning: vi.fn(), + provisionLearningImported: vi.fn(), repairImported: vi.fn(), checkImported: vi.fn(), replayImported: vi.fn(), @@ -42,6 +45,10 @@ describe("runAzureEntrypoint()", () => { mocks.provisionImported() return { provisionDatabaseAccess: mocks.provision } }) + vi.doMock("../../provision-learning-database-access", () => { + mocks.provisionLearningImported() + return { provisionLearningDatabaseAccess: mocks.provisionLearning } + }) vi.doMock("../../../integrations/pino", () => { mocks.loggerImported() return { logger: { info: mocks.info } } @@ -113,6 +120,7 @@ describe("runAzureEntrypoint()", () => { DATABASE_URL: "postgresql://synthetic-admin:fixture@database.invalid/replica", HUB_MIGRATION_PASSWORD: "synthetic-migration-password", HUB_RUNTIME_PASSWORD: "synthetic-runtime-password", + HUB_LEARNING_PASSWORD: "synthetic-learning-password", } const environment: NodeJS.ProcessEnv = { NODE_ENV: "production", @@ -186,6 +194,7 @@ describe("runAzureEntrypoint()", () => { databaseUrl: secrets.DATABASE_URL, migrationPassword: secrets.HUB_MIGRATION_PASSWORD, runtimePassword: secrets.HUB_RUNTIME_PASSWORD, + learningPassword: secrets.HUB_LEARNING_PASSWORD, }) expect(mocks.info).toHaveBeenCalledTimes(1) expect(JSON.stringify(mocks.info.mock.calls)).not.toMatch(/synthetic-|postgresql:/) @@ -196,6 +205,32 @@ describe("runAzureEntrypoint()", () => { }, ) + it("provisions only the learning role for an existing installation", async () => { + const originalEnvironment = process.env + process.env = { NODE_ENV: "production" } + onTestFinished(() => { + process.env = originalEnvironment + }) + mocks.loadSecrets.mockImplementation((environment, target) => { + expect(target).toBe("provision-learning") + expect(mocks.provisionLearningImported).not.toHaveBeenCalled() + environment.DATABASE_URL = "postgresql://admin@database.invalid/replica" + environment.HUB_LEARNING_PASSWORD = "synthetic-learning-password" + return Promise.resolve() + }) + mocks.provisionLearning.mockResolvedValue(undefined) + + await runAzureEntrypoint("provision-learning") + + expect(mocks.provisionLearning).toHaveBeenCalledExactlyOnceWith({ + databaseUrl: "postgresql://admin@database.invalid/replica", + learningPassword: "synthetic-learning-password", + }) + expect(mocks.provisionImported).not.toHaveBeenCalled() + expect(mocks.provision).not.toHaveBeenCalled() + expect(mocks.setupImported).not.toHaveBeenCalled() + }) + it.each(["runtime", "setup", "provision"] as const)( "does not import any workload or begin database work after %s secret loading fails", async (target) => { diff --git a/hub/server/scripts/azure-entrypoint/run/index.ts b/hub/server/scripts/azure-entrypoint/run/index.ts index daa739bf..2def6c53 100644 --- a/hub/server/scripts/azure-entrypoint/run/index.ts +++ b/hub/server/scripts/azure-entrypoint/run/index.ts @@ -5,7 +5,13 @@ export async function runAzureEntrypoint(target: string | undefined): Promise( + `SELECT EXISTS ( + SELECT 1 FROM pg_namespace + WHERE nspname = 'public' AND nspowner = (SELECT oid FROM pg_roles WHERE rolname = 'replica_migration') + ) AND EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'replica_runtime') AS ready`, + ) + if (!existing.rows[0]!.ready) + throw new Error("Learning provisioning requires an existing provisioned Hub database.") + const database = await client.query<{ name: string }>("SELECT current_database() AS name") + await client.query( + `CREATE ROLE replica_learning_runtime LOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS PASSWORD ${pg.escapeLiteral(learningPassword)}`, + ) + await client.query( + `GRANT CONNECT ON DATABASE ${pg.escapeIdentifier(database.rows[0]!.name)} TO replica_learning_runtime`, + ) + await client.query("COMMIT") + } finally { + await client.end() + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { + try { + await provisionLearningDatabaseAccess({ + databaseUrl: process.env.DATABASE_URL ?? "", + learningPassword: process.env.HUB_LEARNING_PASSWORD ?? "", + }) + logger.info("Learning database access provisioned") + } catch { + logger.fatal("Learning database provisioning failed; check the existing database and roles") + process.exitCode = 1 + } +} diff --git a/hub/server/scripts/setup/index.test.ts b/hub/server/scripts/setup/index.test.ts index 27999799..90945dba 100644 --- a/hub/server/scripts/setup/index.test.ts +++ b/hub/server/scripts/setup/index.test.ts @@ -1,10 +1,13 @@ import { spawn, type ChildProcess } from "node:child_process" import { EventEmitter } from "node:events" +import { resolve } from "node:path" import { fileURLToPath } from "node:url" import { describe, expect, it, vi } from "vitest" import { setup } from "." +const lock = vi.hoisted(() => ({ active: false })) + vi.mock("dotenv/config", () => ({})) vi.mock("node:child_process", () => ({ spawn: vi.fn() })) vi.mock("../../integrations/pino", () => ({ logger: { info: vi.fn() } })) @@ -15,13 +18,22 @@ vi.mock("../../integrations/postgres/with-setup-lock", () => ({ }: { run: (signal: AbortSignal) => Promise signal: AbortSignal - }) => run(signal), + }) => { + lock.active = true + try { + await run(signal) + } finally { + lock.active = false + } + }, })) describe("setup()", () => { it("passes native job and runtime-grant script paths to Node", async () => { vi.stubEnv("DATABASE_URL", "postgresql://replica_migration@localhost/replica") vi.stubEnv("DATABASE_RUNTIME_ROLE", "replica_runtime") + vi.stubEnv("REPLICA_LEARNING_MIGRATION_DATABASE_URL", undefined) + vi.stubEnv("REPLICA_LEARNING_RUNTIME_ROLE", undefined) vi.mocked(spawn).mockImplementation(() => { const child = new EventEmitter() as ChildProcess child.kill = vi.fn(() => true) @@ -31,6 +43,7 @@ describe("setup()", () => { await setup() + expect(spawn).toHaveBeenCalledTimes(3) expect(spawn).toHaveBeenNthCalledWith( 2, process.execPath, @@ -44,4 +57,37 @@ describe("setup()", () => { { stdio: "ignore" }, ) }) + + it("migrates and grants the learning database under the setup lock", async () => { + const migrationUrl = "postgresql://learning_migration@localhost/replica" + vi.stubEnv("DATABASE_URL", "postgresql://replica_migration@localhost/replica") + vi.stubEnv("DATABASE_RUNTIME_ROLE", undefined) + vi.stubEnv("REPLICA_LEARNING_MIGRATION_DATABASE_URL", migrationUrl) + vi.stubEnv("REPLICA_LEARNING_RUNTIME_ROLE", "replica_learning_runtime") + vi.stubEnv("REPLICA_LEARNING_CLI", "learning-cli.mjs") + vi.mocked(spawn).mockImplementation((_command, arguments_) => { + expect(lock.active).toBe(true) + expect(arguments_).not.toContain(migrationUrl) + const child = new EventEmitter() as ChildProcess + child.kill = vi.fn(() => true) + queueMicrotask(() => child.emit("close", 0)) + return child + }) + + await setup() + + expect(spawn).toHaveBeenCalledTimes(4) + expect(spawn).toHaveBeenNthCalledWith( + 3, + process.execPath, + [resolve("learning-cli.mjs"), "migrate"], + { stdio: "ignore" }, + ) + expect(spawn).toHaveBeenNthCalledWith( + 4, + process.execPath, + [fileURLToPath(new URL("../grant-learning-database-access/index.ts", import.meta.url))], + { stdio: "ignore" }, + ) + }) }) diff --git a/hub/server/scripts/setup/index.ts b/hub/server/scripts/setup/index.ts index e8d93187..2e2d7a19 100644 --- a/hub/server/scripts/setup/index.ts +++ b/hub/server/scripts/setup/index.ts @@ -16,6 +16,14 @@ export async function setup() { ) { throw new Error("Separate roles require replica_runtime and a replica_migration database URL.") } + const learningMigrationUrl = process.env.REPLICA_LEARNING_MIGRATION_DATABASE_URL + const learningRuntimeRole = process.env.REPLICA_LEARNING_RUNTIME_ROLE + if ( + (learningRuntimeRole && learningRuntimeRole !== "replica_learning_runtime") || + (learningRuntimeRole && !learningMigrationUrl) + ) { + throw new Error("Learning runtime grants require the learning migration URL and runtime role.") + } const controller = new AbortController() function stop() { controller.abort() @@ -33,17 +41,40 @@ export async function setup() { `../grant-runtime-database-access/index.${extension}`, import.meta.url, ) + const learningGrantScript = new URL( + `../grant-learning-database-access/index.${extension}`, + import.meta.url, + ) const steps = [ - [resolve("node_modules/prisma/build/index.js"), "migrate", "deploy"], - [fileURLToPath(jobScript)], - ...(process.env.DATABASE_RUNTIME_ROLE ? [[fileURLToPath(grantScript)]] : []), + { + name: "prisma", + args: [resolve("node_modules/prisma/build/index.js"), "migrate", "deploy"], + }, + { name: "jobs", args: [fileURLToPath(jobScript)] }, + ...(process.env.DATABASE_RUNTIME_ROLE + ? [{ name: "runtime-grants", args: [fileURLToPath(grantScript)] }] + : []), + ...(learningMigrationUrl + ? [ + { + name: "learning-migrate", + args: [ + resolve( + process.env.REPLICA_LEARNING_CLI ?? + "../packages/learning/bin/replica-learning.mjs", + ), + "migrate", + ], + }, + ] + : []), + ...(learningRuntimeRole + ? [{ name: "learning-grants", args: [fileURLToPath(learningGrantScript)] }] + : []), ] - for (const [index, args] of steps.entries()) { + for (const { name, args } of steps) { signal.throwIfAborted() - logger.info( - { step: ["prisma", "jobs", "runtime-grants"][index] }, - "Hub setup step started", - ) + logger.info({ step: name }, "Hub setup step started") // Migration tools can include database URLs in diagnostics; keep their output private. const child = spawn(process.execPath, args, { stdio: "ignore" }) let timeout: ReturnType | undefined diff --git a/hub/server/utils/parse-azure-secret-configuration/index.test.ts b/hub/server/utils/parse-azure-secret-configuration/index.test.ts index f615f1bb..ece5a0fb 100644 --- a/hub/server/utils/parse-azure-secret-configuration/index.test.ts +++ b/hub/server/utils/parse-azure-secret-configuration/index.test.ts @@ -37,7 +37,7 @@ describe("parseAzureSecretConfiguration()", () => { }) }) - it("accepts exactly the three versioned provisioning references", () => { + it("accepts exactly the versioned provisioning references", () => { const references = { DATABASE_URL: "https://fixture.vault.azure.net/secrets/admin-database/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", @@ -45,6 +45,8 @@ describe("parseAzureSecretConfiguration()", () => { "https://fixture.vault.azure.net/secrets/migration-password/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", HUB_RUNTIME_PASSWORD: "https://fixture.vault.azure.net/secrets/runtime-password/cccccccccccccccccccccccccccccccc", + HUB_LEARNING_PASSWORD: + "https://fixture.vault.azure.net/secrets/learning-password/dddddddddddddddddddddddddddddddd", } const environment = { AZURE_CLIENT_ID: "00000000-0000-0000-0000-000000000005", @@ -57,6 +59,96 @@ describe("parseAzureSecretConfiguration()", () => { }) }) + it("accepts only the admin URL and learning password for an existing installation", () => { + const references = { + DATABASE_URL: + "https://fixture.vault.azure.net/secrets/admin-database/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + HUB_LEARNING_PASSWORD: + "https://fixture.vault.azure.net/secrets/learning-password/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + } + const environment = { + AZURE_CLIENT_ID: "00000000-0000-0000-0000-000000000005", + AZURE_KEY_VAULT_SECRET_REFERENCES: JSON.stringify(references), + } + + expect(parseAzureSecretConfiguration(environment, "provision-learning").references).toEqual( + references, + ) + expect(() => + parseAzureSecretConfiguration( + { + ...environment, + AZURE_KEY_VAULT_SECRET_REFERENCES: JSON.stringify({ + DATABASE_URL: references.DATABASE_URL, + }), + }, + "provision-learning", + ), + ).toThrow() + expect(() => + parseAzureSecretConfiguration( + { + ...environment, + AZURE_KEY_VAULT_SECRET_REFERENCES: JSON.stringify({ + HUB_LEARNING_PASSWORD: references.HUB_LEARNING_PASSWORD, + }), + }, + "provision-learning", + ), + ).toThrow() + expect(() => + parseAzureSecretConfiguration( + { + ...environment, + AZURE_KEY_VAULT_SECRET_REFERENCES: JSON.stringify({ + DATABASE_URL: references.DATABASE_URL, + HUB_RUNTIME_PASSWORD: references.HUB_LEARNING_PASSWORD, + }), + }, + "provision-learning", + ), + ).toThrow() + expect(() => + parseAzureSecretConfiguration( + { + ...environment, + AZURE_KEY_VAULT_SECRET_REFERENCES: JSON.stringify({ + ...references, + HUB_RUNTIME_PASSWORD: references.HUB_LEARNING_PASSWORD, + }), + }, + "provision-learning", + ), + ).toThrow() + }) + + it("requires a versioned learning password for an existing installation", () => { + const environment = { + AZURE_CLIENT_ID: "00000000-0000-0000-0000-000000000005", + AZURE_KEY_VAULT_SECRET_REFERENCES: JSON.stringify({ + DATABASE_URL: + "https://fixture.vault.azure.net/secrets/admin-database/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + HUB_LEARNING_PASSWORD: "https://fixture.vault.azure.net/secrets/learning-password", + }), + } + + expect(() => parseAzureSecretConfiguration(environment, "provision-learning")).toThrow() + }) + + it("allows the optional learning migration URL in setup", () => { + const references = { + DATABASE_URL: "https://fixture.vault.azure.net/secrets/migration-database", + REPLICA_LEARNING_MIGRATION_DATABASE_URL: + "https://fixture.vault.azure.net/secrets/learning-migration-database", + } + const environment = { + AZURE_CLIENT_ID: "00000000-0000-0000-0000-000000000003", + AZURE_KEY_VAULT_SECRET_REFERENCES: JSON.stringify(references), + } + + expect(parseAzureSecretConfiguration(environment, "setup").references).toEqual(references) + }) + it.each([undefined, "", "synthetic-client-token", " 00000000-0000-0000-0000-000000000001"])( "rejects a missing or malformed explicit managed identity", (clientId) => { @@ -94,26 +186,30 @@ describe("parseAzureSecretConfiguration()", () => { expect(() => parseAzureSecretConfiguration(environment, target)).toThrow() }) - it.each(["DATABASE_URL", "HUB_MIGRATION_PASSWORD", "HUB_RUNTIME_PASSWORD"])( - "requires the provisioning reference %s", - (missing) => { - const references: Record = { - DATABASE_URL: - "https://fixture.vault.azure.net/secrets/admin-database/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - HUB_MIGRATION_PASSWORD: - "https://fixture.vault.azure.net/secrets/migration-password/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - HUB_RUNTIME_PASSWORD: - "https://fixture.vault.azure.net/secrets/runtime-password/cccccccccccccccccccccccccccccccc", - } - delete references[missing] - const environment = { - AZURE_CLIENT_ID: "00000000-0000-0000-0000-000000000005", - AZURE_KEY_VAULT_SECRET_REFERENCES: JSON.stringify(references), - } + it.each([ + "DATABASE_URL", + "HUB_MIGRATION_PASSWORD", + "HUB_RUNTIME_PASSWORD", + "HUB_LEARNING_PASSWORD", + ])("requires the provisioning reference %s", (missing) => { + const references: Record = { + DATABASE_URL: + "https://fixture.vault.azure.net/secrets/admin-database/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + HUB_MIGRATION_PASSWORD: + "https://fixture.vault.azure.net/secrets/migration-password/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + HUB_RUNTIME_PASSWORD: + "https://fixture.vault.azure.net/secrets/runtime-password/cccccccccccccccccccccccccccccccc", + HUB_LEARNING_PASSWORD: + "https://fixture.vault.azure.net/secrets/learning-password/dddddddddddddddddddddddddddddddd", + } + delete references[missing] + const environment = { + AZURE_CLIENT_ID: "00000000-0000-0000-0000-000000000005", + AZURE_KEY_VAULT_SECRET_REFERENCES: JSON.stringify(references), + } - expect(() => parseAzureSecretConfiguration(environment, "provision")).toThrow() - }, - ) + expect(() => parseAzureSecretConfiguration(environment, "provision")).toThrow() + }) it.each(["setup", "provision"] as const)( "does not grant additional secret access to %s", @@ -127,6 +223,8 @@ describe("parseAzureSecretConfiguration()", () => { "https://fixture.vault.azure.net/secrets/migration-password/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", HUB_RUNTIME_PASSWORD: "https://fixture.vault.azure.net/secrets/runtime-password/cccccccccccccccccccccccccccccccc", + HUB_LEARNING_PASSWORD: + "https://fixture.vault.azure.net/secrets/learning-password/eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", } : {}), SERVICE_API_KEY: @@ -150,6 +248,8 @@ describe("parseAzureSecretConfiguration()", () => { HUB_MIGRATION_PASSWORD: "https://fixture.vault.azure.net/secrets/migration-password", HUB_RUNTIME_PASSWORD: "https://fixture.vault.azure.net/secrets/runtime-password/cccccccccccccccccccccccccccccccc", + HUB_LEARNING_PASSWORD: + "https://fixture.vault.azure.net/secrets/learning-password/dddddddddddddddddddddddddddddddd", }), } diff --git a/hub/server/utils/parse-azure-secret-configuration/index.ts b/hub/server/utils/parse-azure-secret-configuration/index.ts index c14d2520..4f7812e7 100644 --- a/hub/server/utils/parse-azure-secret-configuration/index.ts +++ b/hub/server/utils/parse-azure-secret-configuration/index.ts @@ -10,7 +10,7 @@ export function parseAzureSecretConfiguration( const clientId = environment.AZURE_CLIENT_ID const input = environment.AZURE_KEY_VAULT_SECRET_REFERENCES if ( - !["runtime", "setup", "provision"].includes(target) || + !["runtime", "setup", "provision", "provision-learning"].includes(target) || !clientId || !/^[a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}$/.test(clientId) || !input || @@ -29,12 +29,17 @@ export function parseAzureSecretConfiguration( const names = entries.map(([name]) => name) const required = target === "provision" - ? ["DATABASE_URL", "HUB_MIGRATION_PASSWORD", "HUB_RUNTIME_PASSWORD"] - : ["DATABASE_URL"] + ? ["DATABASE_URL", "HUB_MIGRATION_PASSWORD", "HUB_RUNTIME_PASSWORD", "HUB_LEARNING_PASSWORD"] + : target === "provision-learning" + ? ["DATABASE_URL", "HUB_LEARNING_PASSWORD"] + : ["DATABASE_URL"] + const allowed = + target === "setup" ? [...required, "REPLICA_LEARNING_MIGRATION_DATABASE_URL"] : required const reserved = new Set([ "AZURE_CLIENT_ID", "AZURE_KEY_VAULT_SECRET_REFERENCES", "DATABASE_RUNTIME_ROLE", + "REPLICA_LEARNING_RUNTIME_ROLE", "NODE_ENV", "RUNTIME_MODE", "HOST", @@ -50,7 +55,7 @@ export function parseAzureSecretConfiguration( !entries.length || entries.length > 64 || required.some((name) => !names.includes(name)) || - (target !== "runtime" && names.some((name) => !required.includes(name))) + (target !== "runtime" && names.some((name) => !allowed.includes(name))) ) { throw invalid() } @@ -64,7 +69,8 @@ export function parseAzureSecretConfiguration( !/^https:\/\/[a-zA-Z0-9-]+\.vault\.azure\.net\/secrets\/[a-zA-Z0-9-]+(?:\/[a-fA-F0-9]{32})?$/.test( url, ) || - (target === "provision" && new URL(url).pathname.split("/").length !== 4) + ((target === "provision" || target === "provision-learning") && + new URL(url).pathname.split("/").length !== 4) ) { throw invalid() } diff --git a/hub/server/utils/parse-azure-secret-configuration/types.ts b/hub/server/utils/parse-azure-secret-configuration/types.ts index b6acaf21..cb0c099c 100644 --- a/hub/server/utils/parse-azure-secret-configuration/types.ts +++ b/hub/server/utils/parse-azure-secret-configuration/types.ts @@ -1,4 +1,4 @@ -export type AzureEntrypoint = "runtime" | "setup" | "provision" +export type AzureEntrypoint = "runtime" | "setup" | "provision" | "provision-learning" export interface AzureSecretConfiguration { managedIdentityClientId: string diff --git a/hub/test/fixtures/learning/report-runtime.mjs b/hub/test/fixtures/learning/report-runtime.mjs index 5d94813b..7a5f7d7e 100644 --- a/hub/test/fixtures/learning/report-runtime.mjs +++ b/hub/test/fixtures/learning/report-runtime.mjs @@ -1,13 +1,34 @@ -import { stat } from "node:fs/promises" +import { readFile, stat, writeFile } from "node:fs/promises" +import { join } from "node:path" const temporaryDirectory = process.env.TMPDIR const status = await stat(temporaryDirectory) +const arguments_ = process.argv.slice(2) +const directoryIndex = arguments_.indexOf("--dir") +const directoryArgument = arguments_.find((argument) => argument.startsWith("--dir=")) +const directory = + directoryIndex !== -1 ? arguments_[directoryIndex + 1] : directoryArgument?.slice("--dir=".length) +let config +if (directory !== undefined) { + try { + config = await readFile(join(directory, "config.json"), "utf8") + } catch (error) { + if (error.code !== "ENOENT") throw error + } +} -process.stdout.write( - JSON.stringify({ - arguments: process.argv.slice(2), - environment: process.env, - temporaryDirectory, - temporaryDirectoryMode: status.mode & 0o777, - }), -) +const report = JSON.stringify({ + arguments: arguments_, + config, + environment: process.env, + temporaryDirectory, + temporaryDirectoryMode: status.mode & 0o777, +}) +const failureIndex = arguments_.indexOf("--fixture-fail-report") +if (failureIndex !== -1) { + await writeFile(arguments_[failureIndex + 1], report) + process.stderr.write("error (invalid_request): fixture failure\n") + process.exitCode = 2 +} else { + process.stdout.write(report) +} From 15137c9b5269cd7cdecf1655a2991e7bb7cabfe6 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 10:13:58 -0800 Subject: [PATCH 03/18] feat(azure): provision a separate learning login Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 836fcecf-e7a9-4975-acd2-bf761098f711 --- infrastructure/README.md | 8 +- infrastructure/azure/application.tf | 1 + infrastructure/azure/install/index.test.ts | 93 +++++- infrastructure/azure/install/index.ts | 15 +- infrastructure/azure/install/inputs/index.ts | 20 +- .../azure/install/provision/index.ts | 264 +++++++++++------- infrastructure/azure/install/secrets/index.ts | 21 ++ .../azure/installation.tfvars.example | 6 + infrastructure/azure/post/configure/index.ts | 11 +- infrastructure/azure/post/index.test.ts | 31 +- infrastructure/azure/post/index.ts | 3 + infrastructure/azure/post/types.ts | 1 + infrastructure/azure/provision/main.tf | 14 +- .../provision/tests/provision.tftest.hcl | 42 ++- infrastructure/azure/roles.tf | 2 +- infrastructure/azure/setup.tf | 9 +- .../azure/tests/deployment.tftest.hcl | 27 +- infrastructure/azure/variables.tf | 26 +- 18 files changed, 448 insertions(+), 146 deletions(-) diff --git a/infrastructure/README.md b/infrastructure/README.md index b88869ea..6d2ae0d9 100644 --- a/infrastructure/README.md +++ b/infrastructure/README.md @@ -61,6 +61,8 @@ It then uses separate protected Terraform state files for the foundation, applic The wizard builds and pushes a Linux AMD64 image and deploys its immutable digest. On first installation, Hub remains absent while a separate private-network job initializes the database roles. This job has its own temporary managed identity and secret-scoped administrator/password access; neither Hub nor normal setup receives administrator access. After success, the wizard records completion in Key Vault and destroys the temporary job, identity, and grants before invoking the existing serialized release procedure. +New installations use the separate PostgreSQL learning login. On an existing installation, the wizard provisions that login separately but keeps SQLite selected. Before import, stop old writers, hold the release lock, and run setup to migrate the learning schema. With the migration URL supplied privately as `REPLICA_LEARNING_MIGRATION_DATABASE_URL`, run `node dist/server/scripts/grant-learning-database-access/index.js` from the Hub image to grant the learning login access. Follow the [learning history migration](../hub/docs/learning-foundation.md) before adding `learning_database_secret` to the private saved inputs and running a serialized update. Keep SQLite selected if the old history cannot be recovered or verified. The wizard never treats an unavailable old revision's disk as proof that no history exists. + The final release stops old revisions, runs migrations and schedule setup, starts Hub, and checks HTTPS readiness. Readiness is not authorization. After installation, use the separate [post-setup menu](#post-setup-configuration) to enable setup access and GitHub sign-in without another build or database setup. Artifact import, hosted previews, and reviews are not available yet. ### Saved configuration and repeat runs @@ -450,7 +452,7 @@ Each installation has its own resource group tagged with its application, instal Two optional modules have separate Terraform states and lifecycles. [`azure/foundation/`](azure/foundation/main.tf) creates an installation-owned ACR and RBAC-enabled Key Vault in a separate resource group, with `AcrPush` and `Key Vault Secrets Officer` grants for the deployment identity. The vault has 90-day soft deletion and purge protection. Pass its registry and vault outputs to the main installation; the main module still accepts existing resources and never owns their teardown. -[`azure/provision/`](azure/provision/main.tf) creates a temporary private-network database-role provisioning job and identity in the installation's Container Apps environment. It accepts the same immutable image and exactly three versioned Key Vault references: `DATABASE_URL` for the administrator, `HUB_MIGRATION_PASSWORD`, and `HUB_RUNTIME_PASSWORD`. Each secret URL must belong to the supplied `vault_id`. Its Azure startup entrypoint retrieves those values through the provisioning identity before importing database provisioning code. Omit `registry_id` for a public image; an existing ACR requires its resource ID and grants only the provisioning identity pull access. The job has one replica, no automatic retries, and a ten-minute timeout. An authorized operator must run it once against a fresh database, verify that exact execution succeeded, and remove the temporary job, identity, and grants before release. Do not rerun it against an installed database or grant its administrator secret to Hub or setup. The existing private-network operator script remains an alternative. +[`azure/provision/`](azure/provision/main.tf) creates a temporary private-network database-role provisioning job and identity in the installation's Container Apps environment. Fresh `provision` requires four versioned Key Vault references: administrator `DATABASE_URL`, `HUB_MIGRATION_PASSWORD`, `HUB_RUNTIME_PASSWORD`, and `HUB_LEARNING_PASSWORD`. For an existing installation, `provision-learning` requires only the administrator URL and learning password. Each secret URL must belong to the supplied `vault_id`. The startup entrypoint retrieves those values through the provisioning identity before importing database provisioning code. Omit `registry_id` for a public image; an existing ACR grants only the provisioning identity pull access. Each job has one replica, no automatic retries, and a ten-minute timeout. Verify the exact successful execution and remove its temporary job, identity, and grants before release. Do not rerun fresh provisioning against an installed database or grant its administrator secret to Hub or setup. Initialize each optional module against its own protected backend state key, review its declared inputs and Terraform plan, and authorize its apply separately. Never share a state key with the main installation. Neither module starts Hub or replaces the serialized release command. @@ -475,9 +477,9 @@ These values are stored directly in Terraform state and Container Apps configura Terraform may include an invalid input line in its error output, including any credential supplied on that line. Remove credentials from the input before running Terraform and protect or redact any captured output if a credential was supplied. -Azure containers run `node dist/server/scripts/azure-entrypoint/index.js runtime`, `setup`, or `provision`. The entrypoint validates the complete reference map and explicit managed-identity client ID before fetching anything. It retrieves values directly from Key Vault with that identity, applies them to the workload's in-memory environment only after all reads succeed, then imports the selected workload. Startup secret retrieval has one 30-second deadline, with a bounded exponential retry for transient authorization, throttling, and service errors under the same identity; it stops on cancellation or failure before API/worker startup, database provisioning, or migrations. Secret-retrieval errors do not print token, URL, response-body, or secret contents. Registry pulling still uses Azure's normal managed-identity registry configuration; this does not bypass image-pull, DNS, or access failures. +Azure containers run `node dist/server/scripts/azure-entrypoint/index.js` with `runtime`, `setup`, `provision`, or `provision-learning`. The entrypoint validates the complete reference map and explicit managed-identity client ID before fetching anything. It retrieves values directly from Key Vault with that identity, applies them to the workload's in-memory environment only after all reads succeed, then imports the selected workload. Startup secret retrieval has one 30-second deadline, with a bounded exponential retry for transient authorization, throttling, and service errors under the same identity; it stops on cancellation or failure before API/worker startup, database provisioning, or migrations. Secret-retrieval errors do not print token, URL, response-body, or secret contents. Registry pulling still uses Azure's normal managed-identity registry configuration; this does not bypass image-pull, DNS, or access failures. -Setup can receive only its migration `DATABASE_URL`; provisioning requires exactly its three versioned administrator/password references. Runtime requires its runtime `DATABASE_URL` and may receive validated additional references. References cannot overwrite already-defined environment values or deployment-owned configuration, including the identity and reference-map fields. Existing secret-scoped grants remain unchanged; no vault-wide access is added. Versioned URLs are recommended for deliberate rotation. An unversioned runtime/setup URL selects the latest value only at startup, not through Container Apps' background secret refresh. Restart through a reviewed serialized release to pick up a new version. +Setup receives its migration URL as both `DATABASE_URL` and `REPLICA_LEARNING_MIGRATION_DATABASE_URL`; it needs no runtime credential. Provisioning requires exactly the versioned references for its selected mode. Runtime requires its runtime `DATABASE_URL` and may receive the separate learning URL and validated additional references. References cannot overwrite already-defined environment values or deployment-owned configuration, including the identity and reference-map fields. No vault-wide access is added. Versioned URLs are recommended for deliberate rotation. An unversioned runtime/setup URL selects the latest value only at startup, not through Container Apps' background secret refresh. Restart through a reviewed serialized release to pick up a new version. Terraform ignores only Azure-assigned PostgreSQL availability-zone and Container Apps infrastructure-resource-group values. It still checks other drift and owns both images. The installation output exposes authoritative app, resource-group, and storage-account IDs; before the first release, the app ID is `null`. diff --git a/infrastructure/azure/application.tf b/infrastructure/azure/application.tf index d3fd8b00..c60f5c3c 100644 --- a/infrastructure/azure/application.tf +++ b/infrastructure/azure/application.tf @@ -52,6 +52,7 @@ locals { AZURE_CLIENT_ID = azurerm_user_assigned_identity.hub.client_id AZURE_KEY_VAULT_SECRET_REFERENCES = jsonencode(merge( { DATABASE_URL = var.runtime_database_secret.secret_id }, + var.learning_database_secret == null ? {} : { REPLICA_LEARNING_DATABASE_URL = var.learning_database_secret.secret_id }, { for name, reference in var.runtime_secret_references : name => reference.secret_id }, )) }, local.github_environment) diff --git a/infrastructure/azure/install/index.test.ts b/infrastructure/azure/install/index.test.ts index 1fb03969..6d8053d8 100644 --- a/infrastructure/azure/install/index.test.ts +++ b/infrastructure/azure/install/index.test.ts @@ -58,6 +58,7 @@ afterEach(async () => { async function scenario({ existing = false, + learningProvisioned = true, releaseFails = false, priorProvisioning = false, provisioningFails = false, @@ -82,9 +83,12 @@ async function scenario({ const image = `registry.azurecr.io/replica-hub@sha256:${"a".repeat(64)}` const events: { command: string[]; env?: NodeJS.ProcessEnv }[] = [] const messages: string[] = [] - const secretValues = new Map( - existing ? [["database-provisioned", config.azure.resourceGroup]] : [], - ) + const secretValues = new Map([ + ...(existing ? [["database-provisioned", config.azure.resourceGroup]] : []), + ...(existing && learningProvisioned + ? [["learning-database-provisioned", config.azure.resourceGroup]] + : []), + ] as [string, string][]) const vaultId = `/subscriptions/${config.azure.subscriptionId}/resourceGroups/foundation/providers/Microsoft.KeyVault/vaults/testvault` const foundation = { vault_id: vaultId, @@ -897,6 +901,18 @@ it("uses one deployment approval for dirty-source publication, nonempty plans, t ), ).toBe(false) expect(s.secretValues.get("database-provisioned")).toBe(s.config.azure.resourceGroup) + expect(s.secretValues.get("learning-database-provisioned")).toBe(s.config.azure.resourceGroup) + const workspace = installationWorkspace(s.config, s.directory) + const provision = JSON.parse(await readFile(join(workspace, "provision.tfvars.json"), "utf8")) + expect(provision.mode).toBe("provision") + expect(Object.keys(provision.secret_urls).sort()).toEqual([ + "DATABASE_URL", + "HUB_LEARNING_PASSWORD", + "HUB_MIGRATION_PASSWORD", + "HUB_RUNTIME_PASSWORD", + ]) + const inputs = JSON.parse(await readFile(join(workspace, "installation.tfvars.json"), "utf8")) + expect(inputs.learning_database_secret.secret_id).toContain("/secrets/postgres-learning-url/") const serialized = JSON.stringify({ commands, messages: s.messages }) for (const [name, value] of s.secretValues) { if (name.includes("password") || name.endsWith("-url")) expect(serialized).not.toContain(value) @@ -1056,6 +1072,77 @@ it("updates an installed app only through the release orchestrator and never rer ).toBe(false) }) +it("provisions only the learning role on a SQLite installation without activating PostgreSQL", async () => { + const s = await scenario({ existing: true, learningProvisioned: false }) + + await installAzure(s.config, s) + + const workspace = installationWorkspace(s.config, s.directory) + const provision = JSON.parse(await readFile(join(workspace, "provision.tfvars.json"), "utf8")) + expect(provision.mode).toBe("provision-learning") + expect(Object.keys(provision.secret_urls).sort()).toEqual([ + "DATABASE_URL", + "HUB_LEARNING_PASSWORD", + ]) + const inputs = JSON.parse(await readFile(join(workspace, "installation.tfvars.json"), "utf8")) + expect(inputs).not.toHaveProperty("learning_database_secret") + expect(s.secretValues.get("learning-database-provisioned")).toBe(s.config.azure.resourceGroup) + expect( + s.events.filter(({ command }) => command.slice(0, 4).join(" ") === "az containerapp job start"), + ).toHaveLength(1) + expect(s.released()).toBe(true) +}) + +it("cleans up a completed learning provisioning job without rerunning it", async () => { + const s = await scenario({ existing: true }) + const run: RunCommand = async (executable, args, options) => { + const result = await s.run(executable, args, options) + if ( + executable === "terraform" && + args[1] === "state" && + options?.env?.TF_DATA_DIR?.endsWith("/learning-provision") + ) + return "azurerm_container_app_job.provision" + return result + } + + await installAzure(s.config, { ...s, run }) + + expect( + s.events.some(({ command }) => command.slice(0, 4).join(" ") === "az containerapp job start"), + ).toBe(false) + expect( + s.events.some( + ({ command, env }) => + command[0] === "terraform" && + command[2] === "plan" && + command.includes("-destroy") && + env?.TF_DATA_DIR?.endsWith("/learning-provision"), + ), + ).toBe(true) + expect(s.released()).toBe(true) +}) + +it("refuses to replay learning provisioning with prior executions but no marker", async () => { + const s = await scenario({ existing: true, learningProvisioned: false, priorProvisioning: true }) + const run: RunCommand = async (executable, args, options) => { + const result = await s.run(executable, args, options) + if ( + executable === "terraform" && + args[1] === "state" && + options?.env?.TF_DATA_DIR?.endsWith("/learning-provision") + ) + return "azurerm_container_app_job.provision" + return result + } + + await expect(installAzure(s.config, { ...s, run })).rejects.toThrow("prior executions") + expect( + s.events.some(({ command }) => command.slice(0, 4).join(" ") === "az containerapp job start"), + ).toBe(false) + expect(s.released()).toBe(false) +}) + it("corrects an image-build proxy under the same installation lease without replaying infrastructure or credentials", async () => { const s = await scenario({ imageFailsOnce: true }) delete s.config.npmRegistry diff --git a/infrastructure/azure/install/index.ts b/infrastructure/azure/install/index.ts index 535e157d..6d573a02 100644 --- a/infrastructure/azure/install/index.ts +++ b/infrastructure/azure/install/index.ts @@ -110,9 +110,10 @@ async function install( "foundation-backend.hcl", "app-backend.hcl", "provision-backend.hcl", + "learning-provision-backend.hcl", ]) await privateFile(join(directory, file)) - for (const module of ["foundation", "app", "provision"]) + for (const module of ["foundation", "app", "provision", "learning-provision"]) await privateDirectory(join(directory, "terraform", module)) const env: NodeJS.ProcessEnv = { ARM_SUBSCRIPTION_ID: config.azure.subscriptionId, @@ -242,6 +243,7 @@ async function install( ) } const appCreated = appState.includes("azurerm_container_app.hub[0]") + const databaseProvisioned = await secrets.provisioned() const variables = join(directory, "installation.tfvars.json") const inputs = { ...postgres, @@ -256,12 +258,20 @@ async function install( acr_id: resources.registry_id, runtime_database_secret: { key_vault_id: resources.vault_id, secret_id: secrets.runtimeUrl }, setup_database_secret: { key_vault_id: resources.vault_id, secret_id: secrets.migrationUrl }, + ...(!appCreated && !databaseProvisioned && !operatorInputs.learning_database_secret + ? { + learning_database_secret: { + key_vault_id: resources.vault_id, + secret_id: secrets.learningUrl, + }, + } + : {}), } await writePrivateFile(variables, JSON.stringify({ ...inputs, ...operatorInputs })) if (!appCreated) { ui.status("Bootstrapping infrastructure with Hub stopped") await app.apply(variables) - } else if (!(await secrets.provisioned())) { + } else if (!databaseProvisioned) { throw new Error( "An app exists without the wizard's database provisioning marker. Review ownership; do not provision database roles again.", ) @@ -280,6 +290,7 @@ async function install( secrets, image, await state.backend("provision"), + await state.backend("learning-provision"), ) await ui.phase?.("release") await recoverLease(context, installation.storage_account, "releases", "deployment.lock") diff --git a/infrastructure/azure/install/inputs/index.ts b/infrastructure/azure/install/inputs/index.ts index 57ffadc3..ad300b34 100644 --- a/infrastructure/azure/install/inputs/index.ts +++ b/infrastructure/azure/install/inputs/index.ts @@ -7,6 +7,7 @@ import type { DeploymentConfig } from "../../../installer/types.ts" type SecretReference = { key_vault_id: string; secret_id: string } interface OperatorInputs { + learning_database_secret?: SecretReference runtime_environment_variables?: Record hub_application_origin?: string github_app_id?: string @@ -56,6 +57,7 @@ export async function readInstallationInputs( ] const optional = [ "runtime_environment_variables", + "learning_database_secret", "hub_application_origin", "github_app_id", "github_client_id", @@ -98,6 +100,18 @@ export async function readInstallationInputs( return { key_vault_id: secret.key_vault_id, secret_id: secret.secret_id } } const result: OperatorInputs = {} + if (inputs.learning_database_secret != null) { + const learning = reference(inputs.learning_database_secret) + const identity = (secret: SecretReference) => + `${secret.key_vault_id}/secrets/${new URL(secret.secret_id).pathname.split("/")[2]}`.toLowerCase() + if ( + [reference(inputs.setup_database_secret), reference(inputs.runtime_database_secret)].some( + (secret) => identity(secret) === identity(learning), + ) + ) + throw invalid() + result.learning_database_secret = learning + } for (const key of ["github_app_id", "github_app_installation_id"] as const) { const value = inputs[key] if (value == null) continue @@ -173,6 +187,9 @@ export async function readInstallationInputs( const reserved = [ "DATABASE_URL", "DATABASE_RUNTIME_ROLE", + "REPLICA_LEARNING_DATABASE_URL", + "REPLICA_LEARNING_MIGRATION_DATABASE_URL", + "REPLICA_LEARNING_RUNTIME_ROLE", "NODE_ENV", "RUNTIME_MODE", "HOST", @@ -191,7 +208,8 @@ export async function readInstallationInputs( typeof inputs.runtime_secret_references !== "object" || inputs.runtime_secret_references === null || Array.isArray(inputs.runtime_secret_references) || - Object.keys(inputs.runtime_secret_references).length > 63 + Object.keys(inputs.runtime_secret_references).length > + (result.learning_database_secret ? 62 : 63) ) throw invalid() const setup = reference(inputs.setup_database_secret) diff --git a/infrastructure/azure/install/provision/index.ts b/infrastructure/azure/install/provision/index.ts index 0fe66d22..9b6f15fa 100644 --- a/infrastructure/azure/install/provision/index.ts +++ b/infrastructure/azure/install/provision/index.ts @@ -16,22 +16,25 @@ export async function provisionDatabase( secrets: Awaited>, image: string, backend: string, + learningBackend: string, ) { const { run, ui, env, config, directory, azure } = context - const module = terraformModule({ - directory: resolve(import.meta.dirname, "../../provision"), - dataDirectory: join(directory, "terraform", "provision"), - run, - ui, - env, - preapproved: context.approval !== undefined, - retryApply: retryableProvisioningFailure, - signal: context.signal, - findUntracked: existingRoleAssignment(azure, config.azure.subscriptionId), - }) - await module.init(backend) - const complete = await secrets.provisioned() - if (complete && !(await module.state()).length) return + const moduleFor = (name: string) => + terraformModule({ + directory: resolve(import.meta.dirname, "../../provision"), + dataDirectory: join(directory, "terraform", name), + run, + ui, + env, + preapproved: context.approval !== undefined, + retryApply: retryableProvisioningFailure, + signal: context.signal, + findUntracked: existingRoleAssignment(azure, config.azure.subscriptionId), + }) + const freshModule = moduleFor("provision") + const learningModule = moduleFor("learning-provision") + await freshModule.init(backend) + await learningModule.init(learningBackend) const lease = await acquireLease( context, installation.storage_account, @@ -58,113 +61,164 @@ export async function provisionDatabase( ) } const variables = join(directory, "provision.tfvars.json") - await writePrivateFile( - variables, - JSON.stringify({ - subscription_id: config.azure.subscriptionId, - name: config.name, - location: config.azure.location, - resource_group: installation.resource_group, - environment_id: installation.environment_id, - registry_id: foundation.registry_id, - image, - vault_id: foundation.vault_id, - secret_urls: secrets.provisioning, - }), - ) - if (complete) { - const job = await module.output("job_name") - const executions = JSON.parse( - await azure( - "containerapp", - "job", - "execution", - "list", - "--name", - job, - "--resource-group", - installation.resource_group, - ), - ) as { properties: { status: string } }[] - if (executions.some(({ properties }) => !terminal.includes(properties.status))) { - throw new Error( - "A provisioning execution is still running. Temporary access cannot be removed yet.", - ) - } - } else { - await module.apply(variables) - const job = await module.output("job_name") - const executions = JSON.parse( - await azure( - "containerapp", - "job", - "execution", - "list", - "--name", - job, - "--resource-group", - installation.resource_group, - ), - ) as { name: string; properties: { status: string } }[] - if (executions.length) { - throw new Error( - "Database provisioning has prior executions but no completion marker. Inspect the database and exact job execution; do not rerun fresh-database provisioning blindly.", - ) + const complete = await secrets.provisioned() + const learningComplete = await secrets.learningProvisioned() + const freshState = await freshModule.state() + const learningState = await learningModule.state() + if (learningState.length && (!complete || freshState.length)) { + throw new Error( + "Learning provisioning state conflicts with the database marker or fresh provisioning state. Inspect both states and database ownership before recovery.", + ) + } + const cleanup = async (module: ReturnType) => { + await module.apply(variables, { + destroy: true, + allowedDeletions: [ + "azurerm_container_app_job.provision", + "azurerm_user_assigned_identity.provision", + "azurerm_role_assignment.image[0]", + 'azurerm_role_assignment.secrets["DATABASE_URL"]', + 'azurerm_role_assignment.secrets["HUB_MIGRATION_PASSWORD"]', + 'azurerm_role_assignment.secrets["HUB_RUNTIME_PASSWORD"]', + 'azurerm_role_assignment.secrets["HUB_LEARNING_PASSWORD"]', + ], + }) + } + const provision = async ( + module: ReturnType, + mode: "provision" | "provision-learning", + done: boolean, + ) => { + const state = await module.state() + if (done && !state.length) return + if (!done && state.includes("azurerm_container_app_job.provision")) { + const job = await module.output("job_name") + const executions = JSON.parse( + await azure( + "containerapp", + "job", + "execution", + "list", + "--name", + job, + "--resource-group", + installation.resource_group, + ), + ) as { name: string }[] + if (executions.length) { + throw new Error( + "Database provisioning has prior executions but no completion marker. Inspect the database and exact job execution; do not rerun provisioning blindly.", + ) + } } - const execution = JSON.parse( - await azure( - "containerapp", - "job", - "start", - "--name", - job, - "--resource-group", - installation.resource_group, - ), - ) as { name: string } - const deadline = performance.now() + 720_000 - let success = false - while (performance.now() < deadline) { - const result = JSON.parse( + await writePrivateFile( + variables, + JSON.stringify({ + subscription_id: config.azure.subscriptionId, + name: config.name, + location: config.azure.location, + resource_group: installation.resource_group, + environment_id: installation.environment_id, + registry_id: foundation.registry_id, + image, + vault_id: foundation.vault_id, + mode, + secret_urls: mode === "provision" ? secrets.provisioning : secrets.learningProvisioning, + }), + ) + if (done) { + const job = await module.output("job_name") + const executions = JSON.parse( await azure( "containerapp", "job", "execution", - "show", + "list", "--name", job, "--resource-group", installation.resource_group, - "--job-execution-name", - execution.name, ), - ) as { properties: { status: string } } - if (result.properties.status === "Succeeded") { - success = true - break + ) as { properties: { status: string } }[] + if (executions.some(({ properties }) => !terminal.includes(properties.status))) { + throw new Error( + "A provisioning execution is still running. Temporary access cannot be removed yet.", + ) } - if (["Failed", "Stopped", "Canceled"].includes(result.properties.status)) { + } else { + await module.apply(variables) + const job = await module.output("job_name") + const executions = JSON.parse( + await azure( + "containerapp", + "job", + "execution", + "list", + "--name", + job, + "--resource-group", + installation.resource_group, + ), + ) as { name: string; properties: { status: string } }[] + if (executions.length) { throw new Error( - "Fresh-database provisioning failed. Inspect the named provisioning job and database ownership; the release lock is retained.", + "Database provisioning has prior executions but no completion marker. Inspect the database and exact job execution; do not rerun provisioning blindly.", ) } - await timers.setTimeout(5_000) + await lease.verify() + const execution = JSON.parse( + await azure( + "containerapp", + "job", + "start", + "--name", + job, + "--resource-group", + installation.resource_group, + ), + ) as { name: string } + const deadline = performance.now() + 720_000 + let success = false + while (performance.now() < deadline) { + const result = JSON.parse( + await azure( + "containerapp", + "job", + "execution", + "show", + "--name", + job, + "--resource-group", + installation.resource_group, + "--job-execution-name", + execution.name, + ), + ) as { properties: { status: string } } + if (result.properties.status === "Succeeded") { + success = true + break + } + if (["Failed", "Stopped", "Canceled"].includes(result.properties.status)) { + throw new Error( + "Database provisioning failed. Inspect the named provisioning job and database ownership; the release lock is retained.", + ) + } + await timers.setTimeout(5_000) + } + if (!success) + throw new Error("Provisioning timed out. Check the execution before releasing any lock.") + await lease.verify() + if (mode === "provision") { + await secrets.markLearningProvisioned() + await secrets.markProvisioned() + } else { + await secrets.markLearningProvisioned() + } } - if (!success) - throw new Error("Provisioning timed out. Check the execution before releasing any lock.") - await secrets.markProvisioned() + await cleanup(module) } - await module.apply(variables, { - destroy: true, - allowedDeletions: [ - "azurerm_container_app_job.provision", - "azurerm_user_assigned_identity.provision", - "azurerm_role_assignment.image[0]", - 'azurerm_role_assignment.secrets["DATABASE_URL"]', - 'azurerm_role_assignment.secrets["HUB_MIGRATION_PASSWORD"]', - 'azurerm_role_assignment.secrets["HUB_RUNTIME_PASSWORD"]', - ], - }) + await provision(freshModule, "provision", complete) + await provision(learningModule, "provision-learning", learningComplete || !complete) await lease.release() } finally { lease.reportRetained() diff --git a/infrastructure/azure/install/secrets/index.ts b/infrastructure/azure/install/secrets/index.ts index 4c66184f..6d22e7ff 100644 --- a/infrastructure/azure/install/secrets/index.ts +++ b/infrastructure/azure/install/secrets/index.ts @@ -62,6 +62,7 @@ export async function installationSecrets(context: AzureInstallation, foundation const admin = await ensure("postgres-admin-password", password) const migration = await ensure("postgres-migration-password", password) const runtime = await ensure("postgres-runtime-password", password) + const learning = await ensure("postgres-learning-password", password) const host = `${config.name}-postgres.postgres.database.azure.com` const url = (role: string, password: string) => `postgresql://${role}:${encodeURIComponent(password)}@${host}:5432/replica?sslmode=verify-full` @@ -72,14 +73,23 @@ export async function installationSecrets(context: AzureInstallation, foundation const runtimeUrl = await ensure("postgres-runtime-url", () => url("replica_runtime", runtime.value), ) + const learningUrl = await ensure("postgres-learning-url", () => + url("replica_learning_runtime", learning.value), + ) return { adminPassword: admin.value, migrationUrl: migrationUrl.id, runtimeUrl: runtimeUrl.id, + learningUrl: learningUrl.id, provisioning: { DATABASE_URL: adminUrl.id, HUB_MIGRATION_PASSWORD: migration.id, HUB_RUNTIME_PASSWORD: runtime.id, + HUB_LEARNING_PASSWORD: learning.id, + }, + learningProvisioning: { + DATABASE_URL: adminUrl.id, + HUB_LEARNING_PASSWORD: learning.id, }, async provisioned() { return ( @@ -90,5 +100,16 @@ export async function installationSecrets(context: AzureInstallation, foundation async markProvisioned() { await put("database-provisioned", config.azure.resourceGroup) }, + async learningProvisioned() { + if (!names.has("learning-database-provisioned")) return false + if ((await read("learning-database-provisioned")).value !== config.azure.resourceGroup) + throw new Error( + "The learning database provisioning marker belongs to another installation.", + ) + return true + }, + async markLearningProvisioned() { + await put("learning-database-provisioned", config.azure.resourceGroup) + }, } } diff --git a/infrastructure/azure/installation.tfvars.example b/infrastructure/azure/installation.tfvars.example index 11151738..86f2d4e1 100644 --- a/infrastructure/azure/installation.tfvars.example +++ b/infrastructure/azure/installation.tfvars.example @@ -12,6 +12,12 @@ setup_database_secret = { key_vault_id = "/subscriptions/YOUR_SUBSCRIPTION/resourceGroups/YOUR_SECRETS_GROUP/providers/Microsoft.KeyVault/vaults/YOUR_VAULT" secret_id = "https://YOUR-VAULT.vault.azure.net/secrets/hub-migration-database" } +# Enable on a new installation, or only after an existing installation's SQLite +# history and mappings have been imported and verified. Leave unset otherwise. +# learning_database_secret = { +# key_vault_id = "/subscriptions/YOUR_SUBSCRIPTION/resourceGroups/YOUR_SECRETS_GROUP/providers/Microsoft.KeyVault/vaults/YOUR_VAULT" +# secret_id = "https://YOUR-VAULT.vault.azure.net/secrets/postgres-learning-url" +# } # Supply postgres_admin_password through a secret manager as TF_VAR_postgres_admin_password. # Application secrets stay in Key Vault. Optional references, never values: diff --git a/infrastructure/azure/post/configure/index.ts b/infrastructure/azure/post/configure/index.ts index 98b8e901..4e646d8b 100644 --- a/infrastructure/azure/post/configure/index.ts +++ b/infrastructure/azure/post/configure/index.ts @@ -374,9 +374,10 @@ export async function configurePostSetup( action === "sign-in" ? Object.keys(shared) : ["GITHUB_CLIENT_SECRET", "GITHUB_APP_PRIVATE_KEY_BASE64", "GITHUB_WEBHOOK_SECRET"] - if (new Set([...Object.keys(references), ...requiredReferences]).size > 63) + const maximumReferences = next.learning_database_secret ? 62 : 63 + if (new Set([...Object.keys(references), ...requiredReferences]).size > maximumReferences) throw new Error( - "This configuration would exceed the runtime limit of 63 additional secret references. Review unused references separately before creating secrets.", + `This configuration would exceed the runtime limit of ${maximumReferences} additional secret references. Review unused references separately before creating secrets.`, ) if (action === "sign-in") { if ( @@ -735,8 +736,7 @@ export async function configurePostSetup( next.github_app_installation_id !== deployment.environment.GITHUB_APP_INSTALLATION_ID || credentials.some( ({ key }) => - references[key]?.secret_id !== - (liveSecretReferences as Record)[key], + references[key]?.secret_id !== (liveSecretReferences as Record)[key], ) const storedRevision = await verifiedGitHubRevision() const savedRevision = @@ -793,8 +793,7 @@ export async function configurePostSetup( ]) delete next.runtime_environment_variables[name] replacements.sort( - (left, right) => - Number(right.key === progress.pending) - Number(left.key === progress.pending), + (left, right) => Number(right.key === progress.pending) - Number(left.key === progress.pending), ) for (const credential of replacements) references[credential.key] = await put(credential.key, credential.name, credential.value) diff --git a/infrastructure/azure/post/index.test.ts b/infrastructure/azure/post/index.test.ts index 1c0e7004..a08f7e68 100644 --- a/infrastructure/azure/post/index.test.ts +++ b/infrastructure/azure/post/index.test.ts @@ -118,6 +118,9 @@ async function scenario() { }), AZURE_KEY_VAULT_SECRET_REFERENCES: JSON.stringify({ DATABASE_URL: reference("database-runtime").secret_id, + ...(value.learning_database_secret && { + REPLICA_LEARNING_DATABASE_URL: value.learning_database_secret.secret_id, + }), ...Object.fromEntries( Object.entries(value.runtime_secret_references ?? {}).map(([key, value]) => [ key, @@ -602,6 +605,12 @@ it("retains leases and resumes when the completion marker cannot be saved", asyn it("uses the deployed digest despite stale deploy_hub=false and preserves settings across verification and configuration reruns", async () => { const test = await scenario() + test.inputs.learning_database_secret = test.reference("learning-runtime") + await writeFile(test.inputsPath, JSON.stringify(test.inputs), { mode: 0o600 }) + test.state.environment.AZURE_KEY_VAULT_SECRET_REFERENCES = JSON.stringify({ + ...JSON.parse(test.state.environment.AZURE_KEY_VAULT_SECRET_REFERENCES!), + REPLICA_LEARNING_DATABASE_URL: test.inputs.learning_database_secret.secret_id, + }) expect(test.state.environment.HUB_TRUSTED_PROXY_HOPS).toBe("1") test.state.verifyFailures = 1 test.state.recovery = "verify" @@ -1021,9 +1030,9 @@ it("blocks an origin change with Entra configured before creating shared secrets expect(test.uploads).toEqual([]) expect(test.plans).toEqual([]) expect(test.applies).toBe(0) - expect((await readdir(test.directory)).filter((name) => name.startsWith("post-bootstrap-"))).toEqual( - [], - ) + expect( + (await readdir(test.directory)).filter((name) => name.startsWith("post-bootstrap-")), + ).toEqual([]) }) it.each(["plain", "secret-backed"] as const)( @@ -1063,7 +1072,9 @@ it.each(["plain", "secret-backed"] as const)( .privateKey.export({ type: "pkcs8", format: "pem" }) .toString() const values = ["synthetic-client-secret", pem, "synthetic-webhook-secret-for-tests-only"] - const paths = values.map((_, index) => join(test.directory, `custom-origin-credential-${index}`)) + const paths = values.map((_, index) => + join(test.directory, `custom-origin-credential-${index}`), + ) await Promise.all(paths.map((path, index) => writeFile(path, values[index]!, { mode: 0o600 }))) vi.mocked(test.ui.text) .mockReset() @@ -1474,9 +1485,7 @@ it.each([ args.slice(0, 3).join(" ") === "keyvault secret set" && args[args.indexOf("--name") + 1] === "hub-bootstrap-secret" ) { - expect(test.uploads.map(({ name }) => name)).toEqual([ - "hub-authentication-encryption-key", - ]) + expect(test.uploads.map(({ name }) => name)).toEqual(["hub-authentication-encryption-key"]) throw new command.CommandExecutionError("Synthetic secret write failure", false, 1) } return execute(executable, args, options) @@ -1792,7 +1801,9 @@ it.each([ principalId, roleDefinitionId: lookup === "filtered duplicate" ? roleId.toUpperCase() : roleId, roleDefinitionName: - lookup === "conflicting retry" ? "Key Vault Administrator" : "Key Vault Secrets User", + lookup === "conflicting retry" + ? "Key Vault Administrator" + : "Key Vault Secrets User", }, ] return JSON.stringify( @@ -1873,9 +1884,7 @@ it.each([ test.run.mock.calls.some( ([executable, args]) => (executable === "terraform" && ["import", "state"].includes(args[1]!)) || - (executable === "az" && - args[0] === "role" && - ["create", "delete"].includes(args[2]!)), + (executable === "az" && args[0] === "role" && ["create", "delete"].includes(args[2]!)), ), ).toBe(false) }, diff --git a/infrastructure/azure/post/index.ts b/infrastructure/azure/post/index.ts index e769376d..55cc588b 100644 --- a/infrastructure/azure/post/index.ts +++ b/infrastructure/azure/post/index.ts @@ -155,6 +155,9 @@ export async function postSetupAzure( throw new Error("The deployed startup secret references are missing or unsupported.") const savedReferences = { DATABASE_URL: runtimeDatabase.secret_id, + ...(saved.learning_database_secret + ? { REPLICA_LEARNING_DATABASE_URL: saved.learning_database_secret.secret_id } + : {}), ...Object.fromEntries( Object.entries(saved.runtime_secret_references ?? {}).map(([key, reference]) => [ key, diff --git a/infrastructure/azure/post/types.ts b/infrastructure/azure/post/types.ts index dfa8f54b..54bd652e 100644 --- a/infrastructure/azure/post/types.ts +++ b/infrastructure/azure/post/types.ts @@ -23,6 +23,7 @@ export interface PostInputs extends Record { deploy_hub: boolean runtime_environment_variables?: Record runtime_secret_references?: Record + learning_database_secret?: { key_vault_id: string; secret_id: string } hub_application_origin?: string github_app_id?: string github_client_id?: string diff --git a/infrastructure/azure/provision/main.tf b/infrastructure/azure/provision/main.tf index 15d57ead..b197b01d 100644 --- a/infrastructure/azure/provision/main.tf +++ b/infrastructure/azure/provision/main.tf @@ -39,16 +39,24 @@ variable "vault_id" { error_message = "Supply the Key Vault resource ID that owns the provisioning secrets." } } +variable "mode" { + type = string + default = "provision" + validation { + condition = contains(["provision", "provision-learning"], var.mode) + error_message = "Choose provision for a fresh database or provision-learning for an existing installation." + } +} variable "secret_urls" { type = map(string) validation { condition = ( - toset(keys(var.secret_urls)) == toset(["DATABASE_URL", "HUB_MIGRATION_PASSWORD", "HUB_RUNTIME_PASSWORD"]) && + toset(keys(var.secret_urls)) == toset(var.mode == "provision" ? ["DATABASE_URL", "HUB_MIGRATION_PASSWORD", "HUB_RUNTIME_PASSWORD", "HUB_LEARNING_PASSWORD"] : ["DATABASE_URL", "HUB_LEARNING_PASSWORD"]) && alltrue([for secret in values(var.secret_urls) : can(regex("^https://[a-zA-Z0-9-]{1,24}\\.vault\\.azure\\.net/secrets/[a-zA-Z0-9-]{1,127}/[a-fA-F0-9]{32}$", secret)) ]) ) - error_message = "Provide exactly three versioned Key Vault references for the administrator URL and two role passwords, never raw values." + error_message = "Provide the exact versioned Key Vault references required by the provisioning mode, never raw values." } validation { condition = ( @@ -111,7 +119,7 @@ resource "azurerm_container_app_job" "provision" { image = var.image cpu = 0.5 memory = "1Gi" - command = ["node", "dist/server/scripts/azure-entrypoint/index.js", "provision"] + command = ["node", "dist/server/scripts/azure-entrypoint/index.js", var.mode] env { name = "NODE_ENV" value = "production" diff --git a/infrastructure/azure/provision/tests/provision.tftest.hcl b/infrastructure/azure/provision/tests/provision.tftest.hcl index 04ccd20f..565b56f9 100644 --- a/infrastructure/azure/provision/tests/provision.tftest.hcl +++ b/infrastructure/azure/provision/tests/provision.tftest.hcl @@ -21,6 +21,7 @@ variables { DATABASE_URL = "https://testvault.vault.azure.net/secrets/postgres-admin-url/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" HUB_MIGRATION_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-migration-password/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" HUB_RUNTIME_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-runtime-password/cccccccccccccccccccccccccccccccc" + HUB_LEARNING_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-learning-password/dddddddddddddddddddddddddddddddd" } } @@ -39,7 +40,7 @@ run "fresh_database_job_is_explicit_and_has_separate_access" { azurerm_container_app_job.provision.manual_trigger_config[0].replica_completion_count == 1 && azurerm_container_app_job.provision.template[0].container[0].command == tolist(["node", "dist/server/scripts/azure-entrypoint/index.js", "provision"]) && length(azurerm_container_app_job.provision.secret) == 0 && - length(azurerm_role_assignment.secrets) == 3 && + length(azurerm_role_assignment.secrets) == 4 && alltrue([for env in azurerm_container_app_job.provision.template[0].container[0].env : env.secret_name == null || env.secret_name == "" ]) @@ -68,6 +69,7 @@ run "fresh_database_job_is_explicit_and_has_separate_access" { "${var.vault_id}/secrets/postgres-admin-url", "${var.vault_id}/secrets/postgres-migration-password", "${var.vault_id}/secrets/postgres-runtime-password", + "${var.vault_id}/secrets/postgres-learning-password", ]) && alltrue([for grant in azurerm_role_assignment.secrets : grant.principal_id == azurerm_user_assigned_identity.provision.principal_id && @@ -80,7 +82,7 @@ run "fresh_database_job_is_explicit_and_has_separate_access" { one([for env in azurerm_container_app_job.provision.template[0].container[0].env : env.value if env.name == "AZURE_CLIENT_ID"]) == azurerm_user_assigned_identity.provision.client_id && tomap(jsondecode(one([for env in azurerm_container_app_job.provision.template[0].container[0].env : env.value if env.name == "AZURE_KEY_VAULT_SECRET_REFERENCES"]))) == var.secret_urls ) - error_message = "Only the isolated provisioning identity may receive three secret-scoped grants; its container must contain only production mode, its explicit client ID, and the exact URI-only administrator/password map." + error_message = "Only the isolated provisioning identity may receive the required secret-scoped grants and exact URI-only administrator/password map." } } @@ -98,6 +100,30 @@ run "public_digest_needs_no_registry_or_pull_grant" { } } +run "existing_installation_receives_only_learning_provisioning_secrets" { + command = plan + + variables { + mode = "provision-learning" + secret_urls = { + DATABASE_URL = "https://testvault.vault.azure.net/secrets/postgres-admin-url/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + HUB_LEARNING_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-learning-password/dddddddddddddddddddddddddddddddd" + } + } + + assert { + condition = ( + azurerm_container_app_job.provision.template[0].container[0].command == tolist(["node", "dist/server/scripts/azure-entrypoint/index.js", "provision-learning"]) && + toset([for grant in azurerm_role_assignment.secrets : grant.scope]) == toset([ + "${var.vault_id}/secrets/postgres-admin-url", + "${var.vault_id}/secrets/postgres-learning-password", + ]) && + tomap(jsondecode(one([for env in azurerm_container_app_job.provision.template[0].container[0].env : env.value if env.name == "AZURE_KEY_VAULT_SECRET_REFERENCES"]))) == var.secret_urls + ) + error_message = "Existing installations must grant the job only the admin URL and learning password." + } +} + run "matching_vault_names_are_case_insensitive" { command = plan @@ -107,12 +133,13 @@ run "matching_vault_names_are_case_insensitive" { DATABASE_URL = "https://TestVault.vault.azure.net/secrets/postgres-admin-url/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" HUB_MIGRATION_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-migration-password/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" HUB_RUNTIME_PASSWORD = "https://TESTVAULT.vault.azure.net/secrets/postgres-runtime-password/cccccccccccccccccccccccccccccccc" + HUB_LEARNING_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-learning-password/dddddddddddddddddddddddddddddddd" } } assert { condition = ( - length(azurerm_role_assignment.secrets) == 3 && + length(azurerm_role_assignment.secrets) == 4 && alltrue([for grant in azurerm_role_assignment.secrets : startswith(grant.scope, "${var.vault_id}/secrets/")]) && tomap(jsondecode(one([for env in azurerm_container_app_job.provision.template[0].container[0].env : env.value if env.name == "AZURE_KEY_VAULT_SECRET_REFERENCES"]))) == var.secret_urls ) @@ -130,13 +157,14 @@ run "mutable_image_is_rejected" { expect_failures = [var.image] } -run "all_three_provisioning_secrets_are_required" { +run "all_provisioning_secrets_are_required" { command = plan variables { secret_urls = { HUB_MIGRATION_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-migration-password/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" HUB_RUNTIME_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-runtime-password/cccccccccccccccccccccccccccccccc" + HUB_LEARNING_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-learning-password/dddddddddddddddddddddddddddddddd" } } @@ -151,6 +179,7 @@ run "additional_secret_access_is_rejected" { DATABASE_URL = "https://testvault.vault.azure.net/secrets/postgres-admin-url/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" HUB_MIGRATION_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-migration-password/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" HUB_RUNTIME_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-runtime-password/cccccccccccccccccccccccccccccccc" + HUB_LEARNING_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-learning-password/dddddddddddddddddddddddddddddddd" EXTRA_SECRET = "https://testvault.vault.azure.net/secrets/extra/dddddddddddddddddddddddddddddddd" } } @@ -166,6 +195,7 @@ run "unversioned_secret_is_rejected" { DATABASE_URL = "https://testvault.vault.azure.net/secrets/postgres-admin-url" HUB_MIGRATION_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-migration-password/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" HUB_RUNTIME_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-runtime-password/cccccccccccccccccccccccccccccccc" + HUB_LEARNING_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-learning-password/dddddddddddddddddddddddddddddddd" } } @@ -200,6 +230,7 @@ run "secret_hosts_must_match_the_granted_vault" { DATABASE_URL = "https://another-vault.vault.azure.net/secrets/postgres-admin-url/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" HUB_MIGRATION_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-migration-password/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" HUB_RUNTIME_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-runtime-password/cccccccccccccccccccccccccccccccc" + HUB_LEARNING_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-learning-password/dddddddddddddddddddddddddddddddd" } } @@ -215,6 +246,7 @@ run "maximum_length_secret_urls_are_accepted" { DATABASE_URL = "https://vvvvvvvvvvvvvvvvvvvvvvvv.vault.azure.net/secrets/${join("", [for i in range(127) : "a"])}/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" HUB_MIGRATION_PASSWORD = "https://vvvvvvvvvvvvvvvvvvvvvvvv.vault.azure.net/secrets/${join("", [for i in range(127) : "b"])}/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" HUB_RUNTIME_PASSWORD = "https://vvvvvvvvvvvvvvvvvvvvvvvv.vault.azure.net/secrets/${join("", [for i in range(127) : "c"])}/cccccccccccccccccccccccccccccccc" + HUB_LEARNING_PASSWORD = "https://vvvvvvvvvvvvvvvvvvvvvvvv.vault.azure.net/secrets/${join("", [for i in range(127) : "d"])}/dddddddddddddddddddddddddddddddd" } } @@ -236,6 +268,7 @@ run "secret_urls_reject_oversized_vault" { DATABASE_URL = "https://vvvvvvvvvvvvvvvvvvvvvvvvv.vault.azure.net/secrets/admin/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" HUB_MIGRATION_PASSWORD = "https://vvvvvvvvvvvvvvvvvvvvvvvvv.vault.azure.net/secrets/migration/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" HUB_RUNTIME_PASSWORD = "https://vvvvvvvvvvvvvvvvvvvvvvvvv.vault.azure.net/secrets/runtime/cccccccccccccccccccccccccccccccc" + HUB_LEARNING_PASSWORD = "https://vvvvvvvvvvvvvvvvvvvvvvvvv.vault.azure.net/secrets/learning/dddddddddddddddddddddddddddddddd" } } @@ -250,6 +283,7 @@ run "secret_urls_reject_oversized_secret" { DATABASE_URL = "https://testvault.vault.azure.net/secrets/${join("", [for i in range(128) : "a"])}/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" HUB_MIGRATION_PASSWORD = "https://testvault.vault.azure.net/secrets/migration/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" HUB_RUNTIME_PASSWORD = "https://testvault.vault.azure.net/secrets/runtime/cccccccccccccccccccccccccccccccc" + HUB_LEARNING_PASSWORD = "https://testvault.vault.azure.net/secrets/learning/dddddddddddddddddddddddddddddddd" } } diff --git a/infrastructure/azure/roles.tf b/infrastructure/azure/roles.tf index 8d610f1f..26853a4f 100644 --- a/infrastructure/azure/roles.tf +++ b/infrastructure/azure/roles.tf @@ -1,6 +1,6 @@ locals { runtime_secret_scopes = toset([ - for secret in concat([var.runtime_database_secret], values(var.runtime_secret_references)) : + for secret in concat([var.runtime_database_secret], var.learning_database_secret == null ? [] : [var.learning_database_secret], values(var.runtime_secret_references)) : "${secret.key_vault_id}/secrets/${split("/", secret.secret_id)[4]}" ]) } diff --git a/infrastructure/azure/setup.tf b/infrastructure/azure/setup.tf index 6dfaf0ef..c389cbfd 100644 --- a/infrastructure/azure/setup.tf +++ b/infrastructure/azure/setup.tf @@ -35,15 +35,18 @@ resource "azurerm_container_app_job" "setup" { command = ["node", "dist/server/scripts/azure-entrypoint/index.js", "setup"] dynamic "env" { - for_each = { + for_each = merge({ NODE_ENV = "production" RUNTIME_MODE = "setup" DATABASE_RUNTIME_ROLE = "replica_runtime" AZURE_CLIENT_ID = azurerm_user_assigned_identity.setup.client_id AZURE_KEY_VAULT_SECRET_REFERENCES = jsonencode({ - DATABASE_URL = var.setup_database_secret.secret_id + DATABASE_URL = var.setup_database_secret.secret_id + REPLICA_LEARNING_MIGRATION_DATABASE_URL = var.setup_database_secret.secret_id }) - } + }, var.learning_database_secret == null ? {} : { + REPLICA_LEARNING_RUNTIME_ROLE = "replica_learning_runtime" + }) content { name = env.key value = env.value diff --git a/infrastructure/azure/tests/deployment.tftest.hcl b/infrastructure/azure/tests/deployment.tftest.hcl index 05abee56..54993b33 100644 --- a/infrastructure/azure/tests/deployment.tftest.hcl +++ b/infrastructure/azure/tests/deployment.tftest.hcl @@ -347,7 +347,8 @@ run "setup_and_runtime_have_separate_secret_access" { SERVICE_API_KEY = var.runtime_secret_references.SERVICE_API_KEY.secret_id }) && tomap(jsondecode(one([for env in azurerm_container_app_job.setup.template[0].container[0].env : env.value if env.name == "AZURE_KEY_VAULT_SECRET_REFERENCES"]))) == tomap({ - DATABASE_URL = var.setup_database_secret.secret_id + DATABASE_URL = var.setup_database_secret.secret_id + REPLICA_LEARNING_MIGRATION_DATABASE_URL = var.setup_database_secret.secret_id }) ) error_message = "Each container must receive only its explicit identity and URI-only startup metadata, without platform secrets, secret-name bindings, or resolved secret values." @@ -364,7 +365,7 @@ run "setup_and_runtime_have_separate_secret_access" { } : one([for env in azurerm_container_app_job.setup.template[0].container[0].env : env.value if env.name == name]) == value ]) ) - error_message = "Setup must receive only production/setup mode, its identity and migration URI metadata, and the fixed runtime grant target." + error_message = "SQLite setup must not grant an unprovisioned learning runtime role." } assert { condition = ( @@ -386,6 +387,28 @@ run "setup_and_runtime_have_separate_secret_access" { } } +run "learning_postgresql_uses_runtime_secret_and_setup_migration_identity" { + command = plan + + variables { + deploy_hub = true + learning_database_secret = { + key_vault_id = "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/secrets/providers/Microsoft.KeyVault/vaults/database" + secret_id = "https://database.vault.azure.net/secrets/learning-runtime/dddddddddddddddddddddddddddddddd" + } + } + + assert { + condition = ( + jsondecode(one([for env in azurerm_container_app.hub[0].template[0].container[0].env : env.value if env.name == "AZURE_KEY_VAULT_SECRET_REFERENCES"])).REPLICA_LEARNING_DATABASE_URL == var.learning_database_secret.secret_id && + contains([for grant in azurerm_role_assignment.runtime_secrets : grant.scope], "${var.learning_database_secret.key_vault_id}/secrets/learning-runtime") && + jsondecode(one([for env in azurerm_container_app_job.setup.template[0].container[0].env : env.value if env.name == "AZURE_KEY_VAULT_SECRET_REFERENCES"])).REPLICA_LEARNING_MIGRATION_DATABASE_URL == var.setup_database_secret.secret_id && + one([for env in azurerm_container_app_job.setup.template[0].container[0].env : env.value if env.name == "REPLICA_LEARNING_RUNTIME_ROLE"]) == "replica_learning_runtime" + ) + error_message = "Learning must use its own runtime secret and setup's migration identity." + } +} + run "runtime_environment_rejects_reserved_names" { command = plan variables { diff --git a/infrastructure/azure/variables.tf b/infrastructure/azure/variables.tf index 873a625a..c927ddc7 100644 --- a/infrastructure/azure/variables.tf +++ b/infrastructure/azure/variables.tf @@ -144,9 +144,31 @@ variable "setup_database_secret" { } } +variable "learning_database_secret" { + type = object({ + key_vault_id = string + secret_id = string + }) + default = null + description = "Optional Key Vault reference containing the replica_learning_runtime database URL. Set only after existing SQLite history is reconciled." + + validation { + condition = var.learning_database_secret == null ? true : ( + can(regex("^/subscriptions/[^/]+/resourceGroups/[^/]+/providers/Microsoft.KeyVault/vaults/[^/]+$", var.learning_database_secret.key_vault_id)) && + can(regex("^https://[a-zA-Z0-9-]{1,24}\\.vault\\.azure\\.net/secrets/[a-zA-Z0-9-]{1,127}(/[a-fA-F0-9]{32})?$", var.learning_database_secret.secret_id)) && + lower(try(split("/", var.learning_database_secret.secret_id)[2], "")) == "${lower(try(split("/", var.learning_database_secret.key_vault_id)[8], ""))}.vault.azure.net" && + alltrue([for secret in [var.runtime_database_secret, var.setup_database_secret] : + lower("${secret.key_vault_id}/secrets/${try(split("/", secret.secret_id)[4], "")}") != lower("${var.learning_database_secret.key_vault_id}/secrets/${try(split("/", var.learning_database_secret.secret_id)[4], "")}") + ]) + ) + error_message = "Supply a separate learning runtime secret URL and its Key Vault resource ID." + } +} + locals { runtime_reserved_environment_names = [ "DATABASE_URL", "DATABASE_RUNTIME_ROLE", "NODE_ENV", "RUNTIME_MODE", "HOST", "PORT", + "REPLICA_LEARNING_DATABASE_URL", "REPLICA_LEARNING_MIGRATION_DATABASE_URL", "REPLICA_LEARNING_RUNTIME_ROLE", "CLIENT_DIRECTORY", "SHUTDOWN_TIMEOUT_MS", "ARTIFACT_STORAGE_PROVIDER", "ARTIFACT_STORAGE_DIRECTORY", "AZURE_STORAGE_ACCOUNT", "AZURE_STORAGE_CONTAINER", "AZURE_CLIENT_ID", "AZURE_KEY_VAULT_SECRET_REFERENCES", @@ -266,12 +288,12 @@ variable "runtime_secret_references" { description = "Existing RBAC Key Vault secret references keyed by uppercase runtime environment name. Values remain outside Terraform." validation { - condition = length(keys(var.runtime_secret_references)) <= 63 && alltrue([ + condition = length(keys(var.runtime_secret_references)) <= (var.learning_database_secret == null ? 63 : 62) && alltrue([ for name in keys(var.runtime_secret_references) : can(regex("^[A-Z][A-Z0-9_]{0,40}$", name)) && !contains(concat(local.runtime_reserved_environment_names, ["GITHUB_APP_ID", "GITHUB_CLIENT_ID", "GITHUB_APP_INSTALLATION_ID", "GITHUB_PROVIDER_REVISION"]), name) ]) - error_message = "Supply at most 63 additional secret references, using uppercase environment names of at most 41 characters; deployment-owned settings cannot be overridden." + error_message = "Supply at most 63 additional secret references (62 with a learning database), using uppercase environment names of at most 41 characters; deployment-owned settings cannot be overridden." } validation { From a40cc55b0b9a381b1712f70e3061d8c5659d528b Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 10:36:56 -0800 Subject: [PATCH 04/18] fix(learning): fence PostgreSQL writes against migration changes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 836fcecf-e7a9-4975-acd2-bf761098f711 --- packages/learning/src/providers/postgres.mjs | 35 +++++- .../learning/test-database/postgres.test.mjs | 105 ++++++++++++++++++ 2 files changed, 136 insertions(+), 4 deletions(-) diff --git a/packages/learning/src/providers/postgres.mjs b/packages/learning/src/providers/postgres.mjs index 3a91de93..c7c01938 100644 --- a/packages/learning/src/providers/postgres.mjs +++ b/packages/learning/src/providers/postgres.mjs @@ -1,4 +1,4 @@ -import { canonicalJson } from "../canonical-json.mjs" +import { canonicalJson, digestOf } from "../canonical-json.mjs" import { LearningError, ProviderConflictError } from "../errors.mjs" import { PROVIDER_CONTRACT, @@ -128,11 +128,29 @@ export function createPostgresMemoryProvider({ connectionString } = {}) { return { appended: inserted.rowCount, existing: records.length - inserted.rowCount } } - async function write(batch, { audit = [], expectedCollection } = {}) { + async function assertMigrations(client, expectedMigrations) { + if (!expectedMigrations) return + const { rows } = await client.query( + "select metadata from replica_learning.scope_migrations where new_scope_key = $1 order by seq", + [canonicalJson(expectedMigrations.scope)], + ) + let migrations + try { + migrations = rows.map((row) => JSON.parse(row.metadata)) + } catch { + throw new LearningError("storage_corrupt", "A PostgreSQL migration mapping is invalid.") + } + if (digestOf(migrations) !== expectedMigrations.digest) + throw new ProviderConflictError("Repository migration changed during the write.") + } + + async function write(batch, { audit = [], expectedCollection, expectedMigrations } = {}) { const writes = batchWrites(batch, audit) const scopes = [...writes.values()].flat().map((record) => canonicalJson(record.scope)) if (expectedCollection) scopes.push(canonicalJson(expectedCollection.scope)) + if (expectedMigrations) scopes.push(canonicalJson(expectedMigrations.scope)) return transaction(scopes, async (client) => { + await assertMigrations(client, expectedMigrations) if (expectedCollection) { const { rows } = await client.query( `select id, digest from replica_learning.records @@ -182,6 +200,7 @@ export function createPostgresMemoryProvider({ connectionString } = {}) { return { atomicCollectionImport: true, atomicMigrationRedactions: true, + atomicMigrationFence: true, manifest() { return { @@ -230,15 +249,23 @@ export function createPostgresMemoryProvider({ connectionString } = {}) { }) }, - async appendMemoryVersion(record, { expectedPreviousDigest = null, audit = [] } = {}) { + async appendMemoryVersion( + record, + { expectedPreviousDigest = null, audit = [], expectedMigrations } = {}, + ) { assertStorable([record]) assertStorable(audit) if (!Number.isSafeInteger(record.version) || record.version < 1) throw new LearningError("invalid_input", "A memory version needs a positive version.") const scope = canonicalJson(record.scope) await transaction( - [scope, ...audit.map((entry) => canonicalJson(entry.scope))], + [ + scope, + ...audit.map((entry) => canonicalJson(entry.scope)), + ...(expectedMigrations ? [canonicalJson(expectedMigrations.scope)] : []), + ], async (client) => { + await assertMigrations(client, expectedMigrations) const { rows } = await client.query( "select version, digest, scope_key from replica_learning.memory_versions where id = $1 order by version desc limit 1", [record.id], diff --git a/packages/learning/test-database/postgres.test.mjs b/packages/learning/test-database/postgres.test.mjs index 7e2fa0d9..8906d302 100644 --- a/packages/learning/test-database/postgres.test.mjs +++ b/packages/learning/test-database/postgres.test.mjs @@ -22,6 +22,7 @@ import { weekOneLog, weekTwoLog, } from "../conformance/index.mjs" +import { canonicalJson, digestOf } from "../src/canonical-json.mjs" import { main } from "../src/cli.mjs" import { openProvider } from "../src/config.mjs" import { STREAMS } from "../src/provider-contract.mjs" @@ -1112,6 +1113,110 @@ it("allows only one concurrent version based on the same previous digest", async assert.equal((await first.readMemoryVersions({ scope })).length, 2) }) +it("refuses an import and proposal when migration metadata changes during their writes", async () => { + const url = await database() + const writer = provider(url) + const scope = { host: "github.com", repository: "repositories/123" } + const oldScope = { host: "github.com", repository: "acme/old" } + const mapping = { oldScope, newScope: scope, digestMappings: [] } + const expectedMigrations = { scope, digest: digestOf(await writer.scopeMigrations(scope)) } + function record(id) { + return { id, digest: `sha256:${id}`, scope } + } + const batch = { collections: [record("collection")], events: [record("event")] } + const batchAudit = record("import-audit") + const memory = { ...record("memory"), version: 1 } + const memoryAudit = record("proposal-audit") + const holder = new pg.Client({ connectionString: url }) + await holder.connect() + let writes = [] + let results + try { + await holder.query("begin") + await holder.query("select pg_advisory_xact_lock(hashtextextended($1, 0))", [ + `replica_learning.scope:${canonicalJson(scope)}`, + ]) + await holder.query( + "insert into replica_learning.scope_migrations (old_scope_key, new_scope_key, metadata) values ($1, $2, $3)", + [canonicalJson(oldScope), canonicalJson(scope), JSON.stringify(mapping)], + ) + writes = [ + writer.appendBatch(batch, { audit: [batchAudit], expectedMigrations }), + writer.appendMemoryVersion(memory, { audit: [memoryAudit], expectedMigrations }), + ] + for (const write of writes) write.catch(() => {}) + const deadline = Date.now() + 5000 + while (true) { + await holder.query("select pg_stat_clear_snapshot()") + const { rows } = await holder.query( + "select count(*)::int as count from pg_stat_activity where datname = current_database() and wait_event = 'advisory'", + ) + if (rows[0].count >= 2) break + assert.ok(Date.now() < deadline, "Both writes must wait for the migration's scope lock.") + await new Promise((resolve) => setTimeout(resolve, 20)) + } + await holder.query("commit") + results = await Promise.allSettled(writes) + } finally { + await holder.query("rollback") + await Promise.allSettled(writes) + await holder.end() + } + assert.deepEqual( + results.map((result) => result.status === "rejected" && result.reason.code), + ["conflict", "conflict"], + ) + for (const stream of ["collections", "events", "audit"]) + assert.deepEqual(await writer.readRecords(stream, { scope }), []) + assert.deepEqual(await writer.readMemoryVersions({ scope }), []) + + const currentMigrations = { scope, digest: digestOf(await writer.scopeMigrations(scope)) } + await writer.appendBatch(batch, { audit: [batchAudit], expectedMigrations: currentMigrations }) + await writer.appendMemoryVersion(memory, { + audit: [memoryAudit], + expectedMigrations: currentMigrations, + }) + assert.deepEqual(await writer.readRecords("collections", { scope }), batch.collections) + assert.deepEqual(await writer.readRecords("events", { scope }), batch.events) + assert.deepEqual(await writer.readRecords("audit", { scope }), [batchAudit, memoryAudit]) + assert.deepEqual(await writer.readMemoryVersions({ scope }), [memory]) +}) + +it("refuses an import when any collection history changes", async () => { + const url = await database() + const writer = provider(url) + const scope = { host: "github.com", repository: "repositories/123" } + function record(id) { + return { id, digest: `sha256:${id}`, scope } + } + const first = { ...record("first"), snapshotId: "same-snapshot" } + const second = { ...record("second"), snapshotId: "different-snapshot" } + await writer.registerLegacyScope({ host: "github.com", repository: "acme/old" }, scope) + const expectedMigrations = { scope, digest: digestOf(await writer.scopeMigrations(scope)) } + await writer.appendRecords("collections", [first]) + const expectedCollection = { scope, records: [{ id: first.id, digest: first.digest }] } + await writer.appendRecords("collections", [second]) + const batch = { collections: [record("new")], events: [record("event")] } + const audit = record("import-audit") + await assert.rejects( + writer.appendBatch(batch, { audit: [audit], expectedCollection, expectedMigrations }), + { code: "conflict" }, + ) + assert.deepEqual(await writer.readRecords("collections", { scope }), [first, second]) + assert.deepEqual(await writer.readRecords("events", { scope }), []) + assert.deepEqual(await writer.readRecords("audit", { scope }), []) + + expectedCollection.records.push({ id: second.id, digest: second.digest }) + await writer.appendBatch(batch, { audit: [audit], expectedCollection, expectedMigrations }) + assert.deepEqual(await writer.readRecords("collections", { scope }), [ + first, + second, + ...batch.collections, + ]) + assert.deepEqual(await writer.readRecords("events", { scope }), batch.events) + assert.deepEqual(await writer.readRecords("audit", { scope }), [audit]) +}) + it("treats a concurrent duplicate as existing under a repeatable-read default", async () => { const url = await database() const name = new URL(url).pathname.slice(1) From 20690865ae4c25455f9e090120439546f477f4c9 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 10:36:56 -0800 Subject: [PATCH 05/18] test(hub): include migration status in database overview Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 836fcecf-e7a9-4975-acd2-bf761098f711 --- .../domains/learning/get-learning-overview/index.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/hub/server/domains/learning/get-learning-overview/index.test.ts b/hub/server/domains/learning/get-learning-overview/index.test.ts index a8492292..297baa0e 100644 --- a/hub/server/domains/learning/get-learning-overview/index.test.ts +++ b/hub/server/domains/learning/get-learning-overview/index.test.ts @@ -23,6 +23,7 @@ describe("getLearningOverview()", () => { vi.mocked(access).mockRejectedValue(Object.assign(new Error("missing"), { code: "ENOENT" })) vi.mocked(runLearningCommand) .mockResolvedValueOnce([]) + .mockResolvedValueOnce({}) .mockResolvedValueOnce({ text: "Useful guidance", memories: [] }) const learningDatabaseUrl = "postgresql://learning.example/replica" @@ -39,7 +40,7 @@ describe("getLearningOverview()", () => { }) expect(result.recall.text).toBe("Useful guidance") - expect(runLearningCommand).toHaveBeenCalledTimes(2) + expect(runLearningCommand).toHaveBeenCalledTimes(3) for (const [arguments_, options] of vi.mocked(runLearningCommand).mock.calls) { expect(arguments_).not.toContain(learningDatabaseUrl) expect(options).toMatchObject({ learningDatabaseUrl }) From d92ca59cd8ed520aad2b547deffa1dd4e9175c3a Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 10:50:30 -0800 Subject: [PATCH 06/18] fix(learning): refuse incomplete SQLite imports Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 836fcecf-e7a9-4975-acd2-bf761098f711 --- packages/learning/src/providers/sqlite.mjs | 3 + .../learning/test-database/postgres-v1.sql | 33 +++++ .../learning/test-database/postgres.test.mjs | 121 ++++++++++++++++++ 3 files changed, 157 insertions(+) create mode 100644 packages/learning/test-database/postgres-v1.sql diff --git a/packages/learning/src/providers/sqlite.mjs b/packages/learning/src/providers/sqlite.mjs index d00bddb8..7d6f6ecd 100644 --- a/packages/learning/src/providers/sqlite.mjs +++ b/packages/learning/src/providers/sqlite.mjs @@ -232,6 +232,9 @@ export function createSqliteMemoryProvider({ directory, file = "learning.sqlite" function storedScopes() { const database = connect({ create: false }) if (!database) return [] + for (const { stream } of database.prepare("select distinct stream from records").all()) + if (!Object.hasOwn(STREAMS, stream)) + throw new LearningError("storage_corrupt", "SQLite store has an unknown record stream.") return database .prepare("select scope_key from records union select scope_key from memory_versions") .all() diff --git a/packages/learning/test-database/postgres-v1.sql b/packages/learning/test-database/postgres-v1.sql new file mode 100644 index 00000000..68a7be97 --- /dev/null +++ b/packages/learning/test-database/postgres-v1.sql @@ -0,0 +1,33 @@ + + create table replica_learning.records ( + seq bigint generated always as identity primary key, + stream text collate "C" not null, + id text collate "C" not null, + scope_key text collate "C" not null, + occurred_at text collate "C", + episode_id text collate "C", + operation text collate "C", + digest text collate "C" not null, + body text not null, + unique (stream, id) + ); + create index records_by_scope on replica_learning.records (stream, scope_key, seq); + create index records_by_scope_id on replica_learning.records (stream, scope_key, id); + create index records_by_episode on replica_learning.records (stream, scope_key, episode_id); + create index records_by_time on replica_learning.records (stream, scope_key, occurred_at); + create index records_by_operation on replica_learning.records (stream, scope_key, operation); + create table replica_learning.memory_versions ( + seq bigint generated always as identity primary key, + id text collate "C" not null, + version integer not null, + scope_key text collate "C" not null, + updated_at text collate "C", + operation text collate "C", + digest text collate "C" not null, + body text not null, + unique (id, version) + ); + create index memory_versions_by_scope on replica_learning.memory_versions (scope_key, seq); + create index memory_versions_by_scope_id on replica_learning.memory_versions (scope_key, id); + create index memory_versions_by_time on replica_learning.memory_versions (scope_key, updated_at); + create index memory_versions_by_operation on replica_learning.memory_versions (scope_key, operation); diff --git a/packages/learning/test-database/postgres.test.mjs b/packages/learning/test-database/postgres.test.mjs index 8906d302..05f7f211 100644 --- a/packages/learning/test-database/postgres.test.mjs +++ b/packages/learning/test-database/postgres.test.mjs @@ -12,6 +12,7 @@ import { } from "node:fs" import { createConnection, createServer } from "node:net" import path from "node:path" +import { DatabaseSync } from "node:sqlite" import { after, afterEach, it } from "node:test" import { fileURLToPath } from "node:url" import pg from "pg" @@ -400,6 +401,57 @@ it("imports Hub history offline, preserves mappings and redactions, and refuses } }) +it("refuses an unknown SQLite stream after the scope was migrated", async () => { + const { root, source } = importWorkspace() + const url = await database() + const oldScope = { + host: "github.com", + repository: "repositories/11111111-2222-4333-8444-555555555555", + } + const scope = { host: "github.com", repository: "repositories/123456" } + const sourceProvider = createSqliteMemoryProvider({ directory: source }) + try { + await migrateRepositoryScope({ provider: sourceProvider, oldScope, newScope: scope }) + assert.ok(await sourceProvider.scopeMigrationFrom(oldScope)) + assert.ok((await sourceProvider.readRecords("events", { scope })).length > 0) + } finally { + await sourceProvider.close() + } + const sqlite = new DatabaseSync(path.join(source, "learning.sqlite")) + try { + sqlite + .prepare("insert into records (stream, id, scope_key, digest, body) values (?, ?, ?, ?, ?)") + .run("future_stream", "unknown", canonicalJson(scope), "sha256:unknown", "{}") + } finally { + sqlite.close() + } + + const result = await learningCommand(root, url, [ + "import-sqlite", + "--offline", + "--dir", + source, + "--repository", + `github.com/${scope.repository}`, + "--legacy-repository", + `github.com/${oldScope.repository}`, + ]) + const db = new pg.Client({ connectionString: url }) + await db.connect() + try { + assert.notEqual(result.code, 0) + assert.match(result.stderr, /error \(storage_corrupt\)/) + for (const table of ["records", "memory_versions", "scope_migrations", "sqlite_imports"]) { + const { rows } = await db.query( + `select count(*)::int as count from replica_learning.${table}`, + ) + assert.equal(rows[0].count, 0, table) + } + } finally { + await db.end() + } +}) + it("refuses unrelated history in the same scope but preserves other scopes", async () => { const { root, source } = importWorkspace() const url = await database() @@ -494,6 +546,75 @@ it("rolls back a failed PostgreSQL import and permits a retry", async () => { } }) +it("upgrades the base PostgreSQL schema without losing history", async () => { + const url = await database({ migrate: false }) + const db = new pg.Client({ connectionString: url }) + await db.connect() + const scope = { host: "github.com", repository: "repositories/123456" } + const record = { id: "grant_v1", digest: "sha256:grant", scope } + const memory = { id: "memory_v1", version: 1, digest: "sha256:memory", scope } + try { + await db.query("create schema replica_learning") + await db.query( + "create table replica_learning.schema_migrations (version integer primary key, checksum text not null)", + ) + // Keep the base schema and its ledger checksum independent of current migrations. + await db.query(readFileSync(new URL("./postgres-v1.sql", import.meta.url), "utf8")) + await db.query("insert into replica_learning.schema_migrations values (1, $1)", [ + "2d5e9ea362af3e7753d16c699f483c4d150b28b188f058d32b666db5b2a6c868", + ]) + await db.query( + "insert into replica_learning.records (stream, id, scope_key, digest, body) values ($1, $2, $3, $4, $5)", + ["grants", record.id, canonicalJson(scope), record.digest, JSON.stringify(record)], + ) + await db.query( + "insert into replica_learning.memory_versions (id, version, scope_key, digest, body) values ($1, $2, $3, $4, $5)", + [memory.id, memory.version, canonicalJson(scope), memory.digest, JSON.stringify(memory)], + ) + + assert.equal((await migratePostgres({ connectionString: url })).version, 2) + const ledger = await db.query( + "select version, checksum from replica_learning.schema_migrations order by version", + ) + assert.deepEqual( + ledger.rows.map((row) => row.version), + [1, 2], + ) + assert.equal( + ledger.rows[0].checksum, + "2d5e9ea362af3e7753d16c699f483c4d150b28b188f058d32b666db5b2a6c868", + ) + const target = provider(url) + assert.deepEqual(await target.readRecords("grants", { scope }), [record]) + assert.deepEqual(await target.readMemoryVersions({ scope }), [memory]) + + const importedScope = { host: "github.com", repository: "repositories/987654" } + const oldScope = { host: "github.com", repository: "repositories/old" } + const mapping = { oldScope, newScope: importedScope, digestMappings: [] } + const imported = { id: "grant_import", digest: "sha256:import", scope: importedScope } + const input = { + scope: importedScope, + records: { grants: [imported] }, + memories: [], + migrations: [mapping], + sourceDigest: "sha256:source", + beforeCommit: async () => {}, + } + assert.deepEqual(await target.importSqlite(input), { alreadyImported: false }) + assert.deepEqual(await target.importSqlite(input), { alreadyImported: true }) + await assert.rejects(target.importSqlite({ ...input, sourceDigest: "sha256:changed" }), { + code: "conflict", + }) + assert.deepEqual(await target.readRecords("grants", { scope: importedScope }), [imported]) + assert.deepEqual(await target.scopeMigrationFrom(oldScope), mapping) + assert.equal(await target.hasSqliteImport(importedScope), true) + assert.deepEqual(await target.readRecords("grants", { scope }), [record]) + assert.deepEqual(await target.readMemoryVersions({ scope }), [memory]) + } finally { + await db.end() + } +}) + it("migrates only with the migration URL and lets a limited runtime login use the store", async () => { const url = await database({ migrate: false }) const role = `replica_test_${randomBytes(12).toString("hex")}` From 28939cd6d1aa5472002b3ea570776a6521a4a9d8 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 10:50:30 -0800 Subject: [PATCH 07/18] docs(hub): describe the learning database role Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 836fcecf-e7a9-4975-acd2-bf761098f711 --- hub/docs/database.md | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/hub/docs/database.md b/hub/docs/database.md index 08c020a4..324ecbe0 100644 --- a/hub/docs/database.md +++ b/hub/docs/database.md @@ -104,16 +104,17 @@ Validate schema changes on both a fresh database and an upgrade from the exact b The Azure installation separates database provisioning, migrations, and normal data access: -| Principal | Access | -| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Administrator | One-time database and role provisioning; never passed to Hub or its setup job. | -| `replica_migration` | Can create schemas in this database and owns `public`, `bullmq`, and their migration-created objects. Runs setup, not the long-running app. | -| `replica_runtime` | Uses both schemas, reads/writes application and queue data, uses sequences and executes queue functions. Cannot create schemas, change permanent schema objects, create roles, truncate tables, or change migration ledgers. BullMQ requires read access to its ledger and temporary-table permission for bulk jobs. | +| Principal | Access | +| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Administrator | One-time database and role provisioning; never passed to Hub or its setup job. | +| `replica_migration` | Can create schemas in this database and owns `public`, `bullmq`, and their migration-created objects. Runs setup, not the long-running app. | +| `replica_runtime` | Uses both schemas, reads/writes application and queue data, uses sequences and executes queue functions. Cannot create schemas, change permanent schema objects, create roles, truncate tables, or change migration ledgers. BullMQ requires read access to its ledger and temporary-table permission for bulk jobs. | +| `replica_learning_runtime` | Uses the separate learning schema for learning operations. It does not access Hub application or queue data. | -`server/scripts/provision-database-access/` creates the two login roles and schema ownership on a fresh database. It requires administrator access over the private database network and separate passwords of at least 16 characters. Existing roles, public tables, or a pre-existing BullMQ schema cause failure and rollback rather than adopting unknown permissions. Use a reviewed ownership migration for existing installations. +`server/scripts/provision-database-access/` creates the three login roles and schema ownership on a fresh database. It requires administrator access over the private database network and separate passwords of at least 16 characters. Existing roles, public tables, or a pre-existing BullMQ schema cause failure and rollback rather than adopting unknown permissions. Use a reviewed ownership migration for existing installations. When `DATABASE_RUNTIME_ROLE=replica_runtime`, setup runs `server/scripts/grant-runtime-database-access/` after Prisma and BullMQ setup. That script initializes the two queues' lazy ID sequences before granting data access, so runtime never needs permanent schema creation rights. It refreshes grants for newly migrated tables, sequences, and functions, excludes the Prisma ledger, and permits only reading BullMQ's ledger. Product additions that need other database capabilities must explicitly update and verify this contract. -Local development keeps its existing database user and leaves `DATABASE_RUNTIME_ROLE` unset. See the [Azure installation guide](../../infrastructure/README.md) for private-network provisioning, secret references, release ordering, and recovery. +Local development keeps its existing database user and leaves `DATABASE_RUNTIME_ROLE` unset. See the [learning package guide](../../packages/learning/README.md) for learning database privileges and the [Azure installation guide](../../infrastructure/README.md) for fresh and existing-install provisioning, secret references, release ordering, and recovery. The [database-enabled test projects](testing-and-operations.md#parallel-database-tests) use separate databases for every project, worker, and test run. Setup deploys the committed migrations and clears records before each case. Tests do not use the development database for records. From e0c7c933f18bfe09c178e5b66f52ded6b07bfac1 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 10:57:57 -0800 Subject: [PATCH 08/18] fix(learning): reject noncanonical SQLite scope keys Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 836fcecf-e7a9-4975-acd2-bf761098f711 --- packages/learning/src/providers/sqlite.mjs | 12 +- .../learning/test-database/postgres.test.mjs | 117 ++++++++++++++++++ 2 files changed, 128 insertions(+), 1 deletion(-) diff --git a/packages/learning/src/providers/sqlite.mjs b/packages/learning/src/providers/sqlite.mjs index 7d6f6ecd..b15ae26a 100644 --- a/packages/learning/src/providers/sqlite.mjs +++ b/packages/learning/src/providers/sqlite.mjs @@ -238,7 +238,17 @@ export function createSqliteMemoryProvider({ directory, file = "learning.sqlite" return database .prepare("select scope_key from records union select scope_key from memory_versions") .all() - .map((row) => JSON.parse(row.scope_key)) + .map((row) => { + let scope + try { + scope = JSON.parse(row.scope_key) + } catch { + throw new LearningError("storage_corrupt", "SQLite store has an invalid scope key.") + } + if (canonicalJson(scope) !== row.scope_key) + throw new LearningError("storage_corrupt", "SQLite store has a noncanonical scope key.") + return scope + }) } return { diff --git a/packages/learning/test-database/postgres.test.mjs b/packages/learning/test-database/postgres.test.mjs index 05f7f211..08d77ee2 100644 --- a/packages/learning/test-database/postgres.test.mjs +++ b/packages/learning/test-database/postgres.test.mjs @@ -452,6 +452,123 @@ it("refuses an unknown SQLite stream after the scope was migrated", async () => } }) +it("refuses noncanonical SQLite record scopes after migration", async () => { + const { root, source } = importWorkspace() + const oldScope = { + host: "github.com", + repository: "repositories/11111111-2222-4333-8444-555555555555", + } + const scope = { host: "github.com", repository: "repositories/123456" } + const sourceProvider = createSqliteMemoryProvider({ directory: source }) + try { + await migrateRepositoryScope({ + provider: sourceProvider, + oldScope, + newScope: scope, + }) + assert.ok(await sourceProvider.scopeMigrationFrom(oldScope)) + assert.ok((await sourceProvider.readRecords("audit", { scope })).length > 0) + assert.ok((await sourceProvider.readMemoryVersions({ scope })).length > 0) + } finally { + await sourceProvider.close() + } + const sqlite = new DatabaseSync(path.join(source, "learning.sqlite")) + try { + // Visible versions without their audits would fail verification for a different reason. + sqlite.prepare("delete from memory_versions").run() + const changed = sqlite + .prepare("update records set scope_key = ? where scope_key = ?") + .run(` ${canonicalJson(scope)}`, canonicalJson(scope)) + assert.ok(changed.changes > 0) + assert.ok( + sqlite + .prepare("select count(*) as count from records where stream = 'audit' and scope_key = ?") + .get(` ${canonicalJson(scope)}`).count > 0, + ) + } finally { + sqlite.close() + } + const url = await database() + const result = await learningCommand(root, url, [ + "import-sqlite", + "--offline", + "--dir", + source, + "--repository", + `github.com/${scope.repository}`, + "--legacy-repository", + `github.com/${oldScope.repository}`, + ]) + const db = new pg.Client({ connectionString: url }) + await db.connect() + try { + assert.notEqual(result.code, 0) + assert.match(result.stderr, /error \(storage_corrupt\)/) + for (const table of ["records", "memory_versions", "scope_migrations", "sqlite_imports"]) { + const { rows } = await db.query( + `select count(*)::int as count from replica_learning.${table}`, + ) + assert.equal(rows[0].count, 0, table) + } + } finally { + await db.end() + } +}) + +it("refuses noncanonical SQLite memory version scopes after migration", async () => { + const { root, source } = importWorkspace() + const oldScope = { + host: "github.com", + repository: "repositories/11111111-2222-4333-8444-555555555555", + } + const scope = { host: "github.com", repository: "repositories/123456" } + const sourceProvider = createSqliteMemoryProvider({ directory: source }) + try { + await migrateRepositoryScope({ provider: sourceProvider, oldScope, newScope: scope }) + assert.ok(await sourceProvider.scopeMigrationFrom(oldScope)) + assert.ok((await sourceProvider.readMemoryVersions({ scope })).length > 0) + } finally { + await sourceProvider.close() + } + const sqlite = new DatabaseSync(path.join(source, "learning.sqlite")) + try { + // Visible audits without their versions would fail verification for a different reason. + sqlite.prepare("delete from records").run() + const noncanonical = JSON.stringify({ repository: scope.repository, host: scope.host }) + const changed = sqlite + .prepare("update memory_versions set scope_key = ? where scope_key = ?") + .run(noncanonical, canonicalJson(scope)) + assert.ok(changed.changes > 0) + } finally { + sqlite.close() + } + const url = await database() + const result = await learningCommand(root, url, [ + "import-sqlite", + "--offline", + "--dir", + source, + "--repository", + `github.com/${scope.repository}`, + "--legacy-repository", + `github.com/${oldScope.repository}`, + ]) + const db = new pg.Client({ connectionString: url }) + await db.connect() + try { + assert.notEqual(result.code, 0) + assert.match(result.stderr, /error \(storage_corrupt\)/) + for (const table of ["records", "memory_versions", "scope_migrations", "sqlite_imports"]) { + const { rows } = await db.query( + `select count(*)::int as count from replica_learning.${table}`, + ) + assert.equal(rows[0].count, 0, table) + } + } finally { + await db.end() + } +}) + it("refuses unrelated history in the same scope but preserves other scopes", async () => { const { root, source } = importWorkspace() const url = await database() From 74ebf8540cdfd46a10079c37f76b32d299de80ee Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 11:03:50 -0800 Subject: [PATCH 09/18] fix(learning): validate SQLite migration mappings Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 836fcecf-e7a9-4975-acd2-bf761098f711 --- packages/learning/src/providers/sqlite.mjs | 45 +++- .../learning/test-database/postgres.test.mjs | 212 ++++++++++++++++++ 2 files changed, 247 insertions(+), 10 deletions(-) diff --git a/packages/learning/src/providers/sqlite.mjs b/packages/learning/src/providers/sqlite.mjs index b15ae26a..87b3983d 100644 --- a/packages/learning/src/providers/sqlite.mjs +++ b/packages/learning/src/providers/sqlite.mjs @@ -235,20 +235,45 @@ export function createSqliteMemoryProvider({ directory, file = "learning.sqlite" for (const { stream } of database.prepare("select distinct stream from records").all()) if (!Object.hasOwn(STREAMS, stream)) throw new LearningError("storage_corrupt", "SQLite store has an unknown record stream.") - return database + function parseScopeKey(key) { + try { + const scope = JSON.parse(key) + if (!scope || typeof scope !== "object" || Array.isArray(scope)) throw new Error() + if (canonicalJson(scope) === key) return scope + } catch { + throw new LearningError("storage_corrupt", "SQLite store has an invalid scope key.") + } + throw new LearningError("storage_corrupt", "SQLite store has a noncanonical scope key.") + } + const scopes = new Map() + for (const { scope_key: key } of database .prepare("select scope_key from records union select scope_key from memory_versions") - .all() - .map((row) => { - let scope + .all()) + scopes.set(key, parseScopeKey(key)) + if ( + database + .prepare("select 1 from sqlite_master where type = 'table' and name = 'scope_migrations'") + .get() + ) { + for (const row of database + .prepare("select old_scope_key, new_scope_key, metadata from scope_migrations") + .all()) { + parseScopeKey(row.old_scope_key) + const target = parseScopeKey(row.new_scope_key) try { - scope = JSON.parse(row.scope_key) + const metadata = JSON.parse(row.metadata) + if ( + canonicalJson(metadata.oldScope) !== row.old_scope_key || + canonicalJson(metadata.newScope) !== row.new_scope_key + ) + throw new Error() } catch { - throw new LearningError("storage_corrupt", "SQLite store has an invalid scope key.") + throw new LearningError("storage_corrupt", "SQLite store has an invalid scope mapping.") } - if (canonicalJson(scope) !== row.scope_key) - throw new LearningError("storage_corrupt", "SQLite store has a noncanonical scope key.") - return scope - }) + scopes.set(row.new_scope_key, target) + } + } + return [...scopes.values()] } return { diff --git a/packages/learning/test-database/postgres.test.mjs b/packages/learning/test-database/postgres.test.mjs index 08d77ee2..0600a123 100644 --- a/packages/learning/test-database/postgres.test.mjs +++ b/packages/learning/test-database/postgres.test.mjs @@ -569,6 +569,218 @@ it("refuses noncanonical SQLite memory version scopes after migration", async () } }) +it("refuses a hidden noncanonical SQLite migration target", async () => { + const { root, source } = importWorkspace() + const oldScope = { + host: "github.com", + repository: "repositories/11111111-2222-4333-8444-555555555555", + } + const otherOldScope = { + host: "github.com", + repository: "repositories/aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee", + } + const scope = { host: "github.com", repository: "repositories/123456" } + const sourceProvider = createSqliteMemoryProvider({ directory: source }) + try { + await migrateRepositoryScope({ provider: sourceProvider, oldScope, newScope: scope }) + const primary = await sourceProvider.scopeMigrationFrom(oldScope) + assert.deepEqual(primary.oldScope, oldScope) + assert.deepEqual(primary.newScope, scope) + assert.ok(primary.digestMappings.length > 0) + } finally { + await sourceProvider.close() + } + const sqlite = new DatabaseSync(path.join(source, "learning.sqlite")) + try { + const inserted = sqlite + .prepare( + `insert into scope_migrations (old_scope_key, new_scope_key, metadata) + select ?, ?, json_set(metadata, '$.oldScope', json(?), '$.digestMappings', json('[]')) + from scope_migrations where old_scope_key = ? and new_scope_key = ?`, + ) + .run( + canonicalJson(otherOldScope), + ` ${canonicalJson(scope)}`, + canonicalJson(otherOldScope), + canonicalJson(oldScope), + canonicalJson(scope), + ) + assert.equal(inserted.changes, 1) + } finally { + sqlite.close() + } + const url = await database() + const result = await learningCommand(root, url, [ + "import-sqlite", + "--offline", + "--dir", + source, + "--repository", + `github.com/${scope.repository}`, + "--legacy-repository", + `github.com/${oldScope.repository}`, + ]) + const db = new pg.Client({ connectionString: url }) + await db.connect() + try { + assert.notEqual(result.code, 0) + assert.match(result.stderr, /error \(storage_corrupt\)/) + for (const table of ["records", "memory_versions", "scope_migrations", "sqlite_imports"]) { + const { rows } = await db.query( + `select count(*)::int as count from replica_learning.${table}`, + ) + assert.equal(rows[0].count, 0, table) + } + } finally { + await db.end() + } +}) + +it("refuses a SQLite migration target that disagrees with its metadata", async () => { + const { root, source } = importWorkspace() + const oldScope = { + host: "github.com", + repository: "repositories/11111111-2222-4333-8444-555555555555", + } + const otherOldScope = { + host: "github.com", + repository: "repositories/aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee", + } + const scope = { host: "github.com", repository: "repositories/123456" } + const otherScope = { host: "github.com", repository: "repositories/654321" } + const sourceProvider = createSqliteMemoryProvider({ directory: source }) + try { + await migrateRepositoryScope({ provider: sourceProvider, oldScope, newScope: scope }) + const primary = await sourceProvider.scopeMigrationFrom(oldScope) + assert.deepEqual(primary.oldScope, oldScope) + assert.deepEqual(primary.newScope, scope) + assert.ok(primary.digestMappings.length > 0) + } finally { + await sourceProvider.close() + } + const sqlite = new DatabaseSync(path.join(source, "learning.sqlite")) + try { + const inserted = sqlite + .prepare( + `insert into scope_migrations (old_scope_key, new_scope_key, metadata) + select ?, ?, json_set(metadata, '$.oldScope', json(?), '$.digestMappings', json('[]')) + from scope_migrations where old_scope_key = ? and new_scope_key = ?`, + ) + .run( + canonicalJson(otherOldScope), + canonicalJson(otherScope), + canonicalJson(otherOldScope), + canonicalJson(oldScope), + canonicalJson(scope), + ) + assert.equal(inserted.changes, 1) + } finally { + sqlite.close() + } + const url = await database() + const result = await learningCommand(root, url, [ + "import-sqlite", + "--offline", + "--dir", + source, + "--repository", + `github.com/${scope.repository}`, + "--legacy-repository", + `github.com/${oldScope.repository}`, + ]) + const db = new pg.Client({ connectionString: url }) + await db.connect() + try { + assert.notEqual(result.code, 0) + assert.match(result.stderr, /error \(storage_corrupt\)/) + for (const table of ["records", "memory_versions", "scope_migrations", "sqlite_imports"]) { + const { rows } = await db.query( + `select count(*)::int as count from replica_learning.${table}`, + ) + assert.equal(rows[0].count, 0, table) + } + } finally { + await db.end() + } +}) + +it("refuses a SQLite migration to another target with no records", async () => { + const { root, source } = importWorkspace() + const oldScope = { + host: "github.com", + repository: "repositories/11111111-2222-4333-8444-555555555555", + } + const otherOldScope = { + host: "github.com", + repository: "repositories/aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee", + } + const scope = { host: "github.com", repository: "repositories/123456" } + const otherScope = { host: "github.com", repository: "repositories/654321" } + const sourceProvider = createSqliteMemoryProvider({ directory: source }) + try { + await migrateRepositoryScope({ provider: sourceProvider, oldScope, newScope: scope }) + const primary = await sourceProvider.scopeMigrationFrom(oldScope) + assert.deepEqual(primary.oldScope, oldScope) + assert.deepEqual(primary.newScope, scope) + assert.ok(primary.digestMappings.length > 0) + assert.deepEqual(await sourceProvider.readMemoryVersions({ scope: otherScope }), []) + } finally { + await sourceProvider.close() + } + const sqlite = new DatabaseSync(path.join(source, "learning.sqlite")) + try { + const inserted = sqlite + .prepare( + `insert into scope_migrations (old_scope_key, new_scope_key, metadata) + select ?, ?, json_set(metadata, '$.oldScope', json(?), '$.newScope', json(?), + '$.digestMappings', json('[]')) + from scope_migrations where old_scope_key = ? and new_scope_key = ?`, + ) + .run( + canonicalJson(otherOldScope), + canonicalJson(otherScope), + canonicalJson(otherOldScope), + canonicalJson(otherScope), + canonicalJson(oldScope), + canonicalJson(scope), + ) + assert.equal(inserted.changes, 1) + assert.equal( + sqlite + .prepare("select count(*) as count from records where scope_key = ?") + .get(canonicalJson(otherScope)).count, + 0, + ) + } finally { + sqlite.close() + } + const url = await database() + const result = await learningCommand(root, url, [ + "import-sqlite", + "--offline", + "--dir", + source, + "--repository", + `github.com/${scope.repository}`, + "--legacy-repository", + `github.com/${oldScope.repository}`, + ]) + const db = new pg.Client({ connectionString: url }) + await db.connect() + try { + assert.notEqual(result.code, 0) + assert.match(result.stderr, /error \(conflict\)/) + for (const table of ["records", "memory_versions", "scope_migrations", "sqlite_imports"]) { + const { rows } = await db.query( + `select count(*)::int as count from replica_learning.${table}`, + ) + assert.equal(rows[0].count, 0, table) + } + } finally { + await db.end() + } +}) + it("refuses unrelated history in the same scope but preserves other scopes", async () => { const { root, source } = importWorkspace() const url = await database() From e5e87d80154705c2309cee328f65f2535f0a252b Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 11:09:54 -0800 Subject: [PATCH 10/18] fix(learning): validate SQLite indexed rows before import Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 836fcecf-e7a9-4975-acd2-bf761098f711 --- packages/learning/src/providers/sqlite.mjs | 79 +++++++----- .../learning/test-database/postgres.test.mjs | 118 ++++++++++++++++++ 2 files changed, 167 insertions(+), 30 deletions(-) diff --git a/packages/learning/src/providers/sqlite.mjs b/packages/learning/src/providers/sqlite.mjs index 87b3983d..939892b3 100644 --- a/packages/learning/src/providers/sqlite.mjs +++ b/packages/learning/src/providers/sqlite.mjs @@ -229,12 +229,44 @@ export function createSqliteMemoryProvider({ directory, file = "learning.sqlite" }) } + function storedRecord(row) { + try { + if (!Object.hasOwn(STREAMS, row.stream)) throw new Error() + const record = JSON.parse(row.body) + if ( + row.id === record.id && + row.scope_key === canonicalJson(record.scope) && + row.digest === record.digest && + row.occurred_at === text(record[STREAMS[row.stream]]) && + row.episode_id === text(row.stream === "episodes" ? record.id : record.episodeId) + ) + return record + } catch { + throw new LearningError("storage_corrupt", "SQLite store has an invalid record row.") + } + throw new LearningError("storage_corrupt", "SQLite store has an inconsistent record row.") + } + + function storedMemory(row) { + try { + const record = JSON.parse(row.body) + if ( + row.id === record.id && + row.version === record.version && + row.scope_key === canonicalJson(record.scope) && + row.digest === record.digest && + row.updated_at === text(record.updatedAt) + ) + return record + } catch { + throw new LearningError("storage_corrupt", "SQLite store has an invalid memory row.") + } + throw new LearningError("storage_corrupt", "SQLite store has an inconsistent memory row.") + } + function storedScopes() { const database = connect({ create: false }) if (!database) return [] - for (const { stream } of database.prepare("select distinct stream from records").all()) - if (!Object.hasOwn(STREAMS, stream)) - throw new LearningError("storage_corrupt", "SQLite store has an unknown record stream.") function parseScopeKey(key) { try { const scope = JSON.parse(key) @@ -246,10 +278,18 @@ export function createSqliteMemoryProvider({ directory, file = "learning.sqlite" throw new LearningError("storage_corrupt", "SQLite store has a noncanonical scope key.") } const scopes = new Map() - for (const { scope_key: key } of database - .prepare("select scope_key from records union select scope_key from memory_versions") - .all()) - scopes.set(key, parseScopeKey(key)) + for (const row of database + .prepare("select stream, id, scope_key, occurred_at, episode_id, digest, body from records") + .iterate()) { + storedRecord(row) + if (!scopes.has(row.scope_key)) scopes.set(row.scope_key, parseScopeKey(row.scope_key)) + } + for (const row of database + .prepare("select id, version, scope_key, updated_at, digest, body from memory_versions") + .iterate()) { + storedMemory(row) + if (!scopes.has(row.scope_key)) scopes.set(row.scope_key, parseScopeKey(row.scope_key)) + } if ( database .prepare("select 1 from sqlite_master where type = 'table' and name = 'scope_migrations'") @@ -569,31 +609,10 @@ export function createSqliteMemoryProvider({ directory, file = "learning.sqlite" throw new LearningError("storage_corrupt", `Memory ${id} spans repository scopes.`) const records = Object.fromEntries(Object.keys(STREAMS).map((stream) => [stream, []])) for (const row of rows) { - if (!Object.hasOwn(records, row.stream)) - throw new LearningError("storage_corrupt", `Unknown stored stream ${row.stream}.`) - const record = JSON.parse(row.body) - if ( - row.id !== record.id || - row.scope_key !== canonicalJson(record.scope) || - row.digest !== record.digest || - row.occurred_at !== text(record[STREAMS[row.stream]]) || - row.episode_id !== text(row.stream === "episodes" ? record.id : record.episodeId) - ) - throw new LearningError("storage_corrupt", `Inconsistent ${row.stream} row ${row.id}.`) + const record = storedRecord(row) records[row.stream].push(record) } - const memories = versions.map((row) => { - const record = JSON.parse(row.body) - if ( - row.id !== record.id || - row.version !== record.version || - row.scope_key !== canonicalJson(record.scope) || - row.digest !== record.digest || - row.updated_at !== text(record.updatedAt) - ) - throw new LearningError("storage_corrupt", `Inconsistent memory row ${row.id}.`) - return record - }) + const memories = versions.map(storedMemory) const targetRecords = Object.fromEntries(Object.keys(STREAMS).map((stream) => [stream, []])) for (const row of database .prepare("select stream, body from records where scope_key = ? order by seq") diff --git a/packages/learning/test-database/postgres.test.mjs b/packages/learning/test-database/postgres.test.mjs index 0600a123..717fa73f 100644 --- a/packages/learning/test-database/postgres.test.mjs +++ b/packages/learning/test-database/postgres.test.mjs @@ -401,6 +401,124 @@ it("imports Hub history offline, preserves mappings and redactions, and refuses } }) +it("refuses a duplicate audited grant under a different SQLite record ID", async () => { + const { root, source } = importWorkspace() + const oldScope = { + host: "github.com", + repository: "repositories/11111111-2222-4333-8444-555555555555", + } + const scope = { host: "github.com", repository: "repositories/123456" } + const sourceProvider = createSqliteMemoryProvider({ directory: source }) + try { + await migrateRepositoryScope({ + provider: sourceProvider, + oldScope, + newScope: scope, + }) + assert.ok(await sourceProvider.scopeMigrationFrom(oldScope)) + assert.ok((await sourceProvider.readRecords("grants", { scope })).length > 0) + assert.ok((await sourceProvider.readRecords("audit", { scope })).length > 0) + } finally { + await sourceProvider.close() + } + const sqlite = new DatabaseSync(path.join(source, "learning.sqlite")) + try { + const inserted = sqlite + .prepare( + `insert into records (stream, id, scope_key, occurred_at, episode_id, digest, body) + select stream, ?, scope_key, occurred_at, episode_id, digest, body + from records where stream = 'grants' and scope_key = ? limit 1`, + ) + .run("grant_mismatched_physical_id", canonicalJson(scope)) + assert.equal(inserted.changes, 1) + } finally { + sqlite.close() + } + const url = await database() + const result = await learningCommand(root, url, [ + "import-sqlite", + "--offline", + "--dir", + source, + "--repository", + `github.com/${scope.repository}`, + "--legacy-repository", + `github.com/${oldScope.repository}`, + ]) + const db = new pg.Client({ connectionString: url }) + await db.connect() + try { + assert.notEqual(result.code, 0) + assert.match(result.stderr, /error \(storage_corrupt\)/) + for (const table of ["records", "memory_versions", "scope_migrations", "sqlite_imports"]) { + const { rows } = await db.query( + `select count(*)::int as count from replica_learning.${table}`, + ) + assert.equal(rows[0].count, 0, table) + } + } finally { + await db.end() + } +}) + +it("refuses a SQLite memory version with a mismatched indexed update time", async () => { + const { root, source } = importWorkspace() + const oldScope = { + host: "github.com", + repository: "repositories/11111111-2222-4333-8444-555555555555", + } + const scope = { host: "github.com", repository: "repositories/123456" } + const sourceProvider = createSqliteMemoryProvider({ directory: source }) + try { + await migrateRepositoryScope({ + provider: sourceProvider, + oldScope, + newScope: scope, + }) + assert.ok(await sourceProvider.scopeMigrationFrom(oldScope)) + assert.ok((await sourceProvider.readMemoryVersions({ scope })).length > 0) + } finally { + await sourceProvider.close() + } + const sqlite = new DatabaseSync(path.join(source, "learning.sqlite")) + try { + const changed = sqlite + .prepare( + `update memory_versions set updated_at = ? + where seq = (select seq from memory_versions where scope_key = ? limit 1)`, + ) + .run("1900-01-01T00:00:00.000Z", canonicalJson(scope)) + assert.equal(changed.changes, 1) + } finally { + sqlite.close() + } + const url = await database() + const result = await learningCommand(root, url, [ + "import-sqlite", + "--offline", + "--dir", + source, + "--repository", + `github.com/${scope.repository}`, + "--legacy-repository", + `github.com/${oldScope.repository}`, + ]) + const db = new pg.Client({ connectionString: url }) + await db.connect() + try { + assert.notEqual(result.code, 0) + assert.match(result.stderr, /error \(storage_corrupt\)/) + for (const table of ["records", "memory_versions", "scope_migrations", "sqlite_imports"]) { + const { rows } = await db.query( + `select count(*)::int as count from replica_learning.${table}`, + ) + assert.equal(rows[0].count, 0, table) + } + } finally { + await db.end() + } +}) + it("refuses an unknown SQLite stream after the scope was migrated", async () => { const { root, source } = importWorkspace() const url = await database() From 8107989874ff9d9f313c2af21d1f3509ebeb601b Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 11:28:08 -0800 Subject: [PATCH 11/18] fix(hub): update learning database setup checks Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 836fcecf-e7a9-4975-acd2-bf761098f711 --- hub/script/check-image/index.ts | 3 +++ .../load-secret-environment/index.test.ts | 11 ++++++++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/hub/script/check-image/index.ts b/hub/script/check-image/index.ts index 87991068..ebb826c1 100644 --- a/hub/script/check-image/index.ts +++ b/hub/script/check-image/index.ts @@ -92,6 +92,7 @@ export async function checkImage() { await new Promise((resolve) => setTimeout(resolve, 500)) } const databaseUrl = `DATABASE_URL=postgresql://replica:replica@${database}:5432/replica` + const learningPassword = "replica-learning-image-only" const migrationPassword = "replica-migration-image-only" const runtimePassword = "replica-runtime-image-only" docker( @@ -102,6 +103,8 @@ export async function checkImage() { "-e", databaseUrl, "-e", + `HUB_LEARNING_PASSWORD=${learningPassword}`, + "-e", `HUB_MIGRATION_PASSWORD=${migrationPassword}`, "-e", `HUB_RUNTIME_PASSWORD=${runtimePassword}`, diff --git a/hub/server/scripts/azure-entrypoint/load-secret-environment/index.test.ts b/hub/server/scripts/azure-entrypoint/load-secret-environment/index.test.ts index 4a983bb1..7a08de1c 100644 --- a/hub/server/scripts/azure-entrypoint/load-secret-environment/index.test.ts +++ b/hub/server/scripts/azure-entrypoint/load-secret-environment/index.test.ts @@ -135,12 +135,14 @@ describe("loadAzureSecretEnvironment()", () => { vi.useFakeTimers() const version = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" const databaseUrl = `https://fixture.vault.azure.net/secrets/database/${version}` + const learningUrl = `https://fixture.vault.azure.net/secrets/learning/${version}` const migrationUrl = `https://fixture.vault.azure.net/secrets/migration/${version}` const runtimeUrl = `https://fixture.vault.azure.net/secrets/runtime/${version}` const environment: NodeJS.ProcessEnv = { AZURE_CLIENT_ID: "00000000-0000-0000-0000-000000000001", AZURE_KEY_VAULT_SECRET_REFERENCES: JSON.stringify({ DATABASE_URL: databaseUrl, + HUB_LEARNING_PASSWORD: learningUrl, HUB_MIGRATION_PASSWORD: migrationUrl, HUB_RUNTIME_PASSWORD: runtimeUrl, }), @@ -155,9 +157,11 @@ describe("loadAzureSecretEnvironment()", () => { return Promise.resolve( url === databaseUrl ? "synthetic-database-url" - : url === migrationUrl - ? "synthetic-migration-password" - : "synthetic-runtime-password", + : url === learningUrl + ? "synthetic-learning-password" + : url === migrationUrl + ? "synthetic-migration-password" + : "synthetic-runtime-password", ) }) @@ -176,6 +180,7 @@ describe("loadAzureSecretEnvironment()", () => { expect(environment).toEqual({ ...before, DATABASE_URL: "synthetic-database-url", + HUB_LEARNING_PASSWORD: "synthetic-learning-password", HUB_MIGRATION_PASSWORD: "synthetic-migration-password", HUB_RUNTIME_PASSWORD: "synthetic-runtime-password", }) From 4a9f63e3630c4fa64b06ea587a5281e67f013b18 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 11:28:08 -0800 Subject: [PATCH 12/18] fix(hub): protect learning database credentials Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 836fcecf-e7a9-4975-acd2-bf761098f711 --- .../run-learning-command/index.test.ts | 49 +++++++++++++++++-- .../learning/run-learning-command/index.ts | 31 ++++++++++-- 2 files changed, 73 insertions(+), 7 deletions(-) diff --git a/hub/server/integrations/learning/run-learning-command/index.test.ts b/hub/server/integrations/learning/run-learning-command/index.test.ts index 57351fa9..899b6fa6 100644 --- a/hub/server/integrations/learning/run-learning-command/index.test.ts +++ b/hub/server/integrations/learning/run-learning-command/index.test.ts @@ -4,6 +4,7 @@ import { isAbsolute, relative, resolve, sep } from "node:path" import { describe, expect, it, onTestFinished } from "vitest" import { runLearningCommand } from "." +import { LearningCommandError } from "./errors" const fixtures = resolve("test/fixtures/learning") @@ -117,7 +118,7 @@ describe("runLearningCommand()", () => { }, }, }) - expect(JSON.parse(result.config).memory.requireImport).toBeUndefined() + expect(JSON.parse(result.config)).not.toHaveProperty("memory.requireImport") for (const secret of [ databaseUrl, "learning-password", @@ -204,7 +205,7 @@ describe("runLearningCommand()", () => { await expect(stat(result.temporaryDirectory)).rejects.toMatchObject({ code: "ENOENT" }) }) - it("passes an explicitly supplied learning database URL to a command without a store", async () => { + it("does not pass the configured learning database URL to a command without a store", async () => { const databaseUrl = "postgres://learning-user:learning-password@localhost/learning" const result = (await runLearningCommand(["copilot", "status"], { cliPath: resolve(fixtures, "report-runtime.mjs"), @@ -220,7 +221,6 @@ describe("runLearningCommand()", () => { expect(result.environment).toEqual({ PATH: process.env.PATH, TMPDIR: result.temporaryDirectory, - REPLICA_LEARNING_DATABASE_URL: databaseUrl, }) await expect(stat(result.temporaryDirectory)).rejects.toMatchObject({ code: "ENOENT" }) }) @@ -294,6 +294,49 @@ describe("runLearningCommand()", () => { }) }) + it("keeps the database URL and password out of command errors", async () => { + const directory = resolve(`server/integrations/learning/.process-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { force: true, recursive: true })) + const cliPath = resolve(directory, "fail.mjs") + await writeFile( + cliPath, + ` + const databaseUrl = process.env.REPLICA_LEARNING_DATABASE_URL + const encodedPassword = new URL(databaseUrl).password + const password = decodeURIComponent(encodedPassword) + process.stdout.write(JSON.stringify({ + considered: 3, + details: { databaseUrl, password, [password]: encodedPassword }, + })) + process.stderr.write("error (learning_failed): Database connection failed: " + databaseUrl + " " + password + " " + encodedPassword) + process.exitCode = 1 + `, + ) + const password = "learning@password" + const encodedPassword = "learning%40password" + const databaseUrl = `postgres://learning-user:${encodedPassword}@localhost/learning` + + const error: unknown = await runLearningCommand( + ["label", "--dir", resolve(directory, "store")], + { + cliPath, + learningDatabaseUrl: databaseUrl, + environment: { PATH: process.env.PATH }, + }, + ).catch((failure: unknown) => failure) + + expect(error).toBeInstanceOf(LearningCommandError) + if (!(error instanceof LearningCommandError)) throw new Error("Expected a command failure.") + expect(error.code).toBe("learning_failed") + expect(error.result).toMatchObject({ considered: 3 }) + const result = JSON.stringify(error.result) ?? "" + for (const secret of [databaseUrl, password, encodedPassword]) { + expect.soft(error.message).not.toContain(secret) + expect.soft(result).not.toContain(secret) + } + }) + it.each([ ["stdout", "outputLimit"], ["stderr", "errorLimit"], diff --git a/hub/server/integrations/learning/run-learning-command/index.ts b/hub/server/integrations/learning/run-learning-command/index.ts index 659c5cb0..94d5ac3f 100644 --- a/hub/server/integrations/learning/run-learning-command/index.ts +++ b/hub/server/integrations/learning/run-learning-command/index.ts @@ -107,8 +107,8 @@ export async function runLearningCommand( await chmod(temporaryDirectory, 0o700) try { const commandArguments = [...arguments_] + let hasDirectory = false if (learningDatabaseUrl) { - let hasDirectory = false let requireImport = false async function preserveExistingStore(directory: string) { try { @@ -148,6 +148,29 @@ export async function runLearningCommand( ) } } + const secrets = [learningDatabaseUrl, githubToken].filter((value): value is string => + Boolean(value), + ) + if (learningDatabaseUrl) { + try { + const password = new URL(learningDatabaseUrl).password + if (password) secrets.push(password, decodeURIComponent(password)) + } catch { + // The command reports an invalid URL without requiring it to be parsed here. + } + } + function redact(value: string) { + return secrets.reduce((text, secret) => text.replaceAll(secret, "[redacted]"), value) + } + function redactResult(value: unknown): unknown { + if (typeof value === "string") return redact(value) + if (Array.isArray(value)) return value.map(redactResult) + if (value && typeof value === "object") + return Object.fromEntries( + Object.entries(value).map(([key, item]) => [redact(key), redactResult(item)]), + ) + return value + } return await new Promise((resolve, reject) => { const child = spawn( nodePath, @@ -159,7 +182,7 @@ export async function runLearningCommand( environment, temporaryDirectory, githubToken, - learningDatabaseUrl, + hasDirectory ? learningDatabaseUrl : undefined, ), stdio: ["ignore", "pipe", "pipe"], }, @@ -268,13 +291,13 @@ export async function runLearningCommand( return } const stdout = Buffer.concat(output).toString("utf8") - const stderr = Buffer.concat(errors).toString("utf8").trim() + const stderr = redact(Buffer.concat(errors).toString("utf8").trim()) if (code !== 0) { const match = errorPattern.exec(stderr) let result: unknown if (stdout.trim()) { try { - result = JSON.parse(stdout) + result = redactResult(JSON.parse(stdout)) } catch { result = undefined } From c22d9a76822e4e96595f53d3733828e7063142ad Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 11:36:48 -0800 Subject: [PATCH 13/18] fix(hub): redact supported database credentials Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 836fcecf-e7a9-4975-acd2-bf761098f711 --- .../run-learning-command/index.test.ts | 100 ++++++++++++++++++ .../learning/run-learning-command/index.ts | 25 ++++- 2 files changed, 120 insertions(+), 5 deletions(-) diff --git a/hub/server/integrations/learning/run-learning-command/index.test.ts b/hub/server/integrations/learning/run-learning-command/index.test.ts index 899b6fa6..8a4b2900 100644 --- a/hub/server/integrations/learning/run-learning-command/index.test.ts +++ b/hub/server/integrations/learning/run-learning-command/index.test.ts @@ -1,6 +1,7 @@ import { randomUUID } from "node:crypto" import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises" import { isAbsolute, relative, resolve, sep } from "node:path" +import { inspect } from "node:util" import { describe, expect, it, onTestFinished } from "vitest" import { runLearningCommand } from "." @@ -8,6 +9,36 @@ import { LearningCommandError } from "./errors" const fixtures = resolve("test/fixtures/learning") +async function runPasswordFailure(databaseUrl: string, password: string, encodedPassword: string) { + const directory = resolve(`server/integrations/learning/.process-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { force: true, recursive: true })) + const cliPath = resolve(directory, "fail.mjs") + await writeFile( + cliPath, + ` + const databaseUrl = process.env.REPLICA_LEARNING_DATABASE_URL + const password = ${JSON.stringify(password)} + const encodedPassword = ${JSON.stringify(encodedPassword)} + process.stdout.write(JSON.stringify({ + considered: 3, + receivedDatabaseUrl: Boolean(databaseUrl), + nested: { databaseUrl, password, [password]: encodedPassword }, + })) + process.stderr.write("error (learning_failed): Database failure: " + databaseUrl + " " + password + " " + encodedPassword) + process.exitCode = 1 + `, + ) + + const error: unknown = await runLearningCommand(["label", "--dir", resolve(directory, "store")], { + cliPath, + learningDatabaseUrl: databaseUrl, + environment: { PATH: process.env.PATH }, + }).catch((failure: unknown) => failure) + if (!(error instanceof LearningCommandError)) throw new Error("Expected a command failure.") + return error +} + describe("runLearningCommand()", () => { it("isolates the environment in a private temporary directory and removes it afterward", async () => { const result = (await runLearningCommand(["copilot", "status"], { @@ -337,6 +368,75 @@ describe("runLearningCommand()", () => { } }) + it("hides query parameter passwords in command errors and progress", async () => { + const password = "query@password" + const encodedPassword = "query%40password" + const databaseUrl = `postgres://learning-user@localhost/learning?password=${encodedPassword}` + + const error = await runPasswordFailure(databaseUrl, password, encodedPassword) + + expect(error).toMatchObject({ + code: "learning_failed", + result: { considered: 3, receivedDatabaseUrl: true }, + }) + const result = JSON.stringify(error.result) ?? "" + for (const secret of [databaseUrl, password, encodedPassword]) { + expect.soft(error.message).not.toContain(secret) + expect.soft(result).not.toContain(secret) + } + }) + + it("hides Unix-socket URL passwords in command errors and progress", async () => { + const password = "socket@password" + const encodedPassword = "socket%40password" + const databaseUrl = `postgresql://learning-user:${encodedPassword}@/learning?host=%2Fvar%2Frun%2Fpostgresql` + + const error = await runPasswordFailure(databaseUrl, password, encodedPassword) + + expect(error).toMatchObject({ + code: "learning_failed", + result: { considered: 3, receivedDatabaseUrl: true }, + }) + const result = JSON.stringify(error.result) ?? "" + for (const secret of [databaseUrl, password, encodedPassword]) { + expect.soft(error.message).not.toContain(secret) + expect.soft(result).not.toContain(secret) + } + }) + + it("does not expose malformed successful output through the error or its cause", async () => { + const directory = resolve(`server/integrations/learning/.process-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { force: true, recursive: true })) + const cliPath = resolve(directory, "malformed.mjs") + await writeFile( + cliPath, + ` + const databaseUrl = process.env.REPLICA_LEARNING_DATABASE_URL + process.stdout.write(new URL(databaseUrl).password) + `, + ) + const password = "parseSecret" + const databaseUrl = `postgres://learning-user:${password}@localhost/learning` + + const error: unknown = await runLearningCommand( + ["label", "--dir", resolve(directory, "store")], + { + cliPath, + learningDatabaseUrl: databaseUrl, + environment: { PATH: process.env.PATH }, + }, + ).catch((failure: unknown) => failure) + + expect(error).toBeInstanceOf(LearningCommandError) + if (!(error instanceof LearningCommandError)) throw new Error("Expected a command failure.") + expect(error.code).toBe("unreadable_output") + const diagnostic = inspect(error, { depth: null }) + for (const secret of [databaseUrl, password]) { + expect.soft(diagnostic).not.toContain(secret) + } + }) + it.each([ ["stdout", "outputLimit"], ["stderr", "errorLimit"], diff --git a/hub/server/integrations/learning/run-learning-command/index.ts b/hub/server/integrations/learning/run-learning-command/index.ts index 94d5ac3f..41f3a7b8 100644 --- a/hub/server/integrations/learning/run-learning-command/index.ts +++ b/hub/server/integrations/learning/run-learning-command/index.ts @@ -151,14 +151,26 @@ export async function runLearningCommand( const secrets = [learningDatabaseUrl, githubToken].filter((value): value is string => Boolean(value), ) + let hideDiagnostics = false if (learningDatabaseUrl) { try { - const password = new URL(learningDatabaseUrl).password - if (password) secrets.push(password, decodeURIComponent(password)) + let url: URL + try { + url = new URL(learningDatabaseUrl) + } catch { + url = new URL(learningDatabaseUrl.replace("@/", "@replica-placeholder/")) + } + if (!["postgres:", "postgresql:"].includes(url.protocol)) throw new Error() + if (url.password) secrets.push(url.password, decodeURIComponent(url.password)) + for (const part of url.search.slice(1).split("&")) { + const password = new URLSearchParams(part).get("password") + if (password) secrets.push(password, part.slice(part.indexOf("=") + 1)) + } } catch { - // The command reports an invalid URL without requiring it to be parsed here. + hideDiagnostics = true } } + secrets.sort((first, second) => second.length - first.length) function redact(value: string) { return secrets.reduce((text, secret) => text.replaceAll(secret, "[redacted]"), value) } @@ -293,6 +305,10 @@ export async function runLearningCommand( const stdout = Buffer.concat(output).toString("utf8") const stderr = redact(Buffer.concat(errors).toString("utf8").trim()) if (code !== 0) { + if (hideDiagnostics) { + reject(new LearningCommandError("learning_failed", "replica-learning failed.")) + return + } const match = errorPattern.exec(stderr) let result: unknown if (stdout.trim()) { @@ -315,12 +331,11 @@ export async function runLearningCommand( } try { resolve(JSON.parse(stdout)) - } catch (error) { + } catch { reject( new LearningCommandError( "unreadable_output", "replica-learning returned output Hub could not read.", - { cause: error }, ), ) } From 311bdbc49624c26c3694c89d6a1bd57cb92647c5 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 12:01:35 -0800 Subject: [PATCH 14/18] fix(hub): preserve learning stores during cutover Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 836fcecf-e7a9-4975-acd2-bf761098f711 --- hub/.devcontainer/compose.yaml | 6 +- hub/docs/development.md | 13 +- hub/docs/learning-foundation.md | 4 +- .../run-learning-command/index.test.ts | 171 ++++++++++++++++++ .../learning/run-learning-command/index.ts | 77 ++++++-- infrastructure/README.md | 2 +- packages/learning/src/config.mjs | 76 ++++++-- packages/learning/src/providers/sqlite.mjs | 42 ++++- .../learning/test-database/postgres.test.mjs | 118 +++++++++++- .../learning/test/scope-migration.test.mjs | 78 ++++++++ 10 files changed, 549 insertions(+), 38 deletions(-) diff --git a/hub/.devcontainer/compose.yaml b/hub/.devcontainer/compose.yaml index a448babd..a0a98bdc 100644 --- a/hub/.devcontainer/compose.yaml +++ b/hub/.devcontainer/compose.yaml @@ -8,12 +8,10 @@ services: working_dir: /workspaces/replica/hub volumes: - ../..:/workspaces/replica:cached + - postgres-socket:/var/run/postgresql:ro environment: DATABASE_URL: postgresql://replica:replica@db:5432/replica TEST_DATABASE_URL: postgresql://replica:replica@db:5432/postgres - REPLICA_LEARNING_DATABASE_URL: postgresql://replica_learning_runtime:replica-learning-dev@db:5432/replica - REPLICA_LEARNING_MIGRATION_DATABASE_URL: postgresql://replica:replica@db:5432/replica - REPLICA_LEARNING_RUNTIME_ROLE: replica_learning_runtime REPLICA_DEVCONTAINER: "true" depends_on: db: @@ -29,6 +27,7 @@ services: - "127.0.0.1:5432:5432" volumes: - postgres-data:/var/lib/postgresql + - postgres-socket:/var/run/postgresql - ./learning-role.sql:/docker-entrypoint-initdb.d/learning-role.sql:ro healthcheck: test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U replica -d replica"] @@ -38,3 +37,4 @@ services: volumes: postgres-data: + postgres-socket: diff --git a/hub/docs/development.md b/hub/docs/development.md index 4e6d01b7..1c5d50ce 100644 --- a/hub/docs/development.md +++ b/hub/docs/development.md @@ -16,7 +16,18 @@ The repository is mounted at `/workspaces/replica`, with `hub/` as the working d After the container opens and PostgreSQL is healthy, install the separate learning runtime with `npm ci --prefix ../packages/learning --engine-strict`, then run `npm run setup` before starting `npm run dev:api`. Run setup again after pulling new migrations. -New devcontainer databases create a separate local learning login. Setup migrates the learning schema and grants that login access. If the PostgreSQL volume predates this configuration and the login is absent, run `docker compose -f .devcontainer/compose.yaml exec db psql -U replica -d replica -f /docker-entrypoint-initdb.d/learning-role.sql` once from `hub/`, then run setup. The included password is for this local container only. +Learning uses SQLite by default, including after recreating an existing devcontainer. To use PostgreSQL instead, first stop Hub and all older clients and follow the [offline import and verification procedure](learning-foundation.md#private-storage) for every existing learning store. Keep SQLite selected if any history cannot be recovered or verified. + +New devcontainer databases create a separate local learning login. If the PostgreSQL volume predates this configuration, check whether `replica_learning_runtime` exists. If it is absent, run `docker compose -f .devcontainer/compose.yaml exec db psql -U replica -d replica -f /docker-entrypoint-initdb.d/learning-role.sql` once from `hub/` on the host. Do not overwrite or adopt an existing role without reviewing its ownership and permissions. The included password is for this local container only. + +Inside the devcontainer, initialize the learning schema and grant the local role access before importing: + +```sh +REPLICA_LEARNING_MIGRATION_DATABASE_URL='postgresql://replica:replica@localhost/replica?host=%2Fvar%2Frun%2Fpostgresql' \ +REPLICA_LEARNING_RUNTIME_ROLE=replica_learning_runtime npm run setup +``` + +For the offline import, provide `REPLICA_LEARNING_DATABASE_URL='postgresql://replica_learning_runtime:replica-learning-dev@localhost/replica?host=%2Fvar%2Frun%2Fpostgresql'` only to the import command. After verifying all imported stores, explicitly set that runtime URL in the Hub process environment or its private `.env` before starting Hub and its workers. Repeat the setup command above after pulling learning migrations. The URL uses a shared Unix socket, not the remote `db` TCP hostname; the learning provider allows local sockets without TLS. These development credentials and socket are not suitable for a hosted deployment. Do not restart older clients against the retained SQLite copies. ## Local Node.js diff --git a/hub/docs/learning-foundation.md b/hub/docs/learning-foundation.md index f8769e77..d289b400 100644 --- a/hub/docs/learning-foundation.md +++ b/hub/docs/learning-foundation.md @@ -26,7 +26,9 @@ Hub uses the persisted GitHub repository ID as the package scope, `github.com/re Set `REPLICA_LEARNING_DATABASE_URL` to select the package's PostgreSQL provider. Hub gives each command a private temporary config and does not create a repository store directory. Setup migrates the package schema with a separate privileged URL and grants the learning runtime login access only to that schema. See [PostgreSQL storage](../../packages/learning/README.md#postgresql-storage). -Before switching an existing installation, stop Hub and older clients, inventory every repository's existing store, and import each one offline using the package's `import-sqlite` command. Convert a non-SQLite store using `migrate-scope` first. Do not remove the old storage until every destination has been verified, and never restart older clients against the retained copies. If a local repository directory still contains files, Hub refuses to open the PostgreSQL scope until its import receipt exists. A directory that is no longer mounted cannot provide this check, so inventory and import it before removing the mount or activating PostgreSQL. +Hub preserves the built-in labeling and consolidation settings in an existing repository `config.json` while that directory remains mounted. For a new PostgreSQL store, an operator can instead place the same package configuration in `/repositories//postgres-config.json`. Keep it private and available to every Hub process. Hub selects PostgreSQL regardless of its `memory` setting. Do not keep both configuration files in one directory. Custom labeler or consolidator modules are not supported in this mode; Hub refuses them instead of silently changing the settings. Without either file, Hub uses its defaults and needs no repository configuration directory. + +Before switching an existing installation, stop Hub and older clients, inventory every repository's existing store, and import each one offline using the package's `import-sqlite` command. Convert a non-SQLite store using `migrate-scope` first. Do not remove the old storage until every destination has been verified, and never restart older clients against the retained copies. If a local repository directory contains anything other than `postgres-config.json`, Hub refuses to open the PostgreSQL scope until its import receipt exists. A directory that is no longer mounted cannot provide this check, so inventory and import it before removing the mount or activating PostgreSQL. Commands for an ID-backed store supply the former UUID-based scope as `--legacy-repository`. SQLite migrates existing records and their lifecycle to the numeric scope before opening them. Other existing providers require the [offline migration](../../packages/learning/README.md#rules). Hub review imports retain the original `repositories/` source separately from the numeric learning scope. This preserves existing evidence and snapshot identities. A repository without a GitHub ID cannot open its learning store for users, run learning, or prepare learning-backed decision-model data. Hub does not infer an ID from a name or expose its stored records. diff --git a/hub/server/integrations/learning/run-learning-command/index.test.ts b/hub/server/integrations/learning/run-learning-command/index.test.ts index 8a4b2900..a6302310 100644 --- a/hub/server/integrations/learning/run-learning-command/index.test.ts +++ b/hub/server/integrations/learning/run-learning-command/index.test.ts @@ -51,6 +51,8 @@ describe("runLearningCommand()", () => { LC_ALL: "C", PATH: process.env.PATH, REPLICA_LEARNING_DATABASE_URL: "ambient-database-url-must-not-leak", + REPLICA_LEARNING_HUB_POSTGRES: "ambient-postgres-must-not-leak", + REPLICA_LEARNING_HUB_REQUIRE_IMPORT: "ambient-import-must-not-leak", REPLICA_LEARNING_MIGRATION_DATABASE_URL: "migration-url-must-not-leak", REPLICA_LEARNING_ROOT: "/private/learning", REPLICA_LEARNING_SECRET: "must-not-leak", @@ -140,6 +142,7 @@ describe("runLearningCommand()", () => { TMPDIR: result.temporaryDirectory, COPILOT_GITHUB_TOKEN: "explicit-token", REPLICA_LEARNING_DATABASE_URL: databaseUrl, + REPLICA_LEARNING_HUB_POSTGRES: "1", }) expect(JSON.parse(result.config)).toMatchObject({ memory: { provider: "postgres" }, @@ -164,6 +167,174 @@ describe("runLearningCommand()", () => { await expect(stat(result.temporaryDirectory)).rejects.toMatchObject({ code: "ENOENT" }) }) + it("preserves an existing SQLite config when opening Postgres", async () => { + const directory = resolve(`server/integrations/learning/.process-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { force: true, recursive: true })) + const configPath = resolve(directory, "config.json") + const config = `${JSON.stringify( + { + schemaVersion: "replica.learning-config/v1", + memory: { provider: "sqlite" }, + consolidation: { options: { minPrototypes: 4, minReviewers: 3 } }, + labeling: { options: { model: "example-model", timeoutMs: 12000 } }, + }, + null, + 2, + )}\n` + await writeFile(configPath, config) + const databaseUrl = "postgres://learning-user:learning-password@localhost/learning" + const token = "explicit-token" + + const result = (await runLearningCommand( + ["consolidate", "--dir", directory, "--repository", "github.com/repositories/123"], + { + cliPath: resolve(fixtures, "report-runtime.mjs"), + learningDatabaseUrl: databaseUrl, + githubToken: token, + environment: { PATH: process.env.PATH }, + }, + )) as { + config: string + environment: NodeJS.ProcessEnv + temporaryDirectory: string + } + + expect(result.config).toBe(config) + expect(result.environment.REPLICA_LEARNING_HUB_POSTGRES).toBe("1") + expect(result.environment.REPLICA_LEARNING_HUB_REQUIRE_IMPORT).toBe("1") + expect(result.config).not.toContain(databaseUrl) + expect(result.config).not.toContain(token) + expect(await readFile(configPath, "utf8")).toBe(config) + await expect(stat(result.temporaryDirectory)).rejects.toMatchObject({ code: "ENOENT" }) + }) + + it("uses Postgres-only config for a fresh store without requiring import", async () => { + const directory = resolve(`server/integrations/learning/.process-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { force: true, recursive: true })) + const configPath = resolve(directory, "postgres-config.json") + const config = `${JSON.stringify( + { + schemaVersion: "replica.learning-config/v1", + consolidation: { options: { minPrototypes: 4 } }, + labeling: { options: { model: "example-model" } }, + }, + null, + 2, + )}\n` + await writeFile(configPath, config) + const databaseUrl = "postgres://learning-user:learning-password@localhost/learning" + const token = "explicit-token" + + const result = (await runLearningCommand( + ["consolidate", "--dir", directory, "--repository", "github.com/repositories/123"], + { + cliPath: resolve(fixtures, "report-runtime.mjs"), + learningDatabaseUrl: databaseUrl, + githubToken: token, + environment: { PATH: process.env.PATH }, + }, + )) as { + config: string + environment: NodeJS.ProcessEnv + temporaryDirectory: string + } + + expect(result.config).toBe(config) + expect(result.environment.REPLICA_LEARNING_HUB_POSTGRES).toBe("1") + expect(result.environment.REPLICA_LEARNING_HUB_REQUIRE_IMPORT).toBeUndefined() + expect(result.config).not.toContain(databaseUrl) + expect(result.config).not.toContain(token) + expect(await readFile(configPath, "utf8")).toBe(config) + await expect(stat(result.temporaryDirectory)).rejects.toMatchObject({ code: "ENOENT" }) + }) + + it("rejects a store with both SQLite and Postgres configs", async () => { + const directory = resolve(`server/integrations/learning/.process-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { force: true, recursive: true })) + const sqliteConfig = resolve(directory, "config.json") + const postgresConfig = resolve(directory, "postgres-config.json") + const marker = resolve(directory, "command.json") + await writeFile(sqliteConfig, '{"memory":{"provider":"sqlite"}}\n') + await writeFile(postgresConfig, '{"memory":{"provider":"postgres"}}\n') + + await expect( + runLearningCommand(["consolidate", "--dir", directory, "--fixture-fail-report", marker], { + cliPath: resolve(fixtures, "report-runtime.mjs"), + learningDatabaseUrl: "postgres://learning-user:learning-password@localhost/learning", + environment: { PATH: process.env.PATH }, + }), + ).rejects.toBeInstanceOf(LearningCommandError) + + await expect(stat(marker)).rejects.toMatchObject({ code: "ENOENT" }) + expect(await readFile(sqliteConfig, "utf8")).toBe('{"memory":{"provider":"sqlite"}}\n') + expect(await readFile(postgresConfig, "utf8")).toBe('{"memory":{"provider":"postgres"}}\n') + }) + + it("uses the preserved built-in config in the real learning command", async () => { + const directory = resolve(`server/integrations/learning/.process-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { force: true, recursive: true })) + const configPath = resolve(directory, "config.json") + const config = JSON.stringify({ + schemaVersion: "replica.learning-config/v1", + memory: { provider: "sqlite" }, + consolidation: { consolidator: "none" }, + labeling: { options: { model: "example-model" } }, + }) + await writeFile(configPath, config) + + const error: unknown = await runLearningCommand( + ["doctor", "--dir", directory, "--repository", "github.com/repositories/123"], + { + cliPath: resolve("../packages/learning/bin/replica-learning.mjs"), + learningDatabaseUrl: + "postgres://learning-user:learning-password@postgres.example.invalid/learning", + environment: { PATH: process.env.PATH }, + }, + ).catch((failure: unknown) => failure) + + expect(error).toBeInstanceOf(LearningCommandError) + if (!(error instanceof LearningCommandError)) throw new Error("Expected a command failure.") + expect(error.code).toBe("learning_failed") + const result = error.result as { provider: { error: string }; consolidator: { source: string } } + expect(result.provider.error).toContain("sslmode=verify-full") + expect(result.consolidator.source).toBe("built-in none") + expect(await readFile(configPath, "utf8")).toBe(config) + }) + + it("clearly rejects custom learning modules in the real command", async () => { + const directory = resolve(`server/integrations/learning/.process-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { force: true, recursive: true })) + const configPath = resolve(directory, "postgres-config.json") + + for (const selection of [ + { consolidation: { consolidator: { module: "./custom.mjs" } } }, + { labeling: { labeler: { module: "./custom.mjs" } } }, + ]) { + await writeFile( + configPath, + JSON.stringify({ schemaVersion: "replica.learning-config/v1", ...selection }), + ) + const error: unknown = await runLearningCommand( + ["doctor", "--dir", directory, "--repository", "github.com/repositories/123"], + { + cliPath: resolve("../packages/learning/bin/replica-learning.mjs"), + learningDatabaseUrl: "postgres://learning-user:learning-password@localhost/learning", + environment: { PATH: process.env.PATH }, + }, + ).catch((failure: unknown) => failure) + + expect(error).toBeInstanceOf(LearningCommandError) + if (!(error instanceof LearningCommandError)) throw new Error("Expected a command failure.") + expect(error.code).toBe("unsupported") + expect(error.message).toMatch(/built-in.*only/) + } + }) + it("requires import when the original store directory is nonempty", async () => { const directory = resolve(`server/integrations/learning/.process-test-${randomUUID()}`) await mkdir(directory) diff --git a/hub/server/integrations/learning/run-learning-command/index.ts b/hub/server/integrations/learning/run-learning-command/index.ts index 41f3a7b8..dc32b4d9 100644 --- a/hub/server/integrations/learning/run-learning-command/index.ts +++ b/hub/server/integrations/learning/run-learning-command/index.ts @@ -1,4 +1,5 @@ -import { chmod, mkdtemp, readdir, rm, stat, writeFile } from "node:fs/promises" +import { constants } from "node:fs" +import { chmod, mkdtemp, open, readdir, rm, stat, writeFile } from "node:fs/promises" import { tmpdir } from "node:os" import { join } from "node:path" import { spawn } from "node:child_process" @@ -10,6 +11,8 @@ const childVariables = [ ...passedVariables, "COPILOT_GITHUB_TOKEN", "REPLICA_LEARNING_DATABASE_URL", + "REPLICA_LEARNING_HUB_POSTGRES", + "REPLICA_LEARNING_HUB_REQUIRE_IMPORT", "TMPDIR", ] const bootstrap = ` @@ -30,6 +33,7 @@ function commandEnvironment( temporaryDirectory: string, githubToken?: string, learningDatabaseUrl?: string, + requireImport = false, ) { const environment: NodeJS.ProcessEnv = { TMPDIR: temporaryDirectory } for (const [name, value] of Object.entries(source)) { @@ -38,7 +42,11 @@ function commandEnvironment( } } if (githubToken) environment.COPILOT_GITHUB_TOKEN = githubToken - if (learningDatabaseUrl) environment.REPLICA_LEARNING_DATABASE_URL = learningDatabaseUrl + if (learningDatabaseUrl) { + environment.REPLICA_LEARNING_DATABASE_URL = learningDatabaseUrl + environment.REPLICA_LEARNING_HUB_POSTGRES = "1" + if (requireImport) environment.REPLICA_LEARNING_HUB_REQUIRE_IMPORT = "1" + } return environment } @@ -108,18 +116,51 @@ export async function runLearningCommand( try { const commandArguments = [...arguments_] let hasDirectory = false + let requireImport = false if (learningDatabaseUrl) { - let requireImport = false + let existingConfig: Buffer | undefined async function preserveExistingStore(directory: string) { + let entries: string[] try { - if ((await readdir(directory)).length) requireImport = true + entries = await readdir(directory) } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error + if ((error as NodeJS.ErrnoException).code === "ENOENT") return + throw error + } + if (entries.some((name) => name !== "postgres-config.json")) requireImport = true + if (entries.includes("config.json") && entries.includes("postgres-config.json")) + throw new LearningCommandError( + "invalid_request", + "Keep only one learning configuration for this repository.", + ) + const name = entries.includes("postgres-config.json") + ? "postgres-config.json" + : entries.includes("config.json") + ? "config.json" + : undefined + if (name) { + const handle = await open( + join(directory, name), + constants.O_RDONLY | constants.O_NOFOLLOW, + ) + try { + const info = await handle.stat() + if (!info.isFile() || info.nlink !== 1) + throw new LearningCommandError( + "invalid_request", + "Learning configuration is invalid.", + ) + existingConfig = await handle.readFile() + } finally { + await handle.close() + } } } for (let index = 0; index < commandArguments.length; index += 1) { const argument = commandArguments[index] if (argument === "--dir") { + if (hasDirectory) + throw new LearningCommandError("invalid_request", "Give one learning directory.") const directory = commandArguments[index + 1] if (!directory || directory.startsWith("--")) throw new LearningCommandError("invalid_request", "The learning directory is missing.") @@ -127,6 +168,8 @@ export async function runLearningCommand( commandArguments[++index] = temporaryDirectory hasDirectory = true } else if (argument?.startsWith("--dir=")) { + if (hasDirectory) + throw new LearningCommandError("invalid_request", "Give one learning directory.") await preserveExistingStore(argument.slice("--dir=".length)) commandArguments[index] = `--dir=${temporaryDirectory}` hasDirectory = true @@ -135,15 +178,22 @@ export async function runLearningCommand( if (hasDirectory) { await writeFile( join(temporaryDirectory, "config.json"), - JSON.stringify({ - schemaVersion: "replica.learning-config/v1", - memory: { provider: "postgres", ...(requireImport ? { requireImport: true } : {}) }, - consolidation: { - options: { - signals: ["visual_quality", "accessibility", "usability", "content", "interaction"], + existingConfig ?? + JSON.stringify({ + schemaVersion: "replica.learning-config/v1", + memory: { provider: "postgres", ...(requireImport ? { requireImport: true } : {}) }, + consolidation: { + options: { + signals: [ + "visual_quality", + "accessibility", + "usability", + "content", + "interaction", + ], + }, }, - }, - }), + }), { mode: 0o600, flag: "wx" }, ) } @@ -195,6 +245,7 @@ export async function runLearningCommand( temporaryDirectory, githubToken, hasDirectory ? learningDatabaseUrl : undefined, + requireImport, ), stdio: ["ignore", "pipe", "pipe"], }, diff --git a/infrastructure/README.md b/infrastructure/README.md index 6d2ae0d9..e119bd8b 100644 --- a/infrastructure/README.md +++ b/infrastructure/README.md @@ -525,7 +525,7 @@ node infrastructure/azure/deploy-hub/index.ts bootstrap \ Bootstrap creates infrastructure and the manual setup job with `deploy_hub=false`. No combined app exists yet. Review the configuration and a read-only Terraform plan before authorizing this command: the script applies saved plans without an interactive prompt after checking for deletes/replacements. Command output is kept private because tool diagnostics can contain credentials. Bootstrap refuses any nonempty state so it cannot race a release on an existing installation. If initial provisioning failed partway, inspect the partial state and recover from a separately reviewed plan with `deploy_hub=false`; never use this recovery path after an app has been created. -Before the first release, use an authorized private-network host with Hub's dependencies installed to run `node server/scripts/provision-database-access/index.ts` from `hub/`. Inject the administrator `DATABASE_URL`, `HUB_MIGRATION_PASSWORD`, and `HUB_RUNTIME_PASSWORD` directly from the secret manager without shell tracing or command-line values. Use the same two passwords stored in the workload URL secrets. This first-installation script creates the roles and schemas transactionally and rejects existing roles, public tables, or a pre-existing BullMQ schema; it is not an upgrade or password-rotation command. Remove these environment variables afterward. Do not inject administrator credentials into the setup job. Existing installations require a reviewed ownership/credential migration while Hub is stopped, not rerunning this fresh-database script. +Before the first release, use an authorized private-network host with Hub's dependencies installed to run `node server/scripts/provision-database-access/index.ts` from `hub/`. Inject the administrator `DATABASE_URL`, `HUB_MIGRATION_PASSWORD`, `HUB_RUNTIME_PASSWORD`, and `HUB_LEARNING_PASSWORD` directly from the secret manager without shell tracing or command-line values. Use distinct passwords matching the workload URL secrets. This first-installation script creates the roles and schemas transactionally and rejects existing roles, public tables, or a pre-existing BullMQ schema; it is not an upgrade or password-rotation command. Remove these environment variables afterward. Do not inject administrator credentials into the setup job. Existing installations require a reviewed ownership/credential migration while Hub is stopped, not rerunning this fresh-database script. Use the same release command for the first installation, subsequent image releases, and infrastructure or secret changes: diff --git a/packages/learning/src/config.mjs b/packages/learning/src/config.mjs index 23961caa..1b4fecb3 100644 --- a/packages/learning/src/config.mjs +++ b/packages/learning/src/config.mjs @@ -1,7 +1,19 @@ import { execFile } from "node:child_process" -import { randomBytes } from "node:crypto" -import { constants } from "node:fs" -import { lstat, mkdir, open, realpath, rename, stat, unlink } from "node:fs/promises" +import { createHash, randomBytes } from "node:crypto" +import { constants, createReadStream } from "node:fs" +import { + chmod, + lstat, + mkdir, + mkdtemp, + open, + realpath, + rename, + rm, + stat, + unlink, +} from "node:fs/promises" +import { tmpdir } from "node:os" import path from "node:path" import { pathToFileURL } from "node:url" import { promisify } from "node:util" @@ -15,7 +27,7 @@ import { createInMemoryProvider } from "./providers/in-memory.mjs" import { createJsonLinesMemoryProvider } from "./providers/json-lines.mjs" import { createFileLock } from "./providers/lock.mjs" import { createPostgresMemoryProvider } from "./providers/postgres.mjs" -import { createSqliteMemoryProvider } from "./providers/sqlite.mjs" +import { backupSqliteMemoryStore, createSqliteMemoryProvider } from "./providers/sqlite.mjs" import { migrateRepositoryScope } from "./scope-migration.mjs" import { createLearningStore, scopeProblem } from "./store.mjs" @@ -154,6 +166,26 @@ async function resolveHostedEnvironment({ const dataDirectory = await realLocation(path.resolve(cwd, directory)) const configPath = path.join(dataDirectory, "config.json") const config = await readConfig(configPath) + let selectedConfig = config ?? {} + if (env.REPLICA_LEARNING_HUB_POSTGRES === "1") { + if (!env.REPLICA_LEARNING_DATABASE_URL) + throw new LearningError("invalid_input", "The Hub learning database URL is missing.") + if ( + typeof config?.consolidation?.consolidator === "object" || + typeof config?.labeling?.labeler === "object" + ) + throw new LearningError( + "unsupported", + "Hub PostgreSQL learning supports built-in consolidators and labelers only.", + ) + selectedConfig = { + ...selectedConfig, + memory: { + provider: "postgres", + ...(env.REPLICA_LEARNING_HUB_REQUIRE_IMPORT === "1" ? { requireImport: true } : {}), + }, + } + } const checkout = await checkoutAround(dataDirectory) const placement = checkout ? placeIn(checkout, dataDirectory) : null return { @@ -164,7 +196,7 @@ async function resolveHostedEnvironment({ dataDirectory, configPath, configFound: config !== null, - config: config ?? {}, + config: selectedConfig, env: { REPLICA_LEARNING_DATABASE_URL: env.REPLICA_LEARNING_DATABASE_URL }, scope, legacyScope, @@ -566,9 +598,8 @@ export async function openLegacyRedactionStore(environment, { clock = Date.now } ) const migration = await provider.scopeMigrationFrom?.(environment.scope) if ( - (!migration && typeof provider.hasSqliteImport === "function") || - (environment.config.memory?.requireImport && - (!migration || !(await provider.hasSqliteImport?.(migration.newScope)))) + environment.config.memory?.requireImport && + (!migration || !(await provider.hasSqliteImport?.(migration.newScope))) ) throw new LearningError( "conflict", @@ -649,10 +680,22 @@ export async function importSqliteStore(environment, { clock = Date.now } = {}) "invalid_input", "Import needs an existing Hub SQLite store, its numeric repository ID, and its old Hub scope.", ) + if (choice?.builtin === "sqlite" && typeof choice.file !== "string") + throw new LearningError("invalid_input", "A migrated SQLite provider needs its file name.") const destination = createPostgresMemoryProvider({ connectionString: environment.env.REPLICA_LEARNING_DATABASE_URL, }) + const temporaryDirectory = await mkdtemp(path.join(tmpdir(), "replica-learning-import-")) + const file = choice === "sqlite" ? "learning.sqlite" : choice.file + const sourceOptions = { directory: environment.dataDirectory, file } + const snapshotPath = path.join(temporaryDirectory, file) + const copyEnvironment = { ...environment, dataDirectory: temporaryDirectory } let source + async function fileDigest(filePath) { + const hash = createHash("sha256") + for await (const chunk of createReadStream(filePath)) hash.update(chunk) + return hash.digest("hex") + } async function snapshot() { const scopes = await source.storedScopes() if (scopes.some((scope) => canonicalJson(scope) !== canonicalJson(environment.scope))) @@ -675,7 +718,10 @@ export async function importSqliteStore(environment, { clock = Date.now } = {}) } try { await destination.hasSqliteImport(environment.scope) - const { store } = await openLearningStore(environment, { clock }) + await backupSqliteMemoryStore(sourceOptions, snapshotPath) + await chmod(snapshotPath, 0o600) + const originalDigest = await fileDigest(snapshotPath) + const { store } = await openLearningStore(copyEnvironment, { clock }) try { const verified = await store.verify({ scope: environment.scope, @@ -689,7 +735,7 @@ export async function importSqliteStore(environment, { clock = Date.now } = {}) } finally { await store.close() } - source = (await openProvider(environment)).provider + source = (await openProvider(copyEnvironment)).provider const original = await snapshot() if ( !original.migrations.some( @@ -705,7 +751,11 @@ export async function importSqliteStore(environment, { clock = Date.now } = {}) ...original, sourceDigest: digestOf(original), beforeCommit: async () => { + const checkDirectory = await mkdtemp(path.join(temporaryDirectory, "recheck-")) + const checkPath = path.join(checkDirectory, "source.sqlite") + await backupSqliteMemoryStore(sourceOptions, checkPath) if ( + (await fileDigest(checkPath)) !== originalDigest || canonicalJson(await snapshot()) !== canonicalJson(original) || canonicalJson(await readConfig(environment.configPath)) !== canonicalJson(environment.config) @@ -720,7 +770,11 @@ export async function importSqliteStore(environment, { clock = Date.now } = {}) try { await source?.close() } finally { - await destination.close() + try { + await destination.close() + } finally { + await rm(temporaryDirectory, { recursive: true, force: true }) + } } } } diff --git a/packages/learning/src/providers/sqlite.mjs b/packages/learning/src/providers/sqlite.mjs index 939892b3..344c58da 100644 --- a/packages/learning/src/providers/sqlite.mjs +++ b/packages/learning/src/providers/sqlite.mjs @@ -9,7 +9,7 @@ import { statSync, } from "node:fs" import path from "node:path" -import { DatabaseSync } from "node:sqlite" +import { backup, DatabaseSync } from "node:sqlite" import { canonicalJson, digestOf } from "../canonical-json.mjs" import { LearningError, ProviderConflictError } from "../errors.mjs" import { @@ -58,6 +58,46 @@ const SCHEMA = ` create index if not exists memory_versions_by_scope on memory_versions (scope_key, seq); ` +/** Copy a stopped store without creating or migrating its source. */ +export async function backupSqliteMemoryStore( + { directory, file = "learning.sqlite" }, + destination, +) { + if (typeof file !== "string" || path.basename(file) !== file || file.startsWith(".")) + throw new LearningError("invalid_input", "file must be a plain file name in the directory.") + const root = path.resolve(directory) + const target = path.join(root, file) + assertPrivate(root) + for (const name of [file, `${file}-wal`, `${file}-shm`, `${file}-journal`]) { + const candidate = path.join(root, name) + const info = lstatSync(candidate, { throwIfNoEntry: false }) + if (info) assertOwnPath(root, candidate, info) + } + let descriptor + try { + descriptor = openSync(target, constants.O_RDONLY | NO_FOLLOW) + } catch (error) { + if (error.code === "ENOENT") + throw new LearningError("not_found", "The selected SQLite learning database is missing.") + throw openError(root, target, error) + } + try { + const checked = fstatSync(descriptor) + assertPrivate(target) + assertSameFile(root, target, checked) + const db = new DatabaseSync(target, { readOnly: true }) + try { + assertSameFile(root, target, checked) + await backup(db, destination) + assertSameFile(root, target, checked) + } finally { + db.close() + } + } finally { + closeSync(descriptor) + } +} + /** * Stores learning records in one SQLite file with the driver built into Node.js 24, so it * needs no service and no dependency. It is the default provider. diff --git a/packages/learning/test-database/postgres.test.mjs b/packages/learning/test-database/postgres.test.mjs index 717fa73f..db03d305 100644 --- a/packages/learning/test-database/postgres.test.mjs +++ b/packages/learning/test-database/postgres.test.mjs @@ -4,6 +4,7 @@ import { randomBytes } from "node:crypto" import { chmodSync, copyFileSync, + existsSync, mkdirSync, readFileSync, readdirSync, @@ -138,6 +139,46 @@ memoryProviderConformance({ createProvider: async () => provider(await database()), }) +it("returns no removals for an unmapped new PostgreSQL repository", async () => { + const root = path.resolve(`.learning-hub-tests-${randomBytes(12).toString("hex")}`) + mkdirSync(root, { mode: 0o700 }) + workspaces.push(root) + execFileSync("git", ["init", "-q", root]) + writeFileSync(path.join(root, ".gitignore"), ".replica/\n") + const directory = path.join(root, ".replica", "learning") + mkdirSync(directory, { recursive: true, mode: 0o700 }) + writeFileSync( + path.join(directory, "config.json"), + JSON.stringify({ + schemaVersion: "replica.learning-config/v1", + memory: { provider: "postgres" }, + }), + ) + const url = await database() + const oldScope = { + host: "github.com", + repository: "repositories/11111111-2222-4333-8444-555555555555", + } + const target = provider(url) + assert.equal(await target.scopeMigrationFrom(oldScope), null) + const result = await learningCommand(root, url, [ + "redact", + "--comment", + "103", + "--by", + "github:ana-designer", + "--dir", + directory, + "--legacy-repository", + `github.com/${oldScope.repository}`, + "--legacy-redaction", + "--json", + ]) + assert.equal(result.code, 0, result.stderr) + assert.equal(JSON.parse(result.stdout).removed, 0) + assert.equal(await target.scopeMigrationFrom(oldScope), null) +}) + it("redacts a new PostgreSQL repository using its old Hub UUID", async () => { const root = path.resolve(`.learning-hub-tests-${randomBytes(12).toString("hex")}`) mkdirSync(root, { mode: 0o700 }) @@ -298,6 +339,10 @@ it("imports Hub history offline, preserves mappings and redactions, and refuses try { const original = await snapshot(sourceProvider, oldScope) assert.ok(original.records.events.some((event) => event.redaction && !event.payload)) + assert.deepEqual(await sourceProvider.storedScopes(), [oldScope]) + const originalNumeric = await snapshot(sourceProvider, scope) + assert.equal(await sourceProvider.scopeMigrationFrom(oldScope), null) + assert.deepEqual(await sourceProvider.scopeMigrations(scope), []) assert.deepEqual( original.versions.map((version) => version.state), ["proposed", "accepted"], @@ -322,20 +367,19 @@ it("imports Hub history offline, preserves mappings and redactions, and refuses assert.equal(imported.code, 0, imported.stderr) assert.deepEqual(await snapshot(target, scope), expectedHistory) assert.deepEqual(await target.scopeMigrationFrom(oldScope), expectedMapping) - const oldSource = await snapshot(sourceProvider, oldScope) - const newSource = await snapshot(sourceProvider, scope) - if (newSource.records.events.length) assert.deepEqual(newSource, expectedHistory) - else assert.deepEqual(oldSource, original) + assert.equal(digestOf(await snapshot(sourceProvider, oldScope)), digestOf(original)) + assert.equal(digestOf(await snapshot(sourceProvider, scope)), digestOf(originalNumeric)) + assert.equal(await sourceProvider.scopeMigrationFrom(oldScope), null) + assert.deepEqual(await sourceProvider.scopeMigrations(scope), []) const retry = await learningCommand(root, url, ["import-sqlite", "--offline", ...flags]) assert.equal(retry.code, 0, retry.stderr) assert.deepEqual(await snapshot(target, scope), expectedHistory) assert.deepEqual(await target.scopeMigrationFrom(oldScope), expectedMapping) - const sourceScope = newSource.records.events.length ? scope : oldScope const store = await createLearningStore({ provider: sourceProvider }) await store.addGrant( - { scope: sourceScope, principal: { kind: "human", id: "github:later" } }, + { scope: oldScope, principal: { kind: "human", id: "github:later" } }, { purposes: ["review"], sources: ["hub_review_comments"], @@ -401,6 +445,46 @@ it("imports Hub history offline, preserves mappings and redactions, and refuses } }) +it("refuses an import when the selected SQLite file is missing", async () => { + const { root } = importWorkspace() + const url = await database() + const source = path.join(root, ".replica", "empty") + mkdirSync(source, { mode: 0o700 }) + const selected = path.join(source, "selected.sqlite") + writeFileSync( + path.join(source, "config.json"), + JSON.stringify({ + schemaVersion: "replica.learning-config/v1", + memory: { provider: { builtin: "sqlite", file: "selected.sqlite" } }, + }), + ) + const result = await learningCommand(root, url, [ + "import-sqlite", + "--offline", + "--dir", + source, + "--repository", + "github.com/repositories/123456", + "--legacy-repository", + "github.com/repositories/11111111-2222-4333-8444-555555555555", + ]) + const db = new pg.Client({ connectionString: url }) + await db.connect() + try { + assert.notEqual(result.code, 0) + assert.equal(existsSync(selected), false) + assert.deepEqual(readdirSync(source), ["config.json"]) + for (const table of ["records", "memory_versions", "scope_migrations", "sqlite_imports"]) { + const { rows } = await db.query( + `select count(*)::int as count from replica_learning.${table}`, + ) + assert.equal(rows[0].count, 0, table) + } + } finally { + await db.end() + } +}) + it("refuses a duplicate audited grant under a different SQLite record ID", async () => { const { root, source } = importWorkspace() const oldScope = { @@ -947,8 +1031,20 @@ it("rolls back a failed PostgreSQL import and permits a retry", async () => { const { root, source } = importWorkspace() const url = await database() const db = new pg.Client({ connectionString: url }) + const oldScope = { + host: "github.com", + repository: "repositories/11111111-2222-4333-8444-555555555555", + } + const scope = { host: "github.com", repository: "repositories/123456" } + const sourceProvider = createSqliteMemoryProvider({ directory: source }) await db.connect() try { + const original = await snapshot(sourceProvider, oldScope) + assert.ok(original.records.events.length > 0) + assert.deepEqual(await sourceProvider.storedScopes(), [oldScope]) + const originalNumeric = await snapshot(sourceProvider, scope) + assert.equal(await sourceProvider.scopeMigrationFrom(oldScope), null) + assert.deepEqual(await sourceProvider.scopeMigrations(scope), []) await db.query("create sequence replica_learning.test_import_attempt") await db.query(` create function replica_learning.test_refuse_events() returns trigger language plpgsql as $$ @@ -981,14 +1077,22 @@ it("rolls back a failed PostgreSQL import and permits a retry", async () => { ) assert.equal(records.rows[0].count, 0) assert.equal(versions.rows[0].count, 0) + const receipts = await db.query( + "select count(*)::int as count from replica_learning.sqlite_imports", + ) + assert.equal(receipts.rows[0].count, 0) + assert.equal(digestOf(await snapshot(sourceProvider, oldScope)), digestOf(original)) + assert.equal(digestOf(await snapshot(sourceProvider, scope)), digestOf(originalNumeric)) + assert.equal(await sourceProvider.scopeMigrationFrom(oldScope), null) + assert.deepEqual(await sourceProvider.scopeMigrations(scope), []) await db.query("drop trigger test_refuse_events on replica_learning.records") const retried = await learningCommand(root, url, args) assert.equal(retried.code, 0, retried.stderr) const target = provider(url) - const scope = { host: "github.com", repository: "repositories/123456" } assert.ok((await target.readRecords("events", { scope })).length > 0) assert.equal((await target.readMemoryVersions({ scope })).length, 2) } finally { + await sourceProvider.close() await db.end() } }) diff --git a/packages/learning/test/scope-migration.test.mjs b/packages/learning/test/scope-migration.test.mjs index 6518ed86..fbf43255 100644 --- a/packages/learning/test/scope-migration.test.mjs +++ b/packages/learning/test/scope-migration.test.mjs @@ -23,6 +23,7 @@ import { weekTwoLog, } from "../conformance/fixtures.mjs" import { createRecurrenceConsolidator } from "../src/consolidators/recurrence.mjs" +import { openLegacyRedactionStore } from "../src/config.mjs" import { labelComments } from "../src/labeling.mjs" import { STREAMS } from "../src/provider-contract.mjs" import { createInMemoryProvider } from "../src/providers/in-memory.mjs" @@ -1428,6 +1429,83 @@ it("redacts a Hub UUID store before and after its migration without touching ano } }) +it("completes legacy redaction when a database has no store or mapping", async () => { + const repo = checkout("empty-database-legacy-redaction") + const providerPath = path.join(repo, "tools", "database-provider.mjs") + const inMemoryUrl = pathToFileURL(path.join(here, "../src/providers/in-memory.mjs")).href + writeFileSync( + providerPath, + `import { createInMemoryProvider } from ${JSON.stringify(inMemoryUrl)} +export function createMemoryProvider() { + return { + ...createInMemoryProvider(), + scopeMigrationFrom: async () => null, + hasSqliteImport: async () => false, + } +} +`, + ) + const legacyScope = { host: "github.com", repository: `repositories/${hubId}` } + const environment = { + hosted: true, + legacyRedaction: true, + root: repo, + dataDirectory: path.join(repo, ".replica", "learning"), + scope: legacyScope, + config: { memory: { provider: { module: "./tools/database-provider.mjs" } } }, + } + + const { store } = await openLegacyRedactionStore(environment) + try { + const result = await store.redactHubComment( + { scope: legacyScope, principal: { kind: "human", id: "github:ana-designer" } }, + 101, + ) + assert.deepEqual(result.redacted, []) + assert.equal(existsSync(environment.dataDirectory), false) + } finally { + await store.close() + } +}) + +it("keeps legacy redaction pending when existing SQLite history is not imported", async () => { + const repo = checkout("unimported-database-legacy-redaction") + installLegacyStore(repo, "legacy-hub-scope.sqlite") + const providerPath = path.join(repo, "tools", "database-provider.mjs") + const inMemoryUrl = pathToFileURL(path.join(here, "../src/providers/in-memory.mjs")).href + writeFileSync( + providerPath, + `import { createInMemoryProvider } from ${JSON.stringify(inMemoryUrl)} +export function createMemoryProvider({ migration } = {}) { + return { + ...createInMemoryProvider(), + scopeMigrationFrom: async () => migration ?? null, + hasSqliteImport: async () => false, + } +} +`, + ) + const directory = path.join(repo, ".replica", "learning") + const original = readFileSync(path.join(directory, "learning.sqlite")) + const legacyScope = { host: "github.com", repository: `repositories/${hubId}` } + const environment = { + hosted: true, + legacyRedaction: true, + root: repo, + dataDirectory: directory, + scope: legacyScope, + config: { + memory: { provider: { module: "./tools/database-provider.mjs" }, requireImport: true }, + }, + } + await assert.rejects(openLegacyRedactionStore(environment), { code: "conflict" }) + environment.config.memory.provider.options = { + migration: { oldScope: legacyScope, newScope: scope }, + } + await assert.rejects(openLegacyRedactionStore(environment), { code: "conflict" }) + assert.deepEqual(readFileSync(path.join(directory, "learning.sqlite")), original) +}) + async function checkMigratedHistory(kind) { const repo = checkout(`migration-${kind}`) const hosted = kind === "hosted" From 729004df3d5f382d32a8b6120e4400ad4db169df Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 16:52:30 -0800 Subject: [PATCH 15/18] fix(hub): fence learning snapshot checkpoints Write PostgreSQL checkpoints on the advisory-lock connection and migrate them after the existing Hub schema. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 50605b0b-6b69-4743-b6d9-6918b6c9878a --- hub/docs/database.md | 2 + hub/docs/learning-foundation.md | 4 +- hub/schema/decision-review-snapshot.prisma | 19 + .../migration.sql | 18 + hub/schema/repository.prisma | 1 + .../index.db.test.ts | 588 ++++++++++++++++++ .../index.test.ts | 3 + .../index.ts | 108 +++- .../with-learning-execution-lock/index.ts | 2 + .../get-decision-review-snapshot/index.ts | 11 + .../index.db.test.ts | 46 ++ .../save-decision-review-snapshot/index.ts | 41 ++ .../index.db.test.ts | 195 ++++++ 13 files changed, 1010 insertions(+), 28 deletions(-) create mode 100644 hub/schema/decision-review-snapshot.prisma create mode 100644 hub/schema/migrations/20261220160000_add_decision_review_snapshot/migration.sql create mode 100644 hub/server/domains/decision-model/create-hub-decision-taskset-source/index.db.test.ts create mode 100644 hub/server/repositories/decision-review-snapshots/get-decision-review-snapshot/index.ts create mode 100644 hub/server/repositories/decision-review-snapshots/save-decision-review-snapshot/index.db.test.ts create mode 100644 hub/server/repositories/decision-review-snapshots/save-decision-review-snapshot/index.ts create mode 100644 hub/test/database/decision-review-snapshot-migration/index.db.test.ts diff --git a/hub/docs/database.md b/hub/docs/database.md index 324ecbe0..2de6b11d 100644 --- a/hub/docs/database.md +++ b/hub/docs/database.md @@ -92,6 +92,8 @@ Review threads bind one non-removed repository, one reviewable prototype, and on Decision-model tables store repository settings, pinned input digests, runtime job and candidate references, promotion generations, Build evaluation references, and decimal usage or cost metadata. They do not store credentials, screenshots, tasksets, adapters, evaluation reports, or model weights. Database checks enforce training bounds, positive promotion generations, nonnegative usage and cost, and complete quantity/unit and amount/currency pairs. +For PostgreSQL learning stores, the latest decision-review snapshot keeps its content digest, snapshot ID, and capture time per repository. It contains no review text and is removed with its repository. SQLite keeps this checkpoint in its existing store directory; see [learning storage](learning-foundation.md). + Candidate rows also store the runtime's held-out baseline and candidate metrics, per-learning metric changes, and an optional administrator rejection. Rejection fields must be absent together or include a time and reason. Build evaluation rows keep typed page-level findings in their bounded summary rather than copying screenshot bytes. Runtime copy rows keep content-free provider references and provenance selectors. Runtime deletion rows keep selectors, pending and failure counts, safe receipt metadata, and completion times. They never store evidence bodies, screenshots, labels, prompts, adapters, or model artifacts. diff --git a/hub/docs/learning-foundation.md b/hub/docs/learning-foundation.md index d289b400..494efe3d 100644 --- a/hub/docs/learning-foundation.md +++ b/hub/docs/learning-foundation.md @@ -28,13 +28,13 @@ Set `REPLICA_LEARNING_DATABASE_URL` to select the package's PostgreSQL provider. Hub preserves the built-in labeling and consolidation settings in an existing repository `config.json` while that directory remains mounted. For a new PostgreSQL store, an operator can instead place the same package configuration in `/repositories//postgres-config.json`. Keep it private and available to every Hub process. Hub selects PostgreSQL regardless of its `memory` setting. Do not keep both configuration files in one directory. Custom labeler or consolidator modules are not supported in this mode; Hub refuses them instead of silently changing the settings. Without either file, Hub uses its defaults and needs no repository configuration directory. -Before switching an existing installation, stop Hub and older clients, inventory every repository's existing store, and import each one offline using the package's `import-sqlite` command. Convert a non-SQLite store using `migrate-scope` first. Do not remove the old storage until every destination has been verified, and never restart older clients against the retained copies. If a local repository directory contains anything other than `postgres-config.json`, Hub refuses to open the PostgreSQL scope until its import receipt exists. A directory that is no longer mounted cannot provide this check, so inventory and import it before removing the mount or activating PostgreSQL. +Before switching an existing installation, stop Hub and older clients, inventory every repository's existing store, and import each one offline using the package's `import-sqlite` command. Convert a non-SQLite store using `migrate-scope` first. Keep each old directory mounted for its first decision-model preflight after the switch, so Hub can migrate its retry-stable review snapshot metadata into the Hub database. Do not remove the old storage until every destination has been verified, and never restart older clients against the retained copies. Mixed SQLite and PostgreSQL writers are not supported. New PostgreSQL writes are not copied back to SQLite, so rolling back to the old store requires a separate, verified migration. If a local repository directory contains anything other than `postgres-config.json`, Hub refuses to open the PostgreSQL scope until its import receipt exists. A directory that is no longer mounted cannot provide this check, so inventory and import it before removing the mount or activating PostgreSQL. Commands for an ID-backed store supply the former UUID-based scope as `--legacy-repository`. SQLite migrates existing records and their lifecycle to the numeric scope before opening them. Other existing providers require the [offline migration](../../packages/learning/README.md#rules). Hub review imports retain the original `repositories/` source separately from the numeric learning scope. This preserves existing evidence and snapshot identities. A repository without a GitHub ID cannot open its learning store for users, run learning, or prepare learning-backed decision-model data. Hub does not infer an ID from a name or expose its stored records. To migrate a non-SQLite Hub store, stop Hub and all older clients that can write it. Run `replica-learning migrate-scope --offline --dir /repositories/ --repository github.com/repositories/ --legacy-repository github.com/repositories/`. Verify the copied store before removing any source data. The package guide explains how to restore the previous provider for another repository. -In SQLite mode, decision commands use an existing store and never create one implicitly. The first complete review import prepares the store. +In SQLite mode, decision commands use an existing store and never create one implicitly. The first complete review import prepares the store. Hub keeps the latest decision-review snapshot ID, capture time, and content digest in the SQLite store directory. A SQLite checkpoint rename already in progress can finish after the execution lock is lost. With PostgreSQL, Hub keeps that checkpoint in its database and writes it on the connection holding the learning execution lock. It records observations even when training consent is off and stores no review text in the checkpoint. An ID-less legacy repository remains unavailable for learning. A queued learning run without an ID fails visibly, and decision reconciliation remains pending. Under the learning execution lock, deletion jobs can redact the original UUID-scoped store without making its records available to users. The redaction-only command follows the durable SQLite or PostgreSQL mapping when present and fails closed if ownership is uncertain. Recovery retries failures. It does not assign a GitHub ID or infer ownership from a name. diff --git a/hub/schema/decision-review-snapshot.prisma b/hub/schema/decision-review-snapshot.prisma new file mode 100644 index 00000000..e9724444 --- /dev/null +++ b/hub/schema/decision-review-snapshot.prisma @@ -0,0 +1,19 @@ +model DecisionReviewSnapshot { + // ID columns + id String @id @default(uuid()) @db.Uuid + repositoryId String @unique @map("repository_id") @db.Uuid + + // Relations + repository Repository @relation(fields: [repositoryId], references: [id], onDelete: Cascade) + + // Attribute columns + digest String @db.VarChar(71) + snapshotId String @map("snapshot_id") @db.Uuid + capturedAt DateTime @map("captured_at") @db.Timestamptz(3) + + // Timestamp columns + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(3) + + @@map("decision_review_snapshots") +} diff --git a/hub/schema/migrations/20261220160000_add_decision_review_snapshot/migration.sql b/hub/schema/migrations/20261220160000_add_decision_review_snapshot/migration.sql new file mode 100644 index 00000000..9f196bfc --- /dev/null +++ b/hub/schema/migrations/20261220160000_add_decision_review_snapshot/migration.sql @@ -0,0 +1,18 @@ +-- CreateTable +CREATE TABLE "decision_review_snapshots" ( + "id" UUID NOT NULL, + "repository_id" UUID NOT NULL, + "digest" VARCHAR(71) NOT NULL, + "snapshot_id" UUID NOT NULL, + "captured_at" TIMESTAMPTZ(3) NOT NULL, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "decision_review_snapshots_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "decision_review_snapshots_repository_id_key" ON "decision_review_snapshots"("repository_id"); + +-- AddForeignKey +ALTER TABLE "decision_review_snapshots" ADD CONSTRAINT "decision_review_snapshots_repository_id_fkey" FOREIGN KEY ("repository_id") REFERENCES "repositories"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/hub/schema/repository.prisma b/hub/schema/repository.prisma index 7076a624..0fdb4796 100644 --- a/hub/schema/repository.prisma +++ b/hub/schema/repository.prisma @@ -7,6 +7,7 @@ model Repository { learningRuns LearningRun[] learningDecisionOperations LearningDecisionOperation[] decisionModelConfiguration DecisionModelConfiguration? + decisionReviewSnapshot DecisionReviewSnapshot? decisionTrainingJobs DecisionTrainingJob[] decisionCandidates DecisionCandidate[] decisionModelPromotions DecisionModelPromotion[] diff --git a/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.db.test.ts b/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.db.test.ts new file mode 100644 index 00000000..c563aa39 --- /dev/null +++ b/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.db.test.ts @@ -0,0 +1,588 @@ +import { execFile } from "node:child_process" +import { randomUUID } from "node:crypto" +import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises" +import { join, resolve } from "node:path" +import { promisify } from "node:util" +import pg from "pg" +import { describe, expect, it, onTestFinished, vi } from "vitest" +import { z } from "zod" + +import { prisma } from "../../../integrations/prisma" +import { runLearningCommand } from "../../../integrations/learning/run-learning-command" +import { createHubReviewCollection } from "../../learning/create-hub-review-collection" +import { prepareLearningStore } from "../../learning/prepare-learning-store" +import { captureRepositoryReviewSnapshot } from "../../review-comments/capture-repository-review-snapshot" +import { createReviewCommentService } from "../../review-comments/create-review-comment-service" +import { getDatabaseUrl } from "../../../../test/database/get-database-url" +import { createHubDecisionTasksetSource } from "." + +const execFileAsync = promisify(execFile) +const cliPath = resolve("../packages/learning/bin/replica-learning.mjs") +const repositoryScope = "github.com/repositories/123456" + +async function workspace() { + const root = resolve("..", `.decision-snapshot-${randomUUID()}`) + await mkdir(root, { recursive: true, mode: 0o700 }) + onTestFinished(() => rm(root, { recursive: true, force: true })) + await execFileAsync("git", ["init", "-q", root]) + await writeFile(join(root, ".gitignore"), ".replica/\n") + const scratch = join(root, ".replica", "scratch") + await mkdir(scratch, { recursive: true, mode: 0o700 }) + vi.stubEnv("TMPDIR", scratch) + vi.stubEnv("TMP", scratch) + vi.stubEnv("TEMP", scratch) + return root +} + +async function learningDatabase(root: string) { + const adminUrl = getDatabaseUrl() + const name = `replica_learning_test_${randomUUID().replaceAll("-", "")}` + const admin = new pg.Client({ connectionString: adminUrl }) + await admin.connect() + try { + await admin.query(`CREATE DATABASE ${pg.escapeIdentifier(name)}`) + } finally { + await admin.end() + } + onTestFinished(async () => { + const cleanup = new pg.Client({ connectionString: adminUrl }) + await cleanup.connect() + try { + await cleanup.query(`DROP DATABASE ${pg.escapeIdentifier(name)} WITH (FORCE)`) + } finally { + await cleanup.end() + } + }) + const url = new URL(adminUrl) + url.pathname = name + await execFileAsync(process.execPath, [cliPath, "migrate", "--json"], { + cwd: root, + env: { + PATH: process.env.PATH, + HOME: process.env.HOME, + TMPDIR: process.env.TMPDIR, + REPLICA_LEARNING_MIGRATION_DATABASE_URL: url.href, + }, + }) + return url.href +} + +async function reviewedRepository() { + const repository = await prisma.repository.create({ + data: { githubRepositoryId: 123456n, nameWithOwner: "team/checkout", defaultBranch: "main" }, + }) + const prototype = await prisma.prototype.create({ + data: { + repositoryId: repository.id, + branchName: "checkout", + name: "Checkout", + registeredAt: new Date(), + }, + }) + const build = await prisma.build.create({ + data: { prototypeId: prototype.id, number: 1, state: "successful" }, + }) + const user = await prisma.user.create({ + data: { profile: { create: { provider: "github", login: "reviewer", name: null } } }, + }) + await createReviewCommentService(prisma).createThread({ + sessionDigest: "a".repeat(64), + repositoryId: repository.id, + prototypeId: prototype.id, + buildNumber: build.number, + body: "Keep the field label visible.", + actor: { userId: user.id, login: "reviewer", name: null }, + anchor: { + schemaVersion: 1, + kind: "element", + route: { pathname: "/checkout", search: "", hash: "" }, + selector: "#email", + accessibleName: "Email", + tagName: "input", + selectedText: "", + rect: { x: 0, y: 0, width: 100, height: 40 }, + viewport: { width: 1280, height: 800, scrollX: 0, scrollY: 0 }, + elementOffset: { x: 0.5, y: 0.5 }, + }, + }) + return { repository, prototype } +} + +function storeArguments(root: string, repositoryId: string) { + return [ + "--dir", + join(root, ".replica", "learning", "repositories", repositoryId), + "--repository", + repositoryScope, + "--legacy-repository", + `github.com/repositories/${repositoryId}`, + ] +} + +async function addGrant( + root: string, + repositoryId: string, + purposes: string[], + learningDatabaseUrl?: string, +) { + if (!learningDatabaseUrl) { + await prepareLearningStore({ + applicationRoot: root, + repositoryKey: repositoryId, + repositoryScope, + root: join(root, ".replica", "learning"), + staticDirectories: [], + }) + } + return (await runLearningCommand( + [ + "grants", + "add", + ...purposes.flatMap((purpose) => ["--purpose", purpose]), + "--basis", + "The team agreed to use review evidence.", + "--by", + "human:reviewer", + ...storeArguments(root, repositoryId), + ], + { cliPath, learningDatabaseUrl }, + )) as { id: string } +} + +async function withdrawTraining(root: string, repositoryId: string, grantId: string) { + await runLearningCommand( + [ + "grants", + "withdraw", + grantId, + "--purpose", + "training", + "--by", + "human:reviewer", + ...storeArguments(root, repositoryId), + ], + { cliPath }, + ) +} + +async function importSqlite(root: string, repositoryId: string, databaseUrl: string) { + await execFileAsync( + process.execPath, + [cliPath, "import-sqlite", "--offline", ...storeArguments(root, repositoryId), "--json"], + { + cwd: root, + env: { + PATH: process.env.PATH, + HOME: process.env.HOME, + TMPDIR: process.env.TMPDIR, + REPLICA_LEARNING_DATABASE_URL: databaseUrl, + }, + }, + ) +} + +function source(root: string, learningDatabaseUrl?: string) { + return createHubDecisionTasksetSource({ + applicationRoot: root, + artifactStorage: {} as never, + cliPath, + database: prisma, + databaseUrl: getDatabaseUrl(), + hubOrigin: "https://hub.example.test", + learningDatabaseUrl, + learningRoot: join(root, ".replica", "learning"), + staticDirectories: [], + }).tasksetSource +} + +function exported(bytes: Uint8Array) { + return JSON.parse(new TextDecoder().decode(bytes)) as { + manifest: { records: { kind: string; id: string; digest: string }[] } + grants: unknown[] + collections: { id: string; snapshotId: string; capturedAt: string }[] + episodes: { timeline: { payload?: { body?: string } }[] }[] + memories: unknown[] + } +} + +async function sqliteWithLegacySnapshot() { + const root = await workspace() + const { repository, prototype } = await reviewedRepository() + const grant = await addGrant(root, repository.id, ["review", "training"]) + const request = { repositoryId: repository.id, actorMembershipId: randomUUID() } + const first = await source(root).exportTrainingEvidence(request) + const [collection] = exported(first.bytes).collections + if (!collection) throw new Error("Expected an initial review collection.") + const path = join( + root, + ".replica", + "learning", + "repositories", + repository.id, + "decision-review-snapshot.json", + ) + const legacy = readableLegacySnapshot(await readFile(path, "utf8")) + if (!legacy) throw new Error("Expected the initial SQLite checkpoint.") + expect(legacy).toMatchObject({ + digest: first.repeatableReviewSnapshotDigest, + snapshotId: collection.snapshotId, + }) + expect(new Date(legacy.capturedAt)).toEqual(new Date(collection.capturedAt)) + await expect( + prisma.decisionReviewSnapshot.findUnique({ where: { repositoryId: repository.id } }), + ).resolves.toBeNull() + await withdrawTraining(root, repository.id, grant.id) + await prisma.prototype.update({ where: { id: prototype.id }, data: { name: "Account" } }) + return { root, repository, prototype, request, first, collection, path } +} + +/** Invalid legacy files cause older preflights to fail instead of reusing a snapshot. */ +function readableLegacySnapshot(contents: string) { + try { + const parsed = z + .object({ digest: z.string(), snapshotId: z.uuid(), capturedAt: z.iso.datetime() }) + .strict() + .safeParse(JSON.parse(contents)) + return parsed.success ? parsed.data : null + } catch (error) { + if (error instanceof SyntaxError) return null + throw error + } +} + +describe("createHubDecisionTasksetSource() training exports", () => { + it("retries PostgreSQL exports and imports a returned snapshot as new", async () => { + const root = await workspace() + const databaseUrl = await learningDatabase(root) + const { repository, prototype } = await reviewedRepository() + const grant = await addGrant(root, repository.id, ["review", "training"], databaseUrl) + const request = { repositoryId: repository.id, actorMembershipId: randomUUID() } + const directory = join(root, ".replica", "learning", "repositories", repository.id) + + const first = await source(root, databaseUrl).exportTrainingEvidence(request) + const retry = await source(root, databaseUrl).exportTrainingEvidence(request) + expect(retry).toEqual(first) + expect(first.consentGrantId).toBe(grant.id) + expect(exported(first.bytes).episodes[0]?.timeline[0]?.payload?.body).toBe( + "Keep the field label visible.", + ) + expect(exported(first.bytes).collections).toHaveLength(1) + + await prisma.prototype.update({ where: { id: prototype.id }, data: { name: "Account" } }) + const changed = await source(root, databaseUrl).exportTrainingEvidence(request) + await prisma.prototype.update({ where: { id: prototype.id }, data: { name: "Checkout" } }) + const returned = await source(root, databaseUrl).exportTrainingEvidence(request) + const returnedRetry = await source(root, databaseUrl).exportTrainingEvidence(request) + + expect(returned.repeatableReviewSnapshotDigest).toBe(first.repeatableReviewSnapshotDigest) + expect(returned.digest).not.toBe(first.digest) + expect(exported(changed.bytes).collections).toHaveLength(2) + expect(exported(returned.bytes).collections).toHaveLength(3) + expect(exported(returned.bytes).collections[2]?.snapshotId).not.toBe( + exported(first.bytes).collections[0]?.snapshotId, + ) + expect(returnedRetry).toEqual(returned) + await expect(access(directory)).rejects.toMatchObject({ code: "ENOENT" }) + }, 60_000) + + it("does not overwrite an unchanged successor after the execution lock is lost", async () => { + const root = await workspace() + const databaseUrl = await learningDatabase(root) + const { repository, prototype } = await reviewedRepository() + await addGrant(root, repository.id, ["review"], databaseUrl) + const request = { repositoryId: repository.id, actorMembershipId: randomUUID() } + const first = await source(root, databaseUrl).exportTrainingEvidence(request) + const checkpoint = await prisma.decisionReviewSnapshot.findUniqueOrThrow({ + where: { repositoryId: repository.id }, + select: { digest: true, snapshotId: true, capturedAt: true }, + }) + await prisma.prototype.update({ where: { id: prototype.id }, data: { name: "Account" } }) + + const gate = new pg.Client({ connectionString: getDatabaseUrl() }) + await gate.connect() + const trigger = `checkpoint_gate_${randomUUID().replaceAll("-", "")}` + let gateHeld = false + let stale: Promise | null = null + try { + // Pause the write while its connection still owns the execution lock. + await gate.query(` + CREATE FUNCTION "${trigger}"() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + PERFORM pg_advisory_xact_lock(1919242348, 201); + RETURN NULL; + END $$; + CREATE TRIGGER "${trigger}" BEFORE UPDATE ON decision_review_snapshots + FOR EACH STATEMENT EXECUTE FUNCTION "${trigger}"(); + `) + await gate.query("SELECT pg_advisory_lock(1919242348, 201)") + gateHeld = true + stale = source(root, databaseUrl).exportTrainingEvidence(request) + void stale.catch(() => {}) + + let blockedPid = 0 + await vi.waitFor( + async () => { + const waiting = await gate.query<{ pid: number }>(` + SELECT waiting.pid + FROM pg_locks AS waiting + JOIN pg_locks AS execution ON execution.pid = waiting.pid + WHERE waiting.locktype = 'advisory' AND waiting.classid = 1919242348 + AND waiting.objid = 201 AND NOT waiting.granted + AND execution.locktype = 'advisory' AND execution.classid = 1919242348 + AND execution.objid = 2 AND execution.granted + AND waiting.database = (SELECT oid FROM pg_database WHERE datname = current_database()) + `) + expect(waiting.rows).toHaveLength(1) + blockedPid = waiting.rows[0]!.pid + }, + { timeout: 10_000 }, + ) + const terminated = await gate.query<{ terminated: boolean }>( + "SELECT pg_terminate_backend($1) AS terminated", + [blockedPid], + ) + expect(terminated.rows).toEqual([{ terminated: true }]) + await expect(stale).rejects.toThrow() + + await prisma.prototype.update({ where: { id: prototype.id }, data: { name: "Checkout" } }) + await gate.query("SELECT pg_advisory_unlock(1919242348, 201)") + gateHeld = false + const successor = await source(root, databaseUrl).exportTrainingEvidence(request) + expect(successor.repeatableReviewSnapshotDigest).toBe(first.repeatableReviewSnapshotDigest) + await expect( + prisma.decisionReviewSnapshot.findUniqueOrThrow({ + where: { repositoryId: repository.id }, + select: { digest: true, snapshotId: true, capturedAt: true }, + }), + ).resolves.toEqual(checkpoint) + expect(await source(root, databaseUrl).exportTrainingEvidence(request)).toEqual(successor) + } finally { + if (gateHeld) await gate.query("SELECT pg_advisory_unlock(1919242348, 201)") + if (stale) await stale.catch(() => {}) + await gate.query( + `DROP TRIGGER IF EXISTS "${trigger}" ON decision_review_snapshots; DROP FUNCTION IF EXISTS "${trigger}"()`, + ) + await gate.end() + } + }, 60_000) + + it("imports a returned snapshot after a change without training consent", async () => { + const root = await workspace() + const databaseUrl = await learningDatabase(root) + const { repository, prototype } = await reviewedRepository() + const grant = await addGrant(root, repository.id, ["review", "training"], databaseUrl) + const request = { repositoryId: repository.id, actorMembershipId: randomUUID() } + const first = await source(root, databaseUrl).exportTrainingEvidence(request) + + await runLearningCommand( + [ + "grants", + "withdraw", + grant.id, + "--purpose", + "training", + "--by", + "human:reviewer", + ...storeArguments(root, repository.id), + ], + { cliPath, learningDatabaseUrl: databaseUrl }, + ) + await prisma.prototype.update({ where: { id: prototype.id }, data: { name: "Account" } }) + const withheld = await source(root, databaseUrl).exportTrainingEvidence(request) + const status = await runLearningCommand(["status", ...storeArguments(root, repository.id)], { + cliPath, + learningDatabaseUrl: databaseUrl, + }) + expect(withheld.consentGrantId).toBeNull() + expect(withheld.bytes).toHaveLength(0) + expect(withheld.repeatableReviewSnapshotDigest).not.toBe(first.repeatableReviewSnapshotDigest) + expect(status).toMatchObject({ counts: { completeCollections: 1 } }) + + await addGrant(root, repository.id, ["training"], databaseUrl) + await prisma.prototype.update({ where: { id: prototype.id }, data: { name: "Checkout" } }) + const returned = await source(root, databaseUrl).exportTrainingEvidence(request) + const retry = await source(root, databaseUrl).exportTrainingEvidence(request) + + expect(returned.repeatableReviewSnapshotDigest).toBe(first.repeatableReviewSnapshotDigest) + expect(exported(returned.bytes).collections).toHaveLength(2) + expect(exported(returned.bytes).collections[1]?.snapshotId).not.toBe( + exported(first.bytes).collections[0]?.snapshotId, + ) + expect(retry).toEqual(returned) + }, 60_000) + + it("retries the same export after an offline SQLite migration", async () => { + const root = await workspace() + const databaseUrl = await learningDatabase(root) + const { repository } = await reviewedRepository() + await addGrant(root, repository.id, ["review", "training"]) + const request = { repositoryId: repository.id, actorMembershipId: randomUUID() } + const directory = join(root, ".replica", "learning", "repositories", repository.id) + const original = await source(root).exportTrainingEvidence(request) + const originalBundle = exported(original.bytes) + const [collection] = originalBundle.collections + expect(collection).toBeDefined() + const legacy = readableLegacySnapshot( + await readFile(join(directory, "decision-review-snapshot.json"), "utf8"), + ) + if (!legacy) throw new Error("Expected the initial SQLite checkpoint.") + expect(legacy).toMatchObject({ + digest: original.repeatableReviewSnapshotDigest, + snapshotId: collection!.snapshotId, + }) + expect(new Date(legacy.capturedAt)).toEqual(new Date(collection!.capturedAt)) + await expect( + prisma.decisionReviewSnapshot.findUnique({ where: { repositoryId: repository.id } }), + ).resolves.toBeNull() + await importSqlite(root, repository.id, databaseUrl) + + const retained = await source(root, databaseUrl).exportTrainingEvidence(request) + await rm(directory, { recursive: true, force: true }) + const unmounted = await source(root, databaseUrl).exportTrainingEvidence(request) + const migratedBundle = exported(retained.bytes) + expect(migratedBundle.collections).toEqual(originalBundle.collections) + expect(migratedBundle.manifest.records).toEqual(originalBundle.manifest.records) + expect(migratedBundle.grants).toEqual(originalBundle.grants) + expect(migratedBundle.episodes).toEqual(originalBundle.episodes) + expect(migratedBundle.memories).toEqual(originalBundle.memories) + expect(unmounted).toEqual(retained) + await expect(access(directory)).rejects.toMatchObject({ code: "ENOENT" }) + }, 60_000) + + it("preserves a no-consent snapshot from the SQLite file during cutover", async () => { + const root = await workspace() + const databaseUrl = await learningDatabase(root) + const { repository, prototype } = await reviewedRepository() + const grant = await addGrant(root, repository.id, ["review", "training"]) + const request = { repositoryId: repository.id, actorMembershipId: randomUUID() } + const directory = join(root, ".replica", "learning", "repositories", repository.id) + const first = await source(root).exportTrainingEvidence(request) + + await runLearningCommand( + [ + "grants", + "withdraw", + grant.id, + "--purpose", + "training", + "--by", + "human:reviewer", + ...storeArguments(root, repository.id), + ], + { cliPath }, + ) + await prisma.prototype.update({ where: { id: prototype.id }, data: { name: "Account" } }) + const withheld = await source(root).exportTrainingEvidence(request) + expect(withheld.bytes).toHaveLength(0) + const legacySnapshot = readableLegacySnapshot( + await readFile(join(directory, "decision-review-snapshot.json"), "utf8"), + ) + expect(legacySnapshot).toMatchObject({ digest: withheld.repeatableReviewSnapshotDigest }) + if (!legacySnapshot) throw new Error("Expected the no-consent SQLite checkpoint.") + await expect( + prisma.decisionReviewSnapshot.findUnique({ where: { repositoryId: repository.id } }), + ).resolves.toBeNull() + await importSqlite(root, repository.id, databaseUrl) + + const migrated = await source(root, databaseUrl).exportTrainingEvidence(request) + expect(migrated.consentGrantId).toBeNull() + expect(migrated.bytes).toHaveLength(0) + expect(migrated.repeatableReviewSnapshotDigest).toBe(withheld.repeatableReviewSnapshotDigest) + expect( + await prisma.decisionReviewSnapshot.findUniqueOrThrow({ + where: { repositoryId: repository.id }, + }), + ).toMatchObject({ + ...legacySnapshot, + capturedAt: new Date(legacySnapshot.capturedAt), + }) + await rm(directory, { recursive: true, force: true }) + + await addGrant(root, repository.id, ["training"], databaseUrl) + await prisma.prototype.update({ where: { id: prototype.id }, data: { name: "Checkout" } }) + const returned = await source(root, databaseUrl).exportTrainingEvidence(request) + const retry = await source(root, databaseUrl).exportTrainingEvidence(request) + expect(returned.repeatableReviewSnapshotDigest).toBe(first.repeatableReviewSnapshotDigest) + expect(exported(returned.bytes).collections).toHaveLength(2) + expect(exported(returned.bytes).collections[1]?.snapshotId).not.toBe( + exported(first.bytes).collections[0]?.snapshotId, + ) + expect(retry).toEqual(returned) + }, 60_000) + + it("does not reuse A after an older SQLite writer observes B without consent", async () => { + const { root, repository, prototype, request, first, collection, path } = + await sqliteWithLegacySnapshot() + const snapshot = await captureRepositoryReviewSnapshot(prisma, repository.id) + const changed = createHubReviewCollection(snapshot, "https://hub.example.test", repositoryScope) + expect(changed.digest).not.toBe(first.repeatableReviewSnapshotDigest) + await writeFile( + path, + JSON.stringify({ + digest: changed.digest, + snapshotId: snapshot.snapshotId, + capturedAt: snapshot.capturedAt.toISOString(), + }), + { mode: 0o600 }, + ) + await expect( + prisma.decisionReviewSnapshot.findUnique({ where: { repositoryId: repository.id } }), + ).resolves.toBeNull() + + await addGrant(root, repository.id, ["training"]) + await prisma.prototype.update({ where: { id: prototype.id }, data: { name: "Checkout" } }) + const returned = await source(root).exportTrainingEvidence(request) + expect(returned.repeatableReviewSnapshotDigest).toBe(first.repeatableReviewSnapshotDigest) + expect(exported(returned.bytes).collections).toHaveLength(2) + expect(exported(returned.bytes).collections[1]?.snapshotId).not.toBe(collection.snapshotId) + expect(await source(root).exportTrainingEvidence(request)).toEqual(returned) + await expect( + prisma.decisionReviewSnapshot.findUnique({ where: { repositoryId: repository.id } }), + ).resolves.toBeNull() + }, 60_000) + + it("updates the SQLite checkpoint when training consent is off", async () => { + const { root, repository, prototype, request, first, collection, path } = + await sqliteWithLegacySnapshot() + const withheld = await source(root).exportTrainingEvidence(request) + expect(withheld.consentGrantId).toBeNull() + expect(withheld.bytes).toHaveLength(0) + expect(withheld.repeatableReviewSnapshotDigest).not.toBe(first.repeatableReviewSnapshotDigest) + + const legacy = readableLegacySnapshot(await readFile(path, "utf8")) + expect(legacy).toMatchObject({ digest: withheld.repeatableReviewSnapshotDigest }) + expect(legacy?.snapshotId).not.toBe(collection.snapshotId) + await expect( + prisma.decisionReviewSnapshot.findUnique({ where: { repositoryId: repository.id } }), + ).resolves.toBeNull() + + await addGrant(root, repository.id, ["training"]) + await prisma.prototype.update({ where: { id: prototype.id }, data: { name: "Checkout" } }) + const returned = await source(root).exportTrainingEvidence(request) + expect(exported(returned.bytes).collections).toHaveLength(2) + expect(exported(returned.bytes).collections[1]?.snapshotId).not.toBe(collection.snapshotId) + expect(await source(root).exportTrainingEvidence(request)).toEqual(returned) + }, 60_000) + + it("does not import evidence without training consent", async () => { + const root = await workspace() + const databaseUrl = await learningDatabase(root) + const { repository } = await reviewedRepository() + await addGrant(root, repository.id, ["review"], databaseUrl) + const request = { repositoryId: repository.id, actorMembershipId: randomUUID() } + + const result = await source(root, databaseUrl).exportTrainingEvidence(request) + const status = await runLearningCommand(["status", ...storeArguments(root, repository.id)], { + cliPath, + learningDatabaseUrl: databaseUrl, + }) + expect(result.consentGrantId).toBeNull() + expect(result.bytes).toHaveLength(0) + expect(status).toMatchObject({ + counts: { episodes: 0, events: 0, completeCollections: 0, incompleteCollections: 0 }, + }) + await expect( + access(join(root, ".replica", "learning", "repositories", repository.id)), + ).rejects.toMatchObject({ code: "ENOENT" }) + }, 60_000) +}) diff --git a/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.test.ts b/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.test.ts index ed39b518..76688cc1 100644 --- a/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.test.ts +++ b/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.test.ts @@ -487,6 +487,7 @@ describe("createHubDecisionTasksetSource()", () => { it("reports deterministic eligible evidence, task, split, and label counts", async () => { vi.mocked(withLearningExecutionLock).mockImplementation(({ run }) => run(new AbortController().signal, { + client: {} as never, runWithoutRepositoryAuthorityLock: (operation) => operation(), }), ) @@ -649,6 +650,7 @@ describe("createHubDecisionTasksetSource()", () => { const privateEvidence = "Do not expose this private learning" vi.mocked(withLearningExecutionLock).mockImplementation(({ run }) => run(new AbortController().signal, { + client: {} as never, runWithoutRepositoryAuthorityLock: (operation) => operation(), }), ) @@ -725,6 +727,7 @@ describe("createHubDecisionTasksetSource()", () => { it("exports repository-scoped learning evidence deterministically on retry", async () => { vi.mocked(withLearningExecutionLock).mockImplementation(({ run }) => run(new AbortController().signal, { + client: {} as never, runWithoutRepositoryAuthorityLock: (operation) => operation(), }), ) diff --git a/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.ts b/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.ts index 07b09595..cbed8e8e 100644 --- a/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.ts +++ b/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.ts @@ -15,6 +15,7 @@ import { tmpdir } from "node:os" import { join, resolve } from "node:path" import { z } from "zod" import type { Logger } from "pino" +import type { Client } from "pg" import type { PrismaClient } from "../../../generated/prisma/client.ts" import { runLearningCommand } from "../../../integrations/learning/run-learning-command/index.ts" @@ -27,6 +28,8 @@ import { prepareLearningStore } from "../../learning/prepare-learning-store/inde import { captureRepositoryReviewSnapshot } from "../../review-comments/capture-repository-review-snapshot/index.ts" import { listDecisionTrainingBuilds } from "../../../repositories/decision-training-builds/list-decision-training-builds/index.ts" import { findDecisionEvaluationBuild } from "../../../repositories/decision-training-builds/find-decision-evaluation-build/index.ts" +import { getDecisionReviewSnapshot } from "../../../repositories/decision-review-snapshots/get-decision-review-snapshot/index.ts" +import { saveDecisionReviewSnapshot } from "../../../repositories/decision-review-snapshots/save-decision-review-snapshot/index.ts" import { listDecisionWithdrawalSources } from "../../../repositories/decision-training-jobs/list-decision-withdrawal-sources/index.ts" import { withLearningExecutionLock } from "../../../integrations/postgres/with-learning-execution-lock/index.ts" import { DecisionModelError } from "../errors.ts" @@ -243,14 +246,12 @@ function digestJson(value: unknown): string { return sha256(canonicalJson(value)) } -async function stabilizeReviewSnapshot( - directory: string, - digest: string, - capturedAt: Date, -): Promise<{ snapshotId: string; capturedAt: Date }> { - const statePath = join(directory, "decision-review-snapshot.json") +async function readLegacyReviewSnapshot(directory: string) { try { - const handle = await open(statePath, constants.O_RDONLY | constants.O_NOFOLLOW) + const handle = await open( + join(directory, "decision-review-snapshot.json"), + constants.O_RDONLY | constants.O_NOFOLLOW, + ) try { const state = z .object({ @@ -260,20 +261,26 @@ async function stabilizeReviewSnapshot( }) .strict() .parse(JSON.parse(await handle.readFile("utf8"))) - if (state.digest === digest) { - return { snapshotId: state.snapshotId, capturedAt: new Date(state.capturedAt) } - } + return { ...state, capturedAt: new Date(state.capturedAt) } } finally { await handle.close() } } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error + return null } - const state = { - digest, - snapshotId: randomUUID(), - capturedAt: capturedAt.toISOString(), - } +} + +async function stabilizeLocalReviewSnapshot( + directory: string, + digest: string, + capturedAt: Date, + signal: AbortSignal, +): Promise<{ snapshotId: string; capturedAt: Date }> { + const previous = await readLegacyReviewSnapshot(directory) + signal.throwIfAborted() + if (previous?.digest === digest) return previous + const next = { digest, snapshotId: randomUUID(), capturedAt } const temporary = join(directory, `.decision-review-snapshot-${randomUUID()}`) const handle = await open( temporary, @@ -281,13 +288,45 @@ async function stabilizeReviewSnapshot( 0o600, ) try { - await handle.writeFile(`${JSON.stringify(state)}\n`) - await handle.sync() + try { + await handle.writeFile(`${JSON.stringify(next)}\n`) + await handle.sync() + } finally { + await handle.close() + } + signal.throwIfAborted() + await rename(temporary, join(directory, "decision-review-snapshot.json")) } finally { - await handle.close() + await rm(temporary, { force: true }) + } + return next +} + +async function stabilizeReviewSnapshot( + database: PrismaClient, + lockClient: Pick, + repositoryId: string, + directory: string, + digest: string, + capturedAt: Date, + signal: AbortSignal, +): Promise<{ snapshotId: string; capturedAt: Date }> { + const stored = await getDecisionReviewSnapshot(database, repositoryId) + signal.throwIfAborted() + const previous = stored ?? (await readLegacyReviewSnapshot(directory)) + signal.throwIfAborted() + if (stored?.digest === digest) return stored + const next = + previous?.digest === digest ? previous : { digest, snapshotId: randomUUID(), capturedAt } + if (!(await saveDecisionReviewSnapshot(lockClient, repositoryId, next, stored))) { + throw new DecisionModelError( + 409, + "taskset_drift", + "The review snapshot changed during taskset preparation. Try again.", + ) } - await rename(temporary, statePath) - return { snapshotId: state.snapshotId, capturedAt } + signal.throwIfAborted() + return next } function stableExport(bundle: Record, snapshotDigest: string) { @@ -1003,7 +1042,7 @@ export function createHubDecisionTasksetSource(options: HubDecisionTasksetSource try { return await withLearningExecutionLock({ databaseUrl: options.databaseUrl, - run: async (signal) => { + run: async (signal, { client }) => { const store = await learningStore(repositoryId) const common = learningStoreArguments(store) const grants = grantListSchema.parse( @@ -1044,11 +1083,28 @@ export function createHubDecisionTasksetSource(options: HubDecisionTasksetSource options.hubOrigin, store.repositoryScope, ) - const metadata = await (options.stabilizeSnapshot ?? stabilizeReviewSnapshot)( - store.directory, - initialReview.digest, - snapshot.capturedAt, - ) + const metadata = options.stabilizeSnapshot + ? await options.stabilizeSnapshot( + store.directory, + initialReview.digest, + snapshot.capturedAt, + ) + : options.learningDatabaseUrl + ? await stabilizeReviewSnapshot( + options.database, + client, + repositoryId, + store.directory, + initialReview.digest, + snapshot.capturedAt, + signal, + ) + : await stabilizeLocalReviewSnapshot( + store.directory, + initialReview.digest, + snapshot.capturedAt, + signal, + ) snapshot.snapshotId = metadata.snapshotId snapshot.capturedAt = metadata.capturedAt const review = createHubReviewCollection( diff --git a/hub/server/integrations/postgres/with-learning-execution-lock/index.ts b/hub/server/integrations/postgres/with-learning-execution-lock/index.ts index 9db35b37..86d77205 100644 --- a/hub/server/integrations/postgres/with-learning-execution-lock/index.ts +++ b/hub/server/integrations/postgres/with-learning-execution-lock/index.ts @@ -11,6 +11,7 @@ export async function withLearningExecutionLock({ run: ( signal: AbortSignal, controls: { + client: Pick runWithoutRepositoryAuthorityLock: ( operation: () => Promise, ) => Promise @@ -49,6 +50,7 @@ export async function withLearningExecutionLock({ } controller.signal.throwIfAborted() running = run(controller.signal, { + client, runWithoutRepositoryAuthorityLock: async (operation: () => Promise) => { const unlocked = await client.query<{ unlocked: boolean }>( "SELECT pg_advisory_unlock_shared(1919242348, 3) AS unlocked", diff --git a/hub/server/repositories/decision-review-snapshots/get-decision-review-snapshot/index.ts b/hub/server/repositories/decision-review-snapshots/get-decision-review-snapshot/index.ts new file mode 100644 index 00000000..6ad081ac --- /dev/null +++ b/hub/server/repositories/decision-review-snapshots/get-decision-review-snapshot/index.ts @@ -0,0 +1,11 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +export function getDecisionReviewSnapshot( + database: Pick, + repositoryId: string, +) { + return database.decisionReviewSnapshot.findUnique({ + where: { repositoryId }, + select: { digest: true, snapshotId: true, capturedAt: true }, + }) +} diff --git a/hub/server/repositories/decision-review-snapshots/save-decision-review-snapshot/index.db.test.ts b/hub/server/repositories/decision-review-snapshots/save-decision-review-snapshot/index.db.test.ts new file mode 100644 index 00000000..d8372c39 --- /dev/null +++ b/hub/server/repositories/decision-review-snapshots/save-decision-review-snapshot/index.db.test.ts @@ -0,0 +1,46 @@ +import { randomUUID } from "node:crypto" +import pg from "pg" +import { describe, expect, it } from "vitest" + +import { prisma } from "../../../integrations/prisma" +import { getDatabaseUrl } from "../../../../test/database/get-database-url" +import { saveDecisionReviewSnapshot } from "." + +describe("saveDecisionReviewSnapshot()", () => { + it("keeps the winning checkpoint when a stale writer tries to create or update it", async () => { + const repository = await prisma.repository.create({ + data: { nameWithOwner: "team/checkout", defaultBranch: "main" }, + }) + const first = { + digest: `sha256:${"a".repeat(64)}`, + snapshotId: randomUUID(), + capturedAt: new Date("2026-01-01T00:00:00.000Z"), + } + const changed = { + digest: `sha256:${"b".repeat(64)}`, + snapshotId: randomUUID(), + capturedAt: new Date("2026-01-01T00:01:00.000Z"), + } + const winner = { + ...first, + snapshotId: randomUUID(), + capturedAt: new Date("2026-01-01T00:02:00.000Z"), + } + + const client = new pg.Client({ connectionString: getDatabaseUrl() }) + await client.connect() + try { + expect(await saveDecisionReviewSnapshot(client, repository.id, first, null)).toBe(true) + expect(await saveDecisionReviewSnapshot(client, repository.id, changed, first)).toBe(true) + expect(await saveDecisionReviewSnapshot(client, repository.id, winner, changed)).toBe(true) + + expect(await saveDecisionReviewSnapshot(client, repository.id, changed, null)).toBe(false) + expect(await saveDecisionReviewSnapshot(client, repository.id, changed, first)).toBe(false) + await expect( + prisma.decisionReviewSnapshot.findUniqueOrThrow({ where: { repositoryId: repository.id } }), + ).resolves.toMatchObject(winner) + } finally { + await client.end() + } + }) +}) diff --git a/hub/server/repositories/decision-review-snapshots/save-decision-review-snapshot/index.ts b/hub/server/repositories/decision-review-snapshots/save-decision-review-snapshot/index.ts new file mode 100644 index 00000000..efb8146a --- /dev/null +++ b/hub/server/repositories/decision-review-snapshots/save-decision-review-snapshot/index.ts @@ -0,0 +1,41 @@ +import { randomUUID } from "node:crypto" +import type { Client } from "pg" + +interface Snapshot { + digest: string + snapshotId: string + capturedAt: Date +} + +/** Keep the checkpoint write on the session that owns the execution lock. */ +export async function saveDecisionReviewSnapshot( + database: Pick, + repositoryId: string, + snapshot: Snapshot, + previous: Snapshot | null, +) { + // Prisma cannot use the session holding the advisory lock. + const result = previous + ? await database.query( + `UPDATE decision_review_snapshots + SET digest = $1, snapshot_id = $2, captured_at = $3, updated_at = CURRENT_TIMESTAMP + WHERE repository_id = $4 AND digest = $5 AND snapshot_id = $6 AND captured_at = $7`, + [ + snapshot.digest, + snapshot.snapshotId, + snapshot.capturedAt, + repositoryId, + previous.digest, + previous.snapshotId, + previous.capturedAt, + ], + ) + : await database.query( + `INSERT INTO decision_review_snapshots + (id, repository_id, digest, snapshot_id, captured_at) + VALUES ($1, $2, $3, $4, $5) + ON CONFLICT (repository_id) DO NOTHING`, + [randomUUID(), repositoryId, snapshot.digest, snapshot.snapshotId, snapshot.capturedAt], + ) + return result.rowCount === 1 +} diff --git a/hub/test/database/decision-review-snapshot-migration/index.db.test.ts b/hub/test/database/decision-review-snapshot-migration/index.db.test.ts new file mode 100644 index 00000000..da275376 --- /dev/null +++ b/hub/test/database/decision-review-snapshot-migration/index.db.test.ts @@ -0,0 +1,195 @@ +import { execFile } from "node:child_process" +import { randomBytes, randomUUID } from "node:crypto" +import { readFile, readdir } from "node:fs/promises" +import { join } from "node:path" +import { fileURLToPath } from "node:url" +import { promisify } from "node:util" +import pg from "pg" +import { describe, expect, it } from "vitest" + +const timeoutMs = 180_000 +const baseMigration = "20261220150000_inbox_unread_lookup" + +describe("decision review snapshot migration", () => { + it( + "preserves the populated base and keeps checkpoints unique to each repository", + async () => { + const adminUrl = process.env.TEST_DATABASE_URL + if (!adminUrl) throw new Error("TEST_DATABASE_URL is required.") + const name = `replica_snapshot_upgrade_${randomBytes(8).toString("hex")}` + const admin = new pg.Client({ connectionString: adminUrl }) + await admin.connect() + let created = false + try { + await admin.query(`CREATE DATABASE ${pg.escapeIdentifier(name)}`) + created = true + const databaseUrl = new URL(adminUrl) + databaseUrl.pathname = name + const database = new pg.Client({ connectionString: databaseUrl.toString() }) + try { + await database.connect() + const hubRoot = fileURLToPath(new URL("../../../", import.meta.url)) + const migrationsRoot = join(hubRoot, "schema/migrations") + const names = (await readdir(migrationsRoot, { withFileTypes: true })) + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name) + .sort() + const checkpointMigrations = names.filter((name) => + name.endsWith("_add_decision_review_snapshot"), + ) + expect(checkpointMigrations).toHaveLength(1) + const checkpointMigration = checkpointMigrations[0]! + const base = names.filter((name) => name <= baseMigration && name !== checkpointMigration) + expect(base.at(-1)).toBe(baseMigration) + expect(checkpointMigration > baseMigration).toBe(true) + + for (const migrationName of base) { + const sql = await readFile(join(migrationsRoot, migrationName, "migration.sql"), "utf8") + if (migrationName === "20261104190000_entra_oidc_authentication") { + const statements = sql.split("\n") + await database.query(statements.slice(0, 2).join("\n")) + await database.query(statements.slice(2).join("\n")) + } else { + await database.query(sql) + } + } + + const retainedRepositoryId = randomUUID() + const removedRepositoryId = randomUUID() + const prototypeId = randomUUID() + const runId = randomUUID() + const reviewDigest = `sha256:${"a".repeat(64)}` + await database.query( + `INSERT INTO repositories (id, github_repository_id, name_with_owner, default_branch) + VALUES ($1, 1001, 'team/retained', 'main'), ($2, 1002, 'team/removed', 'main')`, + [retainedRepositoryId, removedRepositoryId], + ) + await database.query( + `INSERT INTO prototypes (id, repository_id, branch_name, name, registered_at) + VALUES ($1, $2, 'prototype/checkout', 'Checkout', '2026-11-18T12:00:00Z')`, + [prototypeId, retainedRepositoryId], + ) + await database.query( + `INSERT INTO learning_runs + (id, repository_id, snapshot_digest, state, started_at, finished_at) + VALUES ($1, $2, $3, 'SUCCEEDED', '2026-11-18T12:01:00Z', '2026-11-18T12:02:00Z')`, + [runId, retainedRepositoryId, reviewDigest], + ) + async function retainedData() { + const result = await database.query<{ + repository_id: string + name_with_owner: string + prototype_id: string + name: string + run_id: string + state: string + snapshot_digest: string + }>( + `SELECT repository.id AS repository_id, repository.name_with_owner, + prototype.id AS prototype_id, prototype.name, + run.id AS run_id, run.state, run.snapshot_digest + FROM repositories repository + JOIN prototypes prototype ON prototype.repository_id = repository.id + JOIN learning_runs run ON run.repository_id = repository.id + WHERE repository.id = $1`, + [retainedRepositoryId], + ) + return result.rows + } + const before = await retainedData() + expect(before).toEqual([ + { + repository_id: retainedRepositoryId, + name_with_owner: "team/retained", + prototype_id: prototypeId, + name: "Checkout", + run_id: runId, + state: "SUCCEEDED", + snapshot_digest: reviewDigest, + }, + ]) + + const run = promisify(execFile) + const prismaCli = join(hubRoot, "node_modules/prisma/build/index.js") + const options = { + cwd: hubRoot, + env: { ...process.env, DATABASE_URL: databaseUrl.toString() }, + timeout: timeoutMs, + } + for (const migrationName of base) { + await run( + process.execPath, + [ + prismaCli, + "migrate", + "resolve", + "--applied", + migrationName, + "--config", + "prisma7.config.ts", + ], + options, + ) + } + await run( + process.execPath, + [prismaCli, "migrate", "deploy", "--config", "prisma7.config.ts"], + options, + ) + + expect(await retainedData()).toEqual(before) + expect( + ( + await database.query( + `SELECT migration_name FROM _prisma_migrations + WHERE migration_name = $1 AND finished_at IS NOT NULL`, + [checkpointMigration], + ) + ).rows, + ).toEqual([{ migration_name: checkpointMigration }]) + expect((await database.query("SELECT id FROM decision_review_snapshots")).rows).toEqual( + [], + ) + + const keptSnapshotId = randomUUID() + const insert = `INSERT INTO decision_review_snapshots + (id, repository_id, digest, snapshot_id, captured_at) + VALUES ($1, $2, $3, $4, '2026-11-18T12:00:00Z')` + await database.query(insert, [ + randomUUID(), + removedRepositoryId, + reviewDigest, + randomUUID(), + ]) + await expect( + database.query(insert, [randomUUID(), removedRepositoryId, reviewDigest, randomUUID()]), + ).rejects.toMatchObject({ code: "23505" }) + await database.query(insert, [ + randomUUID(), + retainedRepositoryId, + reviewDigest, + keptSnapshotId, + ]) + await database.query("DELETE FROM repositories WHERE id = $1", [removedRepositoryId]) + expect( + ( + await database.query( + "SELECT repository_id, snapshot_id FROM decision_review_snapshots", + ) + ).rows, + ).toEqual([{ repository_id: retainedRepositoryId, snapshot_id: keptSnapshotId }]) + expect(await retainedData()).toEqual(before) + } finally { + await database.end() + } + } finally { + try { + if (created) await admin.query(`DROP DATABASE ${pg.escapeIdentifier(name)} WITH (FORCE)`) + } finally { + await admin.end() + } + } + }, + timeoutMs, + ) +}) From 190fb929986ae15512d11806a416632ab05b19ac Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 17:12:57 -0800 Subject: [PATCH 16/18] fix(ci): install learning runtime for Hub checks Hub database tests run the learning command and need its optional PostgreSQL driver. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 50605b0b-6b69-4743-b6d9-6918b6c9878a --- .github/workflows/hub-ci.yml | 5 ++++- hub/docs/testing-and-operations.md | 2 +- scripts/check-ci-workflows/index.test.ts | 13 +++++++++++++ scripts/check-ci-workflows/index.ts | 7 +++++++ 4 files changed, 25 insertions(+), 2 deletions(-) diff --git a/.github/workflows/hub-ci.yml b/.github/workflows/hub-ci.yml index ab189513..759a531c 100644 --- a/.github/workflows/hub-ci.yml +++ b/.github/workflows/hub-ci.yml @@ -41,8 +41,11 @@ jobs: with: node-version: ${{ matrix.node }} cache: npm - cache-dependency-path: hub/package-lock.json + cache-dependency-path: | + hub/package-lock.json + packages/learning/package-lock.json - run: npm ci --engine-strict + - run: npm ci --prefix ../packages/learning --ignore-scripts --engine-strict - run: npm run ${{ matrix.command }} env: TEST_DATABASE_URL: ${{ matrix.command == 'test:database' && 'postgresql://replica:replica@127.0.0.1:5432/postgres' || '' }} diff --git a/hub/docs/testing-and-operations.md b/hub/docs/testing-and-operations.md index d506e242..1f4007e4 100644 --- a/hub/docs/testing-and-operations.md +++ b/hub/docs/testing-and-operations.md @@ -2,7 +2,7 @@ These checks cover the Hub API, database setup, and frontend. See [Architecture](architecture.md) for the features that are implemented. -Run commands directly from `hub/` after `npm ci`. The database command also needs PostgreSQL and `TEST_DATABASE_URL`, as described in [parallel database tests](#parallel-database-tests): +Run commands directly from `hub/` after `npm ci`. For database tests, also install the learning runtime as described in [Development](development.md), start PostgreSQL, and set `TEST_DATABASE_URL` as described in [parallel database tests](#parallel-database-tests): ```sh npm run lint diff --git a/scripts/check-ci-workflows/index.test.ts b/scripts/check-ci-workflows/index.test.ts index 0b2bbba1..6db6e1a9 100644 --- a/scripts/check-ci-workflows/index.test.ts +++ b/scripts/check-ci-workflows/index.test.ts @@ -39,6 +39,19 @@ describe("checkWorkflows()", () => { expect(() => checkWorkflows(root)).not.toThrow() }) + it("rejects Hub checks without the learning runtime", () => { + const directory = fixture() + const path = join(directory, ".github/workflows/hub-ci.yml") + const workflow = parse(readFileSync(path, "utf8")) as Workflow + assert(workflow.jobs.check.steps) + workflow.jobs.check.steps = workflow.jobs.check.steps.filter( + (step) => + step.run !== "npm ci --prefix ../packages/learning --ignore-scripts --engine-strict", + ) + writeFileSync(path, stringify(workflow)) + expect(() => checkWorkflows(directory)).toThrow(/learning runtime/) + }) + it("rejects an aggregate result gate", () => { const directory = fixture() const path = join(directory, ".github/workflows/hub-ci.yml") diff --git a/scripts/check-ci-workflows/index.ts b/scripts/check-ci-workflows/index.ts index 87a2f5fd..516c86ff 100644 --- a/scripts/check-ci-workflows/index.ts +++ b/scripts/check-ci-workflows/index.ts @@ -78,6 +78,13 @@ export function checkWorkflows(root: string): void { "test:database", ]) assert(hub.check.steps?.some((step) => step.run === "npm run ${{ matrix.command }}")) + assert( + hub.check.steps?.some( + (step) => + step.run === "npm ci --prefix ../packages/learning --ignore-scripts --engine-strict", + ), + "Hub checks must install the learning runtime", + ) for (const command of [ "controls:test", "extension:test", From d508a7aaefb3e5d0f6ebc256672f823ff90aca69 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 17:28:06 -0800 Subject: [PATCH 17/18] docs(azure): clarify setup database references Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 50605b0b-6b69-4743-b6d9-6918b6c9878a --- infrastructure/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/infrastructure/README.md b/infrastructure/README.md index e119bd8b..4771b057 100644 --- a/infrastructure/README.md +++ b/infrastructure/README.md @@ -483,7 +483,7 @@ Setup receives its migration URL as both `DATABASE_URL` and `REPLICA_LEARNING_MI Terraform ignores only Azure-assigned PostgreSQL availability-zone and Container Apps infrastructure-resource-group values. It still checks other drift and owns both images. The installation output exposes authoritative app, resource-group, and storage-account IDs; before the first release, the app ID is `null`. -The setup job uses the same digest and command `node dist/server/scripts/azure-entrypoint/index.js setup`. Its environment settings are `NODE_ENV=production`, `RUNTIME_MODE=setup`, `DATABASE_RUNTIME_ROLE=replica_runtime`, its own `AZURE_CLIENT_ID`, and a reference map containing only its migration `DATABASE_URL` for `replica_migration`. It receives no artifact configuration or additional runtime secrets. It has one replica, no automatic retries, and a 30-minute timeout. Hub's readiness probe is `/api/ready`; startup and liveness use `/api/health`. Azure allows 60 seconds for termination, covering the 30-second application drain and up to five seconds of telemetry flushing with platform margin. +The setup job uses the same digest and command `node dist/server/scripts/azure-entrypoint/index.js setup`. Its environment settings are `NODE_ENV=production`, `RUNTIME_MODE=setup`, `DATABASE_RUNTIME_ROLE=replica_runtime`, and its own `AZURE_CLIENT_ID`. Its reference map supplies the same `replica_migration` secret as both `DATABASE_URL` and `REPLICA_LEARNING_MIGRATION_DATABASE_URL`. When a PostgreSQL learning database secret is configured, it also sets `REPLICA_LEARNING_RUNTIME_ROLE=replica_learning_runtime`. Setup receives no artifact configuration or additional runtime secrets. It has one replica, no automatic retries, and a 30-minute timeout. Hub's readiness probe is `/api/ready`; startup and liveness use `/api/health`. Azure allows 60 seconds for termination, covering the 30-second application drain and up to five seconds of telemetry flushing with platform margin. Neither workload receives the PostgreSQL administrator credential. A separate, one-time operator script provisions the migration and runtime roles over the private database network. Setup owns schema changes and refreshes the runtime's data permissions after migrations. See [database access](../hub/docs/database.md#deployment-database-roles). Managed identity is used for Blob, Key Vault, and ACR, not database authentication. From 9688410a6e3be0ef2ece918defb8f0ab0857a265 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 17:37:05 -0800 Subject: [PATCH 18/18] docs(azure): clarify runtime secret limits Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 50605b0b-6b69-4743-b6d9-6918b6c9878a --- infrastructure/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/infrastructure/README.md b/infrastructure/README.md index 4771b057..bbe8b096 100644 --- a/infrastructure/README.md +++ b/infrastructure/README.md @@ -458,7 +458,7 @@ Initialize each optional module against its own protected backend state key, rev The app has external HTTPS ingress and minimum and maximum one replica **per revision**. Multiple-revision mode permits explicit deactivation before releases. Azure's single-revision mode deliberately overlaps old and new processes while readiness is checked, so it is unsuitable for this maintenance-window strategy. Do not activate old revisions alongside the combined worker. This is not a high-availability or zero-downtime installation. -The runtime receives `RUNTIME_MODE=combined`, `HOST=0.0.0.0`, `PORT=3001`, `CLIENT_DIRECTORY=/app/dist/client`, `SHUTDOWN_TIMEOUT_MS=30000`, and `NODE_ENV=production`. Artifacts use `ARTIFACT_STORAGE_PROVIDER=azure`, the provisioned `AZURE_STORAGE_ACCOUNT`, `AZURE_STORAGE_CONTAINER=artifacts`, and Hub's `AZURE_CLIENT_ID`. Optional `runtime_secret_references` map environment names to vault resource IDs and HTTPS secret URLs; at most 63 additional references are allowed because the runtime database URL is the 64th. Vault and secret names in these URLs must fit Azure's 24-character and 127-character limits. Terraform passes the Key Vault URLs, including the runtime database secret reference, as the non-secret JSON map `AZURE_KEY_VAULT_SECRET_REFERENCES`, never as inline secret values or Container Apps Key Vault secret bindings. +The runtime receives `RUNTIME_MODE=combined`, `HOST=0.0.0.0`, `PORT=3001`, `CLIENT_DIRECTORY=/app/dist/client`, `SHUTDOWN_TIMEOUT_MS=30000`, and `NODE_ENV=production`. Artifacts use `ARTIFACT_STORAGE_PROVIDER=azure`, the provisioned `AZURE_STORAGE_ACCOUNT`, `AZURE_STORAGE_CONTAINER=artifacts`, and Hub's `AZURE_CLIENT_ID`. Optional `runtime_secret_references` map environment names to vault resource IDs and HTTPS secret URLs. At most 63 additional references are allowed, or 62 when a learning database is configured, because the database URLs also use reference slots. Vault and secret names in these URLs must fit Azure's 24-character and 127-character limits. Terraform passes the Key Vault URLs, including the runtime database secret references, as the non-secret JSON map `AZURE_KEY_VAULT_SECRET_REFERENCES`, never as inline secret values or Container Apps Key Vault secret bindings. Use the optional `runtime_environment_variables` string map for non-secret Hub settings. Names must start with an uppercase letter and contain only uppercase letters, digits, or underscores, with at most 41 characters. Empty string values are allowed; null values are not. Deployment-owned names, including database credentials, storage settings, and startup identity/reference metadata, cannot be overridden. A name cannot appear in both this map and `runtime_secret_references`. These values go only to Hub, not setup or provisioning. The wizard adds no questions for this map; guided updates preserve it in the private workspace's `installation.tfvars.json`.