diff --git a/plugins/plugin-local-storage/src/services/local-storage.ts b/plugins/plugin-local-storage/src/services/local-storage.ts index 06fbe089a0f74..24688809d4d10 100644 --- a/plugins/plugin-local-storage/src/services/local-storage.ts +++ b/plugins/plugin-local-storage/src/services/local-storage.ts @@ -262,10 +262,10 @@ export class LocalFileStorageService extends Service { try { return await storage.exists(normalizeStorageKey(key)); } catch (err: unknown) { - // `@brighter/storage-adapter-local`'s `exists()` calls `fs.access`, - // which throws ENOENT on Windows when the file is missing instead - // of returning false. Coerce the absence case to `false` so the - // public method behaves identically on every platform. + // error-policy:J3 platform normalization — `@brighter/storage-adapter-local`'s + // `exists()` calls `fs.access`, which throws ENOENT on Windows when the + // file is missing instead of returning false. ENOENT is the typed "does + // not exist" answer (false); every other error is a real fault → rethrow. const e = err as NodeJS.ErrnoException; if (e?.code === "ENOENT") return false; throw err; diff --git a/plugins/plugin-localdb/index.ts b/plugins/plugin-localdb/index.ts index 8732d29476edb..b9b43eb87e8e7 100644 --- a/plugins/plugin-localdb/index.ts +++ b/plugins/plugin-localdb/index.ts @@ -48,6 +48,9 @@ class FileStorage implements IStorage { this.collections.set(collection, new Map(Object.entries(entries))); } } catch (error) { + // error-policy:J3 expected-shape degrade — ENOENT means the store file + // doesn't exist yet (fresh install): start empty. Every other error + // (corrupt JSON, permission, I/O) is a real fault → rethrow. if ((error as { code?: string }).code !== "ENOENT") throw error; } this.ready = true; @@ -83,8 +86,9 @@ class FileStorage implements IStorage { const payload = JSON.stringify(out, null, 2); const run = this.writeChain.then(() => this.writeAtomic(payload)); - // Keep the chain alive even if a write rejects, so a single failure does - // not permanently break serialization for subsequent flushes. + // error-policy:J5 unhandled-rejection suppression — the swallow only guards + // the *chain link* so one failed write can't poison later flushes; the real + // rejection IS observed by this flush's caller via `await run` below. this.writeChain = run.catch(() => {}); await run; } diff --git a/plugins/plugin-sql/src/__tests__/integration/db-failure-error-path.real.test.ts b/plugins/plugin-sql/src/__tests__/integration/db-failure-error-path.real.test.ts new file mode 100644 index 0000000000000..9f34fa5afbf2c --- /dev/null +++ b/plugins/plugin-sql/src/__tests__/integration/db-failure-error-path.real.test.ts @@ -0,0 +1,150 @@ +/** + * Real error-path coverage for the fail-fast DB adapter sweep (#12269 / #12182): + * drives a genuinely broken PGlite (its underlying connection is closed out from + * under the adapter while the manager still reports "not shutting down", so the + * query itself faults) and asserts that read/count/write methods throw a typed + * `ElizaError` with the right `code` instead of fabricating a healthy-looking + * default (`0` / `[]` / `false` / `undefined`). A companion case confirms an API + * route mounted over the adapter surfaces a structured 5xx, not a fabricated 200. + * + * No mocks: the failure is a real closed PGlite client. `VITEST_EXCLUDE_REAL=1` + * (the PR lane) skips this; the post-merge lane runs it against real PGlite. + */ +import type { PGlite } from "@electric-sql/pglite"; +import { type ElizaError, isElizaError, type UUID } from "@elizaos/core"; +import { v4 } from "uuid"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import type { PgDatabaseAdapter } from "../../pg/adapter"; +import type { PgliteDatabaseAdapter } from "../../pglite/adapter"; +import { createIsolatedTestDatabase } from "../test-helpers"; + +type Adapter = PgliteDatabaseAdapter | PgDatabaseAdapter; + +// Close the live PGlite client without going through adapter.close() (which +// flips the manager's shuttingDown flag and short-circuits withDatabase with a +// plain "shutting down" error). Closing only the raw connection leaves the +// shutdown gate open, so the next real query faults and exercises the adapter's +// own catch → ElizaError path — the actual behavior under a broken DB. +async function breakConnection(adapter: Adapter): Promise { + const raw = (adapter as PgliteDatabaseAdapter).getRawConnection?.() as PGlite | undefined; + if (!raw) throw new Error("test requires the PGlite adapter (getRawConnection)"); + await raw.close(); +} + +async function expectElizaError(fn: () => Promise, code: string): Promise { + let thrown: unknown; + try { + await fn(); + } catch (e) { + thrown = e; + } + expect(thrown, `expected a throw with code ${code}, got a normal return`).toBeDefined(); + expect(isElizaError(thrown), `expected ElizaError, got ${String(thrown)}`).toBe(true); + expect((thrown as ElizaError).code).toBe(code); + return thrown as ElizaError; +} + +describe("DB adapter fail-fast error paths (real broken PGlite)", () => { + let adapter: Adapter; + let cleanup: () => Promise; + + beforeEach(async () => { + const setup = await createIsolatedTestDatabase("db-failure-error-path"); + adapter = setup.adapter; + cleanup = setup.cleanup; + }, 60_000); + + afterEach(async () => { + // cleanup() calls adapter.close(); the raw connection may already be closed, + // which is tolerated by the J6 teardown handlers in the manager. + if (cleanup) await cleanup(); + }); + + it("countAgents throws DB_COUNT_FAILED instead of returning 0", async () => { + await breakConnection(adapter); + await expectElizaError(() => adapter.countAgents(), "DB_COUNT_FAILED"); + }); + + it("getCache throws DB_QUERY_FAILED instead of returning undefined (miss)", async () => { + await breakConnection(adapter); + const err = await expectElizaError(() => adapter.getCache("any-key"), "DB_QUERY_FAILED"); + // The typed error carries structured context, not a swallowed message. + expect(err.context).toMatchObject({ table: "cache" }); + expect(err.cause).toBeDefined(); + }); + + it("setCache throws DB_UPSERT_FAILED instead of returning false", async () => { + await breakConnection(adapter); + await expectElizaError(() => adapter.setCache("k", "v"), "DB_UPSERT_FAILED"); + }); + + it("deleteCache throws DB_DELETE_FAILED instead of returning false", async () => { + await breakConnection(adapter); + await expectElizaError(() => adapter.deleteCache("k"), "DB_DELETE_FAILED"); + }); + + it("deleteAgents throws DB_DELETE_FAILED instead of returning false", async () => { + await breakConnection(adapter); + await expectElizaError(() => adapter.deleteAgents([v4() as UUID]), "DB_DELETE_FAILED"); + }); + + it("createEntities throws DB_INSERT_FAILED instead of returning []", async () => { + const entity = { id: v4() as UUID, agentId: v4() as UUID, names: ["x"], metadata: {} }; + await breakConnection(adapter); + await expectElizaError(() => adapter.createEntities([entity]), "DB_INSERT_FAILED"); + }); + + it("updateMemory throws DB_UPDATE_FAILED instead of returning false", async () => { + await breakConnection(adapter); + await expectElizaError( + () => adapter.updateMemory({ id: v4() as UUID, content: { text: "x" } }), + "DB_UPDATE_FAILED" + ); + }); + + it("addParticipant throws DB_INSERT_FAILED instead of returning false", async () => { + await breakConnection(adapter); + await expectElizaError( + () => adapter.addParticipant(v4() as UUID, v4() as UUID), + "DB_INSERT_FAILED" + ); + }); + + it("createRelationship throws DB_INSERT_FAILED instead of returning false", async () => { + await breakConnection(adapter); + await expectElizaError( + () => + adapter.createRelationship({ + sourceEntityId: v4() as UUID, + targetEntityId: v4() as UUID, + }), + "DB_INSERT_FAILED" + ); + }); + + it("an API-style handler over the adapter surfaces a structured 5xx, not a fabricated 200/0", async () => { + await breakConnection(adapter); + + // Minimal J1 boundary: the shape a route handler uses — call the adapter, + // and on a thrown ElizaError produce a structured 500 body. A fabricated + // default (0) would instead sail through as a 200 and hide the outage. + const handler = async (): Promise<{ status: number; body: unknown }> => { + try { + const count = await adapter.countAgents(); + return { status: 200, body: { count } }; + } catch (error) { + if (isElizaError(error)) { + return { + status: 500, + body: { error: error.code, message: error.message }, + }; + } + return { status: 500, body: { error: "UNCLASSIFIED" } }; + } + }; + + const res = await handler(); + expect(res.status).toBe(500); + expect(res.body).toMatchObject({ error: "DB_COUNT_FAILED" }); + }); +}); diff --git a/plugins/plugin-sql/src/__tests__/integration/error-policy.test.ts b/plugins/plugin-sql/src/__tests__/integration/error-policy.test.ts index b69b2ef91a414..7164f4297d176 100644 --- a/plugins/plugin-sql/src/__tests__/integration/error-policy.test.ts +++ b/plugins/plugin-sql/src/__tests__/integration/error-policy.test.ts @@ -33,25 +33,22 @@ describe("SQL adapter error policy", () => { try { await dropTable(setup.adapter.getDatabase() as DrizzleDatabase, "agents"); - await expectElizaError(setup.adapter.countAgents(), "DB_COUNT_AGENTS_FAILED"); + await expectElizaError(setup.adapter.countAgents(), "DB_COUNT_FAILED"); } finally { await setup.cleanup(); } - }); + }, 60_000); it("throws a typed error when deleteAgents cannot write the agents table", async () => { const setup = await createIsolatedTestDatabase("error-policy-delete-agents"); try { await dropTable(setup.adapter.getDatabase() as DrizzleDatabase, "agents"); - await expectElizaError( - setup.adapter.deleteAgents([uuidv4() as UUID]), - "DB_DELETE_AGENTS_FAILED" - ); + await expectElizaError(setup.adapter.deleteAgents([uuidv4() as UUID]), "DB_DELETE_FAILED"); } finally { await setup.cleanup(); } - }); + }, 60_000); it("throws a typed error when createEntities cannot write the entities table", async () => { const setup = await createIsolatedTestDatabase("error-policy-create-entities"); @@ -63,11 +60,11 @@ describe("SQL adapter error policy", () => { agentId: setup.testAgentId, names: ["Error Policy Entity"], }; - await expectElizaError(setup.adapter.createEntities([entity]), "DB_CREATE_ENTITIES_FAILED"); + await expectElizaError(setup.adapter.createEntities([entity]), "DB_INSERT_FAILED"); } finally { await setup.cleanup(); } - }); + }, 60_000); it("throws a typed error when updateComponent cannot write the components table", async () => { const setup = await createIsolatedTestDatabase("error-policy-update-component"); @@ -85,12 +82,9 @@ describe("SQL adapter error policy", () => { data: { value: "boom" }, createdAt: Date.now(), }; - await expectElizaError( - setup.adapter.updateComponent(component), - "DB_UPDATE_COMPONENT_FAILED" - ); + await expectElizaError(setup.adapter.updateComponent(component), "DB_UPDATE_FAILED"); } finally { await setup.cleanup(); } - }); + }, 60_000); }); diff --git a/plugins/plugin-sql/src/base.ts b/plugins/plugin-sql/src/base.ts index 72b0684a16be0..1b3a8c2ca974e 100644 --- a/plugins/plugin-sql/src/base.ts +++ b/plugins/plugin-sql/src/base.ts @@ -473,6 +473,8 @@ export abstract class BaseDrizzleAdapter extends DatabaseAdapter { if (agentIds.length === 0) return true; return this.withDatabase(async () => { + // error-policy:J2 context-adding rethrow — a failed delete must not read + // as "nothing matched" (both would return false); surface it as a typed error. try { await this.db.delete(agentTable).where(inArray(agentTable.id, agentIds)); return true; } catch (error) { - logger.error( - { - src: "plugin:sql", - error: error instanceof Error ? error.message : String(error), - }, - "Failed to delete agents" - ); throw new ElizaError("deleteAgents failed", { - code: "DB_DELETE_AGENTS_FAILED", + code: "DB_DELETE_FAILED", cause: error, - context: { agentIds }, + context: { table: "agents", agentIds }, }); } }); @@ -698,6 +695,8 @@ export abstract class BaseDrizzleAdapter extends DatabaseAdapter { return this.withDatabase(async () => { - let result: Array<{ count: number }>; + // "DB broken" must never read as "0 agents": both a query failure and a + // missing count row surface as a typed DB_COUNT_FAILED. The aggregate + // always returns exactly one row, so a missing count is a broken pipeline. + let total: number | undefined; try { - result = await this.db.select({ count: count() }).from(agentTable); + const result = await this.db.select({ count: count() }).from(agentTable); + total = result[0]?.count; } catch (error) { - logger.error( - { - src: "plugin:sql", - error: error instanceof Error ? error.message : String(error), - }, - "Failed to count agents" - ); - throw new ElizaError("countAgents failed", { - code: "DB_COUNT_AGENTS_FAILED", + // error-policy:J2 context-adding rethrow — surface a query failure as a + // typed count error rather than letting a bare driver error escape. + throw new ElizaError("countAgents query failed", { + code: "DB_COUNT_FAILED", cause: error, context: { table: "agents" }, }); } - const total = result[0]?.count; if (typeof total !== "number") { throw new ElizaError("countAgents returned no count row", { - code: "DB_COUNT_AGENTS_FAILED", + code: "DB_COUNT_FAILED", context: { table: "agents" }, }); } @@ -946,19 +937,10 @@ export abstract class BaseDrizzleAdapter extends DatabaseAdapter { + // No catch: a delete failure propagates via withDatabase's retry layer; the + // previous log-then-rethrow added no context the retry layer doesn't log. return this.withDatabase(async () => { - try { - await this.db.delete(agentTable); - } catch (error) { - logger.error( - { - src: "plugin:sql", - error: error instanceof Error ? error.message : String(error), - }, - "Failed to clean up agent table" - ); - throw error; - } + await this.db.delete(agentTable); }); } @@ -1108,18 +1090,13 @@ export abstract class BaseDrizzleAdapter extends DatabaseAdapter entity.id as UUID); } catch (error) { - logger.error( - { - src: "plugin:sql", - entityId: entities[0]?.id, - error: error instanceof Error ? error.message : String(error), - }, - "Failed to create entities" - ); + // error-policy:J2 context-adding rethrow — a failed batch insert must + // not read as "created zero entities" (an empty return is a valid + // success for an empty input); surface the write failure. throw new ElizaError("createEntities failed", { - code: "DB_CREATE_ENTITIES_FAILED", + code: "DB_INSERT_FAILED", cause: error, - context: { entityIds: entities.map((entity) => entity.id).filter(Boolean) }, + context: { table: "entities", count: normalizedEntities.length }, }); } }); @@ -1132,33 +1109,19 @@ export abstract class BaseDrizzleAdapter extends DatabaseAdapter { if (!entity.id) { - logger.error({ src: "plugin:sql" }, "Entity ID is required for ensureEntityExists"); - return false; + throw new ElizaError("Entity ID is required for ensureEntityExists", { + code: "DB_INVALID_ARGUMENT", + context: { table: "entities" }, + }); } - try { - const existingEntities = await this.getEntitiesByIds([entity.id]); - - if (!existingEntities.length) { - return (await this.createEntities([entity])).length > 0; - } - - return true; - } catch (error) { - logger.error( - { - src: "plugin:sql", - entityId: entity.id, - error: error instanceof Error ? error.message : String(error), - }, - "Failed to ensure entity exists" - ); - throw new ElizaError("ensureEntityExists failed", { - code: "DB_ENSURE_ENTITY_FAILED", - cause: error, - context: { entityId: entity.id }, - }); + // No catch: a lookup/insert failure propagates so callers see a broken + // pipeline instead of a fabricated "could not ensure" (false). + const existingEntities = await this.getEntitiesByIds([entity.id]); + if (!existingEntities.length) { + return (await this.createEntities([entity])).length > 0; } + return true; } /** @@ -1416,19 +1379,13 @@ export abstract class BaseDrizzleAdapter extends DatabaseAdapter Array.isArray(row.embedding)); } catch (error) { - logger.error( - { - src: "plugin:sql", - tableName: opts.query_table_name, - fieldName: opts.query_field_name, - error: error instanceof Error ? error.message : String(error), - }, - "Failed to get cached embeddings" - ); + // error-policy:J3 untrusted-input sanitizing — an over-long query + // string exceeds levenshtein's 255-char ceiling, so no fuzzy cache + // match can exist for it: an empty result is the correct typed answer, + // not a masked failure. Every other error is a real fault → rethrow. if ( error instanceof Error && error.message === "levenshtein argument exceeds maximum length of 255 characters" ) { return []; } - throw error; + throw new ElizaError("getCachedEmbeddings failed", { + code: "DB_QUERY_FAILED", + cause: error, + context: { + table: opts.query_table_name, + field: opts.query_field_name, + }, + }); } }); } @@ -1925,17 +1884,19 @@ export abstract class BaseDrizzleAdapter extends DatabaseAdapter 0; return removed; } catch (error) { - logger.error( - { - src: "plugin:sql", - entityId, - roomId, - error: error instanceof Error ? error.message : String(error), - }, - "Failed to remove participant from room" - ); - return false; + // error-policy:J2 context-adding rethrow — false is the typed "no row + // matched" signal; a delete failure must not collapse into it. + throw new ElizaError("removeParticipant failed", { + code: "DB_DELETE_FAILED", + cause: error, + context: { table: "participants", entityId, roomId }, + }); } }); } @@ -3258,17 +3212,13 @@ export abstract class BaseDrizzleAdapter extends DatabaseAdapter 0; } catch (error) { - logger.error( - { - src: "plugin:sql", + // error-policy:J2 context-adding rethrow — false is the typed "already + // existed (onConflictDoNothing)" signal; an insert failure must not + // collapse into it. + throw new ElizaError("createRelationship failed", { + code: "DB_INSERT_FAILED", + cause: error, + context: { + table: "relationships", agentId: this.agentId, - error: error instanceof Error ? error.message : String(error), - saveParams, + sourceEntityId: params.sourceEntityId, + targetEntityId: params.targetEntityId, }, - "Error creating relationship" - ); - return false; + }); } }); } @@ -3336,16 +3289,16 @@ export abstract class BaseDrizzleAdapter extends DatabaseAdapter { + // error-policy:J4 explicit availability probe — false IS the designed answer + // to "can the DB serve a query?"; a failing SELECT 1 means not-ready. try { await this.db.execute(sql`SELECT 1`); return true; diff --git a/plugins/plugin-sql/src/index.browser.ts b/plugins/plugin-sql/src/index.browser.ts index b4369cadfd0d8..bb422f7b21632 100644 --- a/plugins/plugin-sql/src/index.browser.ts +++ b/plugins/plugin-sql/src/index.browser.ts @@ -119,6 +119,9 @@ export const plugin: Plugin = { const runtimeWithAdapter = runtime as IAgentRuntime & RuntimeWithAdapterRegistrar; logger.info({ src: "plugin:sql" }, "plugin-sql (browser) init starting"); + // error-policy:J4 capability probe — if readiness can't be determined (no + // adapter registered yet, so `isReady` is absent/throws), fall through to + // create one. A registered-and-ready adapter short-circuits above. try { const isReady = await runtime.isReady(); if (isReady) { diff --git a/plugins/plugin-sql/src/index.ts b/plugins/plugin-sql/src/index.ts index 638f9d813fb6a..42f55170da897 100644 --- a/plugins/plugin-sql/src/index.ts +++ b/plugins/plugin-sql/src/index.ts @@ -186,6 +186,8 @@ export const plugin: Plugin = { typeof runtimeWithAdapter.hasDatabaseAdapter === "function" ? runtimeWithAdapter.hasDatabaseAdapter() : (() => { + // error-policy:J4 capability probe — a throwing/absent accessor means + // "no adapter registered yet"; the init below then creates one. try { const existing = runtimeWithAdapter.getDatabaseAdapter?.() ?? diff --git a/plugins/plugin-sql/src/pglite/manager.ts b/plugins/plugin-sql/src/pglite/manager.ts index d556056071099..f1c15b4bca3a0 100644 --- a/plugins/plugin-sql/src/pglite/manager.ts +++ b/plugins/plugin-sql/src/pglite/manager.ts @@ -258,18 +258,29 @@ export class PGliteClientManager implements IDatabaseClientManager { if (this.writeBack.enabled) { try { await this.writeBack.flush(); - } catch {} + } catch (error) { + // error-policy:J6 best-effort teardown — a failed final flush must not + // abort close(); log at debug and continue tearing down. + logger.debug({ src: "plugin:sql", error: String(error) }, "close: write-back flush failed"); + } } // Drain any in-progress startSync before we tear down. if (this.startSyncMutex) { try { await this.startSyncMutex; - } catch {} + } catch (error) { + // error-policy:J6 best-effort teardown — a rejected in-flight startSync + // is irrelevant once we're closing; log at debug and continue. + logger.debug({ src: "plugin:sql", error: String(error) }, "close: startSync drain failed"); + } } if (this.syncUnsubscribe) { try { this.syncUnsubscribe(); - } catch {} + } catch (error) { + // error-policy:J6 best-effort teardown — unsubscribe failure is non-fatal. + logger.debug({ src: "plugin:sql", error: String(error) }, "close: sync unsubscribe failed"); + } this.syncUnsubscribe = null; } // Allow the sync extension's async teardown (network abort handlers, @@ -280,7 +291,11 @@ export class PGliteClientManager implements IDatabaseClientManager { if (this.client) { try { await this.client.close(); - } catch {} + } catch (error) { + // error-policy:J6 best-effort teardown — a failed client close still + // proceeds to release the data-dir lock so the writer slot is freed. + logger.debug({ src: "plugin:sql", error: String(error) }, "close: client close failed"); + } } this.releaseDataDirLock(); } @@ -367,11 +382,16 @@ export class PGliteClientManager implements IDatabaseClientManager { : null; return { pid, createdAt, bootId, processStartTicks }; } catch { + // error-policy:J3 untrusted-input parse — a missing/corrupt lock file + // yields the typed all-null "unknown" struct; the liveness check treats + // unknown conservatively (does not reclaim on guesswork). return { pid: null, createdAt: null, bootId: null, processStartTicks: null }; } } private readLinuxBootId(): string | null { + // error-policy:J3 optional-source probe — /proc is Linux-only and may be + // unreadable; null is the designed "couldn't determine" signal. try { const bootId = readFileSync("/proc/sys/kernel/random/boot_id", "utf-8").trim(); return bootId.length > 0 ? bootId : null; @@ -381,6 +401,8 @@ export class PGliteClientManager implements IDatabaseClientManager { } private readLinuxUptimeSeconds(): number | null { + // error-policy:J3 optional-source probe — /proc/uptime is Linux-only; null + // means "unavailable", not zero uptime. try { const raw = readFileSync("/proc/uptime", "utf-8").trim().split(/\s+/)[0]; const uptimeSeconds = Number.parseFloat(raw ?? ""); @@ -391,6 +413,8 @@ export class PGliteClientManager implements IDatabaseClientManager { } private readLinuxProcStartTicks(pid: number | "self"): string | null { + // error-policy:J3 optional-source probe — /proc//stat is Linux-only and + // absent once the process exits; null is the designed "unknown" signal. try { const stat = readFileSync(`/proc/${pid}/stat`, "utf-8"); const commEnd = stat.lastIndexOf(")"); @@ -593,14 +617,22 @@ export class PGliteClientManager implements IDatabaseClientManager { if (this.lockFd !== null) { try { closeSync(this.lockFd); - } catch {} + } catch (error) { + // error-policy:J6 best-effort teardown — a stale fd or double-close is + // harmless during lock release; drop the handle regardless. + logger.debug({ src: "plugin:sql", error: String(error) }, "lock: closeSync failed"); + } this.lockFd = null; } if (this.lockPath) { try { unlinkSync(this.lockPath); - } catch {} + } catch (error) { + // error-policy:J6 best-effort teardown — an already-removed lock file is + // fine; clear the path regardless. + logger.debug({ src: "plugin:sql", error: String(error) }, "lock: unlinkSync failed"); + } this.lockPath = null; } } @@ -622,7 +654,11 @@ export class PGliteClientManager implements IDatabaseClientManager { if (json && json !== "{}") { return json; } - } catch {} + } catch { + // error-policy:J3 untrusted-input sanitizing — a non-serializable value + // (circular ref, throwing getter) just means JSON isn't a usable + // representation; fall through to the toString/String strategies below. + } if (typeof obj.toString === "function") { const stringified = obj.toString.call(error); if (stringified && stringified !== "[object Object]") { @@ -825,7 +861,11 @@ export class PGliteClientManager implements IDatabaseClientManager { if (this.syncUnsubscribe) { try { this.syncUnsubscribe(); - } catch {} + } catch (error) { + // error-policy:J6 best-effort teardown — unsubscribe failure is non-fatal + // to a resync; we drop the handle and rebuild the stream below. + logger.debug({ src: "plugin:sql", error: String(error) }, "resync: unsubscribe failed"); + } this.syncUnsubscribe = null; // Let the sync extension drain in-flight network operations before we // drop the schema it depends on. A single setTimeout(0) is insufficient @@ -1126,7 +1166,15 @@ export class PGliteClientManager implements IDatabaseClientManager { ); try { await this.client.close(); - } catch {} + } catch (error) { + // error-policy:J6 best-effort teardown — closing the failed client + // before recreating it is best-effort; a close error must not block + // the retry that follows. + logger.debug( + { src: "plugin:sql", error: String(error) }, + "retry: stale client close failed" + ); + } this.client = this.createClient(this.options); try { diff --git a/plugins/plugin-sql/src/runtime-migrator/schema-transformer.ts b/plugins/plugin-sql/src/runtime-migrator/schema-transformer.ts index a9aa50dd96321..af8e160adfea3 100644 --- a/plugins/plugin-sql/src/runtime-migrator/schema-transformer.ts +++ b/plugins/plugin-sql/src/runtime-migrator/schema-transformer.ts @@ -155,8 +155,9 @@ function isPgTable(value: unknown): value is PgTable { return false; } - // instanceof doesn't work across module boundaries, so probe for the - // table config shape instead. + // error-policy:J3 type probe — instanceof doesn't work across module + // boundaries, so probe the table-config shape; getTableConfig throwing on a + // non-table value is the typed "not a PgTable" answer (false), not a fault. try { const config = getTableConfig(value as PgTable); return config && typeof config.name === "string"; diff --git a/plugins/plugin-sql/src/services/advanced-memory-storage.ts b/plugins/plugin-sql/src/services/advanced-memory-storage.ts index 737a7c8782ec5..8d9e19fb0dfc0 100644 --- a/plugins/plugin-sql/src/services/advanced-memory-storage.ts +++ b/plugins/plugin-sql/src/services/advanced-memory-storage.ts @@ -275,6 +275,9 @@ export class AdvancedMemoryStorageService extends Service implements MemoryStora if (!this.runtime.hasService(ENTITY_RESOLUTION_SERVICE)) { return null; } + // error-policy:J4 optional-collaborator probe — null is the designed + // "resolution service unavailable" signal; getIdentityGroup then degrades to + // a single-entity group. This is an optional enhancement, not a required dep. try { const loaded = await this.runtime.getServiceLoadPromise(ENTITY_RESOLUTION_SERVICE); return isEntityResolutionService(loaded) ? loaded : null; diff --git a/plugins/plugin-sql/src/stores/agent.store.ts b/plugins/plugin-sql/src/stores/agent.store.ts index a9d4eca2b7d23..3694542a6e124 100644 --- a/plugins/plugin-sql/src/stores/agent.store.ts +++ b/plugins/plugin-sql/src/stores/agent.store.ts @@ -4,7 +4,7 @@ * examples) and the runtime's `Agent` domain type. `update` deep-merges * `settings` with the existing row rather than overwriting it wholesale. */ -import { type Agent, logger, type UUID } from "@elizaos/core"; +import { type Agent, ElizaError, logger, type UUID } from "@elizaos/core"; import { count, eq } from "drizzle-orm"; import { documentsFromDb, @@ -75,15 +75,18 @@ export class AgentStore implements Store { bio: normalizeAgentBio(row.bio), })); }, "AgentStore.getAll"); - return result || []; + return result; } async create(agent: Agent): Promise { + if (!agent.name) { + throw new ElizaError("Cannot create agent without a name", { + code: "DB_INVALID_ARGUMENT", + context: { table: "agents", agentId: agent.id }, + }); + } return this.ctx.withRetry(async () => { try { - if (!agent.name) { - throw new Error("Cannot create agent without a name"); - } if (agent.id) { const existing = await this.db .select({ id: agentTable.id }) @@ -114,26 +117,26 @@ export class AgentStore implements Store { return true; } catch (error) { - logger.error( - { - src: "plugin:sql", - agentId: agent.id, - error: error instanceof Error ? error.message : String(error), - }, - "Failed to create agent" - ); - return false; + // error-policy:J2 context-adding rethrow — false is the typed "duplicate + // id" outcome above; a write failure must not collapse into it. + throw new ElizaError("AgentStore.create failed", { + code: "DB_INSERT_FAILED", + cause: error, + context: { table: "agents", agentId: agent.id }, + }); } }, "AgentStore.create"); } async update(agentId: UUID, agent: Partial): Promise { + if (!agentId) { + throw new ElizaError("Agent ID is required for update", { + code: "DB_INVALID_ARGUMENT", + context: { table: "agents" }, + }); + } return this.ctx.withRetry(async () => { try { - if (!agentId) { - throw new Error("Agent ID is required for update"); - } - await this.db.transaction(async (tx) => { if (agent.settings) { agent.settings = await this.mergeSettings(tx, agentId, agent.settings); @@ -177,15 +180,13 @@ export class AgentStore implements Store { return true; } catch (error) { - logger.error( - { - src: "plugin:sql", - agentId, - error: error instanceof Error ? error.message : String(error), - }, - "Failed to update agent" - ); - return false; + // error-policy:J2 context-adding rethrow — a failed update must not read + // as a benign false. + throw new ElizaError("AgentStore.update failed", { + code: "DB_UPDATE_FAILED", + cause: error, + context: { table: "agents", agentId }, + }); } }, "AgentStore.update"); } @@ -198,6 +199,7 @@ export class AgentStore implements Store { .where(eq(agentTable.id, agentId)) .returning(); + // false is the typed "no agent matched" outcome, distinct from failure. if (result.length === 0) { logger.warn({ src: "plugin:sql", agentId }, "Agent not found for deletion"); return false; @@ -205,51 +207,38 @@ export class AgentStore implements Store { return true; } catch (error) { - logger.error( - { - src: "plugin:sql", - agentId, - error: error instanceof Error ? error.message : String(error), - }, - "Failed to delete agent" - ); - throw error; + // error-policy:J2 context-adding rethrow — surface a real delete failure + // (the not-found case already returned false above). + throw new ElizaError("AgentStore.delete failed", { + code: "DB_DELETE_FAILED", + cause: error, + context: { table: "agents", agentId }, + }); } }, "AgentStore.delete"); } async count(): Promise { return this.ctx.withRetry(async () => { - try { - const result = await this.db.select({ count: count() }).from(agentTable); - return result[0]?.count || 0; - } catch (error) { - logger.error( - { - src: "plugin:sql", - error: error instanceof Error ? error.message : String(error), - }, - "Failed to count agents" - ); - return 0; + // No catch: "DB broken" must never read as "0 agents". The aggregate + // always returns one row, so a missing count is a broken pipeline. + const result = await this.db.select({ count: count() }).from(agentTable); + const total = result[0]?.count; + if (typeof total !== "number") { + throw new ElizaError("AgentStore.count returned no count row", { + code: "DB_COUNT_FAILED", + context: { table: "agents" }, + }); } + return total; }, "AgentStore.count"); } async deleteAll(): Promise { + // No catch: a delete failure propagates via withRetry; the previous + // log-then-rethrow added no context the retry layer doesn't log. return this.ctx.withRetry(async () => { - try { - await this.db.delete(agentTable); - } catch (error) { - logger.error( - { - src: "plugin:sql", - error: error instanceof Error ? error.message : String(error), - }, - "Failed to clean up agent table" - ); - throw error; - } + await this.db.delete(agentTable); }, "AgentStore.deleteAll"); } diff --git a/plugins/plugin-sql/src/stores/cache.store.ts b/plugins/plugin-sql/src/stores/cache.store.ts index 772d09e3137da..4bbf64442bc2e 100644 --- a/plugins/plugin-sql/src/stores/cache.store.ts +++ b/plugins/plugin-sql/src/stores/cache.store.ts @@ -1,5 +1,4 @@ /** Per-agent key/value cache store backed by the `cache` table (upsert on `set`, scoped by `agentId`). */ -import { logger } from "@elizaos/core"; import { and, eq } from "drizzle-orm"; import { cacheTable } from "../schema/index"; import type { DrizzleDatabase } from "../types"; @@ -13,86 +12,53 @@ export class CacheStore implements Store { } async get(key: string): Promise { + // No catch: undefined is the typed cache miss; a query failure propagates + // via withRetry so "DB broken" never reads as "not cached". return this.ctx.withRetry(async () => { - try { - const result = await this.db - .select({ value: cacheTable.value }) - .from(cacheTable) - .where(and(eq(cacheTable.agentId, this.ctx.agentId), eq(cacheTable.key, key))) - .limit(1); + const result = await this.db + .select({ value: cacheTable.value }) + .from(cacheTable) + .where(and(eq(cacheTable.agentId, this.ctx.agentId), eq(cacheTable.key, key))) + .limit(1); - if (result && result.length > 0 && result[0]) { - return result[0].value as T | undefined; - } - - return undefined; - } catch (error) { - logger.error( - { - src: "plugin:sql", - agentId: this.ctx.agentId, - error: error instanceof Error ? error.message : String(error), - key, - }, - "Error fetching cache" - ); - return undefined; + if (result && result.length > 0 && result[0]) { + return result[0].value as T | undefined; } + + return undefined; }, "CacheStore.get"); } async set(key: string, value: T): Promise { + // No catch: a write failure propagates via withRetry rather than reading as + // a benign false. return this.ctx.withRetry(async () => { - try { - await this.db - .insert(cacheTable) - .values({ - key: key, - agentId: this.ctx.agentId, - value: value, - }) - .onConflictDoUpdate({ - target: [cacheTable.key, cacheTable.agentId], - set: { value: value }, - }); + await this.db + .insert(cacheTable) + .values({ + key: key, + agentId: this.ctx.agentId, + value: value, + }) + .onConflictDoUpdate({ + target: [cacheTable.key, cacheTable.agentId], + set: { value: value }, + }); - return true; - } catch (error) { - logger.error( - { - src: "plugin:sql", - agentId: this.ctx.agentId, - error: error instanceof Error ? error.message : String(error), - key, - }, - "Error setting cache" - ); - return false; - } + return true; }, "CacheStore.set"); } async delete(key: string): Promise { + // No catch: a delete failure propagates via withRetry rather than reading as + // a benign false. return this.ctx.withRetry(async () => { - try { - await this.db.transaction(async (tx) => { - await tx - .delete(cacheTable) - .where(and(eq(cacheTable.agentId, this.ctx.agentId), eq(cacheTable.key, key))); - }); - return true; - } catch (error) { - logger.error( - { - src: "plugin:sql", - agentId: this.ctx.agentId, - error: error instanceof Error ? error.message : String(error), - key, - }, - "Error deleting cache" - ); - return false; - } + await this.db.transaction(async (tx) => { + await tx + .delete(cacheTable) + .where(and(eq(cacheTable.agentId, this.ctx.agentId), eq(cacheTable.key, key))); + }); + return true; }, "CacheStore.delete"); } } diff --git a/plugins/plugin-sql/src/stores/entity.store.ts b/plugins/plugin-sql/src/stores/entity.store.ts index 6f4a5e68a3bd5..1a6a60d9a5606 100644 --- a/plugins/plugin-sql/src/stores/entity.store.ts +++ b/plugins/plugin-sql/src/stores/entity.store.ts @@ -6,7 +6,7 @@ * builder. */ import { randomUUID } from "node:crypto"; -import { type Component, type Entity, logger, type UUID } from "@elizaos/core"; +import { type Component, ElizaError, type Entity, type UUID } from "@elizaos/core"; import { and, eq, inArray, or, sql } from "drizzle-orm"; import { componentTable, entityTable, participantTable } from "../schema/index"; import type { DrizzleDatabase } from "../types"; @@ -122,46 +122,41 @@ export class EntityStore implements Store { return true; }); } catch (error) { - logger.error( - { - src: "plugin:sql", - entityId: entities[0]?.id, - error: error instanceof Error ? error.message : String(error), - }, - "Failed to create entities" - ); - return false; + // error-policy:J2 context-adding rethrow — a failed insert must not read + // as a benign false. + throw new ElizaError("EntityStore.create failed", { + code: "DB_INSERT_FAILED", + cause: error, + context: { table: "entities", count: entities.length }, + }); } }, "EntityStore.create"); } async ensureExists(entity: Entity): Promise { if (!entity.id) { - logger.error({ src: "plugin:sql" }, "Entity ID is required for ensureExists"); - return false; + throw new ElizaError("Entity ID is required for ensureExists", { + code: "DB_INVALID_ARGUMENT", + context: { table: "entities" }, + }); } - try { - const existingEntities = await this.getByIds([entity.id]); - if (!existingEntities?.length) { - return await this.create([entity]); - } - return true; - } catch (error) { - logger.error( - { - src: "plugin:sql", - entityId: entity.id, - error: error instanceof Error ? error.message : String(error), - }, - "Failed to ensure entity exists" - ); - return false; + // No catch: a lookup/insert failure propagates so callers see a broken + // pipeline instead of a fabricated "could not ensure" (false). + const existingEntities = await this.getByIds([entity.id]); + if (!existingEntities?.length) { + return await this.create([entity]); } + return true; } async update(entity: Entity): Promise { - if (!entity.id) throw new Error("Entity ID is required for update"); + if (!entity.id) { + throw new ElizaError("Entity ID is required for update", { + code: "DB_INVALID_ARGUMENT", + context: { table: "entities" }, + }); + } return this.ctx.withRetry(async () => { const normalizedEntity = { diff --git a/plugins/plugin-sql/src/stores/log.store.ts b/plugins/plugin-sql/src/stores/log.store.ts index 8c16ba2603d46..a5417f56e2818 100644 --- a/plugins/plugin-sql/src/stores/log.store.ts +++ b/plugins/plugin-sql/src/stores/log.store.ts @@ -14,7 +14,7 @@ import type { RunStatus, UUID, } from "@elizaos/core"; -import { logger } from "@elizaos/core"; +import { ElizaError } from "@elizaos/core"; import { and, desc, eq, gte, lte, type SQL, sql } from "drizzle-orm"; import { logTable, roomTable } from "../schema"; import { sanitizeJsonObject } from "../utils"; @@ -66,17 +66,19 @@ export class LogStore implements Store { }); }); } catch (error) { - logger.error( - { - src: "plugin:sql", + // error-policy:J2 context-adding rethrow — a swallowed insert dropped the + // log entry silently; the caller decides whether a failed diagnostic write + // should be tolerated (J7), not this deep store method. + throw new ElizaError("LogStore.create failed", { + code: "DB_INSERT_FAILED", + cause: error, + context: { + table: "logs", type: params.type, roomId: params.roomId, entityId: params.entityId, - error: error instanceof Error ? error.message : String(error), }, - "Failed to create log entry" - ); - return; + }); } } diff --git a/plugins/plugin-sql/src/stores/memory.store.ts b/plugins/plugin-sql/src/stores/memory.store.ts index 2cb5235bce8e8..f43882d086d56 100644 --- a/plugins/plugin-sql/src/stores/memory.store.ts +++ b/plugins/plugin-sql/src/stores/memory.store.ts @@ -6,7 +6,7 @@ * messages, long-term memories, etc.) within the same physical table. */ import { randomUUID } from "node:crypto"; -import { logger, type Memory, type MemoryMetadata, type UUID } from "@elizaos/core"; +import { ElizaError, type Memory, type MemoryMetadata, type UUID } from "@elizaos/core"; import { and, cosineDistance, desc, eq, gte, inArray, lte, sql } from "drizzle-orm"; import { embeddingTable, memoryTable } from "../schema/index"; import type { DrizzleDatabase } from "../types"; @@ -164,20 +164,17 @@ export class MemoryStore implements Store { const memory = memoryResult[0]; - // Fetch embedding separately - let embedding: number[] | undefined; - try { - const embeddingCol = this.ctx.getEmbeddingDimension(); - const embeddingResult = await this.db - .select({ embedding: embeddingTable[embeddingCol] }) - .from(embeddingTable) - .where(eq(embeddingTable.memoryId, id)) - .limit(1); - - embedding = embeddingResult[0]?.embedding ?? undefined; - } catch { - embedding = undefined; - } + // Fetch embedding separately. No catch: `?? undefined` already handles the + // "no embedding row" case; a query failure propagates via withRetry rather + // than masquerading as a memory with no embedding. + const embeddingCol = this.ctx.getEmbeddingDimension(); + const embeddingResult = await this.db + .select({ embedding: embeddingTable[embeddingCol] }) + .from(embeddingTable) + .where(eq(embeddingTable.memoryId, id)) + .limit(1); + + const embedding: number[] | undefined = embeddingResult[0]?.embedding ?? undefined; return { id: memory.id as UUID, @@ -386,15 +383,13 @@ export class MemoryStore implements Store { return true; } catch (error) { - logger.error( - { - src: "plugin:sql", - memoryId: memory.id, - error: error instanceof Error ? error.message : String(error), - }, - "Failed to update memory" - ); - return false; + // error-policy:J2 context-adding rethrow — a failed memory update must + // not read as a benign false. + throw new ElizaError("MemoryStore.update failed", { + code: "DB_UPDATE_FAILED", + cause: error, + context: { table: "memories", memoryId: memory.id }, + }); } }, "MemoryStore.update"); } @@ -463,7 +458,16 @@ export class MemoryStore implements Store { .from(memoryTable) .where(and(...conditions)); - return Number(result[0]?.count ?? 0); + // count(*) always returns one row; a missing count is a broken pipeline, + // not "0 memories" — throw rather than fabricate zero. + const total = result[0]?.count; + if (total == null) { + throw new ElizaError("MemoryStore.count returned no count row", { + code: "DB_COUNT_FAILED", + context: { table: "memories", roomId, tableName: resolvedTableName }, + }); + } + return Number(total); }, "MemoryStore.count"); } diff --git a/plugins/plugin-sql/src/stores/participant.store.ts b/plugins/plugin-sql/src/stores/participant.store.ts index df832f186c235..46c96fabb3c1f 100644 --- a/plugins/plugin-sql/src/stores/participant.store.ts +++ b/plugins/plugin-sql/src/stores/participant.store.ts @@ -3,7 +3,7 @@ * scoped to the current agent, plus a per-(room, entity) follow/mute state * (`roomState`). */ -import { logger, type UUID } from "@elizaos/core"; +import { ElizaError, type UUID } from "@elizaos/core"; import { and, eq, inArray } from "drizzle-orm"; import { participantTable, roomTable } from "../schema/index"; import type { DrizzleDatabase } from "../types"; @@ -70,17 +70,13 @@ export class ParticipantStore implements Store { } return true; } catch (error) { - logger.error( - { - src: "plugin:sql", - entityId, - roomId, - agentId: this.ctx.agentId, - error: error instanceof Error ? error.message : String(error), - }, - "Failed to add participant to room" - ); - return false; + // error-policy:J2 context-adding rethrow — insert-if-absent only returns + // true on success, so false here masked a real write failure. + throw new ElizaError("ParticipantStore.add failed", { + code: "DB_INSERT_FAILED", + cause: error, + context: { table: "participants", entityId, roomId, agentId: this.ctx.agentId }, + }); } }, "ParticipantStore.add"); } @@ -110,16 +106,18 @@ export class ParticipantStore implements Store { } return true; } catch (error) { - logger.error( - { - src: "plugin:sql", + // error-policy:J2 context-adding rethrow — insert-if-absent only returns + // true on success, so false here masked a real write failure. + throw new ElizaError("ParticipantStore.addMany failed", { + code: "DB_INSERT_FAILED", + cause: error, + context: { + table: "participants", roomId, agentId: this.ctx.agentId, - error: error instanceof Error ? error.message : String(error), + count: entityIds.length, }, - "Failed to add participants to room" - ); - return false; + }); } }, "ParticipantStore.addMany"); } @@ -137,16 +135,13 @@ export class ParticipantStore implements Store { }); return result.length > 0; } catch (error) { - logger.error( - { - src: "plugin:sql", - entityId, - roomId, - error: error instanceof Error ? error.message : String(error), - }, - "Failed to remove participant from room" - ); - return false; + // error-policy:J2 context-adding rethrow — false is the typed "no row + // matched" signal; a delete failure must not collapse into it. + throw new ElizaError("ParticipantStore.remove failed", { + code: "DB_DELETE_FAILED", + cause: error, + context: { table: "participants", entityId, roomId }, + }); } }, "ParticipantStore.remove"); } @@ -212,17 +207,13 @@ export class ParticipantStore implements Store { ); }); } catch (error) { - logger.error( - { - src: "plugin:sql", - roomId, - entityId, - state, - error: error instanceof Error ? error.message : String(error), - }, - "Failed to set participant follow state" - ); - throw error; + // error-policy:J2 context-adding rethrow — attach the participant/state + // context to the surfaced failure. + throw new ElizaError("ParticipantStore.setUserState failed", { + code: "DB_UPDATE_FAILED", + cause: error, + context: { table: "participants", roomId, entityId, state }, + }); } }, "ParticipantStore.setUserState"); } diff --git a/plugins/plugin-sql/src/stores/relationship.store.ts b/plugins/plugin-sql/src/stores/relationship.store.ts index 28d60731efe82..9f269bcee4a90 100644 --- a/plugins/plugin-sql/src/stores/relationship.store.ts +++ b/plugins/plugin-sql/src/stores/relationship.store.ts @@ -5,7 +5,7 @@ * cover the `&&` array-overlap operator used here. */ import { randomUUID } from "node:crypto"; -import { logger, type Metadata, type Relationship, type UUID } from "@elizaos/core"; +import { ElizaError, type Metadata, type Relationship, type UUID } from "@elizaos/core"; import { and, eq, type SQL, sql } from "drizzle-orm"; import { relationshipTable } from "../schema/index"; import type { DrizzleDatabase } from "../types"; @@ -42,16 +42,19 @@ export class RelationshipStore implements Store { .returning(); return inserted.length > 0; } catch (error) { - logger.error( - { - src: "plugin:sql", + // error-policy:J2 context-adding rethrow — false is the typed "already + // existed (onConflictDoNothing)" signal; an insert failure must not + // collapse into it. + throw new ElizaError("RelationshipStore.create failed", { + code: "DB_INSERT_FAILED", + cause: error, + context: { + table: "relationships", agentId: this.ctx.agentId, - error: error instanceof Error ? error.message : String(error), - saveParams, + sourceEntityId: params.sourceEntityId, + targetEntityId: params.targetEntityId, }, - "Error creating relationship" - ); - return false; + }); } }, "RelationshipStore.create"); } @@ -67,16 +70,16 @@ export class RelationshipStore implements Store { }) .where(eq(relationshipTable.id, relationship.id)); } catch (error) { - logger.error( - { - src: "plugin:sql", + // error-policy:J2 context-adding rethrow — attach relationship context. + throw new ElizaError("RelationshipStore.update failed", { + code: "DB_UPDATE_FAILED", + cause: error, + context: { + table: "relationships", agentId: this.ctx.agentId, - error: error instanceof Error ? error.message : String(error), relationshipId: relationship.id, }, - "Error updating relationship" - ); - throw error; + }); } }, "RelationshipStore.update"); }