Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions plugins/plugin-local-storage/src/services/local-storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
8 changes: 6 additions & 2 deletions plugins/plugin-localdb/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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<void> {
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<unknown>, code: string): Promise<ElizaError> {
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<void>;

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" });
});
});
22 changes: 8 additions & 14 deletions plugins/plugin-sql/src/__tests__/integration/error-policy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand All @@ -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");
Expand All @@ -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);
});
Loading
Loading