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
23 changes: 23 additions & 0 deletions docs/data.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,26 @@ The local workspace runs without any database. The account database matters only
```

Never point `OWNER_URL` or the seed at the production database. `tests/local-database.test.ts` keeps this section and the seed in step with the migrations; it reads the files as text and needs no database server. What is not covered here: the app talking to this database end to end, which needs Clerk sign-in.

## When analyses answer "Pencatat batas pemakaian belum tersedia"

In Clerk mode every analysis first counts against the daily quota and the shared budget in the account database (`src/lib/aadi/limits.ts`). When that count cannot be made, the analysis is refused with 503 `LIMITS_UNAVAILABLE` and nothing runs. The readiness probe (`GET /api/aadi`) only checks that `SENTRAPEDIA_DATABASE_URL` and `SENTRAPEDIA_USER_DAILY_ANALYSES` are set, not that the database answers, so it can report `ready: true` while every analysis is refused.

Each refusal writes one log line `{"event":"aadi.limits","level":"error","stage":"admit","code":"…"}` with no case text. The code says what to fix:

| `code` | Meaning | Fix |
| --- | --- | --- |
| `NO_STORE` | `SENTRAPEDIA_DATABASE_URL` is not set in the running container. | Set it to the pooled URL of the `sentrapedia_runtime` role and restart. |
| `NO_PRINCIPAL` | The signed-in session has no usable account id. | Check the Clerk instance and keys; this should not happen with Clerk's own ids. |
| `42P01` | A table is missing: a migration was not applied to this database. | Apply the missing files of `db/migrations/` in name order as the owner role, never as the runtime role. |
| `42501` | The runtime role lacks a grant on a table. | Re-apply the migration that creates the table; its `grant` gives the role access. |
| `28P01`, `28000` | The runtime role's password or name is wrong. | Correct the URL, or reset the password as the owner. |
| `ENOTFOUND`, `ECONNREFUSED`, `ETIMEDOUT` | The container cannot reach the database host. | Check the host in the URL and the server's outbound network. |
| `UNKNOWN` | Any other failure. | Read the database's own logs for the same minute. |

To check which tables exist, run this in the database's SQL editor. Every row should say `true`:

```sql
select t, to_regclass('public.' || t) is not null as present
from unnest(array['profile', 'personal_template', 'workspace_sync', 'analysis_usage', 'analysis_budget_day', 'output_report', 'workspace_feedback']) as t;
```
23 changes: 18 additions & 5 deletions src/lib/aadi/limits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,16 @@ const refusals = {
const refuse = (code: keyof typeof refusals): LimitRefusal => ({ ok: false, code, status: refusals[code][0], message: refusals[code][1] });
const micro = (usd: number) => Math.round(usd * 1e6) / 1e6;

/**
* Why the store failed, in a form safe to log: a Postgres SQLSTATE (42P01 missing table, 42501 permission, 28P01
* password) or a Node network code (ENOTFOUND, ECONNREFUSED, ETIMEDOUT). Never the error message, which can name the
* host, the role or a value. docs/data.md maps the codes to their fixes.
*/
export function storeFailureCode(error: unknown): string {
const code = error && typeof error === "object" && "code" in error ? (error as { code: unknown }).code : undefined;
return typeof code === "string" && /^[A-Z0-9_]{2,32}$/.test(code) ? code : "UNKNOWN";
}

/** The daily quota as configured: a whole number from 1 to 9999, or null when it is unset or unusable. */
export function parseDailyQuota(value: string | undefined): number | null {
return value !== undefined && /^[1-9]\d{0,3}$/.test(value.trim()) ? Number(value.trim()) : null;
Expand All @@ -50,18 +60,21 @@ export function createAnalysisLimits(options: { store?: LimitsStore; quota: stri
const quota = parseDailyQuota(options.quota);
if (!options.store || !principal || quota === null) return null;
try { return { used: await options.store.used(principal, now().toISOString().slice(0, 10)), quota }; }
catch { log({ event: "aadi.limits", level: "error", stage: "usage" }); return null; }
catch (error) { log({ event: "aadi.limits", level: "error", stage: "usage", code: storeFailureCode(error) }); return null; }
},
async admit(principal) {
const store = options.store;
if (!store || !principal) return refuse("LIMITS_UNAVAILABLE");
if (!store || !principal) {
log({ event: "aadi.limits", level: "error", stage: "admit", code: store ? "NO_PRINCIPAL" : "NO_STORE" });
return refuse("LIMITS_UNAVAILABLE");
}
const quota = parseDailyQuota(options.quota);
if (quota === null) return refuse("QUOTA_NOT_SET");
if (!(options.dailyBudgetUsd > 0) || options.holdUsd > options.dailyBudgetUsd) return refuse("BUDGET_EXHAUSTED");
const day = now().toISOString().slice(0, 10);
let outcome: Awaited<ReturnType<LimitsStore["admit"]>>;
try { outcome = await store.admit(principal, day, quota, options.holdUsd, options.dailyBudgetUsd); }
catch { log({ event: "aadi.limits", level: "error", stage: "admit" }); return refuse("LIMITS_UNAVAILABLE"); }
catch (error) { log({ event: "aadi.limits", level: "error", stage: "admit", code: storeFailureCode(error) }); return refuse("LIMITS_UNAVAILABLE"); }
if (outcome !== "admitted") return refuse(outcome === "quota" ? "QUOTA_EXCEEDED" : "BUDGET_EXHAUSTED");
let settled = false;
return { ok: true, settle: async (spentUsd, completed) => {
Expand All @@ -71,10 +84,10 @@ export function createAnalysisLimits(options: { store?: LimitsStore; quota: stri
try {
const state = await store.settle(principal, day, options.holdUsd, spent, completed, micro(options.dailyBudgetUsd * BUDGET_ALERT_FRACTION));
if (state.alert) log({ event: "aadi.budget", level: "alert", day, spentUsd: micro(state.spentUsd), limitUsd: options.dailyBudgetUsd });
} catch {
} catch (error) {
// The answer already exists and is returned. A hold that was not released keeps counting until the day
// turns, so this failure can only make the budget stricter, never looser.
log({ event: "aadi.limits", level: "error", stage: "settle" });
log({ event: "aadi.limits", level: "error", stage: "settle", code: storeFailureCode(error) });
}
} };
},
Expand Down
30 changes: 24 additions & 6 deletions tests/aadi-limits.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { createAnalysisLimits, createMemoryLimitsStore, type LimitsStore } from "../src/lib/aadi/limits";
import { createAnalysisLimits, createMemoryLimitsStore, storeFailureCode, type LimitsStore } from "../src/lib/aadi/limits";

// Gated beta (Gaffer, 2026-11-17): a daily quota per person and one shared daily budget that stops new analyses
// at 100% and raises an alert at 80%. The memory store used here follows the same rules as the SQL store
Expand Down Expand Up @@ -63,29 +63,47 @@ describe("configuration that would switch the guard off refuses instead", () =>
expect(await limits.admit("user_a")).toMatchObject({ ok: false, code: "QUOTA_NOT_SET", status: 503 });
});

it("refuses when no store is configured", async () => {
const { limits } = setup({ store: undefined });
it("refuses when no store is configured, and says so in the log", async () => {
const { limits, events } = setup({ store: undefined });
expect(await limits.admit("user_a")).toMatchObject({ ok: false, code: "LIMITS_UNAVAILABLE", status: 503 });
expect(events).toEqual([{ event: "aadi.limits", level: "error", stage: "admit", code: "NO_STORE" }]);
});

it("refuses when the store fails, and never runs the analysis unguarded", async () => {
const broken: LimitsStore = { admit: async () => { throw new Error("connection refused"); }, settle: async () => ({ alert: false, spentUsd: 0 }), used: async () => 0 };
const { limits, events } = setup({ store: broken });
expect(await limits.admit("user_a")).toMatchObject({ ok: false, code: "LIMITS_UNAVAILABLE", status: 503 });
expect(events).toEqual([{ event: "aadi.limits", level: "error", stage: "admit" }]);
expect(events).toEqual([{ event: "aadi.limits", level: "error", stage: "admit", code: "UNKNOWN" }]);
});

it("logs the database's error code, never its message, so the operator can tell a missing table from a network fault", async () => {
const failure = Object.assign(new Error('relation "analysis_usage" does not exist on host db.example'), { code: "42P01" });
const broken: LimitsStore = { admit: async () => { throw failure; }, settle: async () => ({ alert: false, spentUsd: 0 }), used: async () => { throw failure; } };
const { limits, events } = setup({ store: broken });
expect(await limits.admit("user_a")).toMatchObject({ ok: false, code: "LIMITS_UNAVAILABLE", status: 503 });
expect(await limits.usage("user_a")).toBeNull();
expect(events).toEqual([{ event: "aadi.limits", level: "error", stage: "admit", code: "42P01" }, { event: "aadi.limits", level: "error", stage: "usage", code: "42P01" }]);
expect(JSON.stringify(events)).not.toMatch(/relation|host|example/);
});

it("ignores an error code that is not a plain code", async () => {
expect(storeFailureCode(Object.assign(new Error("x"), { code: "postgres://user:secret@host" }))).toBe("UNKNOWN");
expect(storeFailureCode("ECONNREFUSED")).toBe("UNKNOWN");
expect(storeFailureCode(Object.assign(new Error("x"), { code: "ECONNREFUSED" }))).toBe("ECONNREFUSED");
});

it("refuses a caller without a principal", async () => {
const { limits } = setup();
const { limits, events } = setup();
expect(await limits.admit(undefined)).toMatchObject({ ok: false, code: "LIMITS_UNAVAILABLE" });
expect(events).toEqual([{ event: "aadi.limits", level: "error", stage: "admit", code: "NO_PRINCIPAL" }]);
});

it("keeps the answer when settling fails, and logs it without any case text", async () => {
const store = createMemoryLimitsStore();
const flaky: LimitsStore = { admit: store.admit, settle: async () => { throw new Error("timeout"); }, used: store.used };
const { limits, events } = setup({ store: flaky });
await expect((await admitted(limits)).settle(0.01, true)).resolves.toBeUndefined();
expect(events).toEqual([{ event: "aadi.limits", level: "error", stage: "settle" }]);
expect(events).toEqual([{ event: "aadi.limits", level: "error", stage: "settle", code: "UNKNOWN" }]);
});
});

Expand Down
Loading