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
42 changes: 42 additions & 0 deletions backend/src/knowledge/list-cursor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/**
* The `cursor` of `GET /api/knowledge`: a record page's last sort key, as
* opaque base64url text. The key is the list order, pinned first, then newest
* first (see `listRecordPage` in ./store).
*/
import type { RecordPageCursor } from "./store";

const MAX_CURSOR_LENGTH = 512;
/** 9999-12-31T23:59:59.999999Z, the last instant Postgres timestamps reach in this form. */
const MAX_CURSOR_MICROSECONDS = 253_402_300_799_999_999n;
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

export function encodeRecordPageCursor(cursor: RecordPageCursor): string {
return Buffer.from(
JSON.stringify([cursor.pinned, cursor.createdAtMicros, cursor.id]),
"utf8",
).toString("base64url");
}

/** Decode a cursor from `encodeRecordPageCursor`; null for anything else. */
export function parseRecordPageCursor(value: string): RecordPageCursor | null {
if (!value || value.length > MAX_CURSOR_LENGTH || !/^[A-Za-z0-9_-]+$/.test(value)) return null;
let decoded: unknown;
try {
decoded = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
} catch {
return null;
}
if (!Array.isArray(decoded) || decoded.length !== 3) return null;
const [pinned, createdAtMicros, id] = decoded as unknown[];
if (
typeof pinned !== "boolean" ||
typeof createdAtMicros !== "string" ||
!/^[0-9]{1,18}$/.test(createdAtMicros) ||
BigInt(createdAtMicros) > MAX_CURSOR_MICROSECONDS ||
typeof id !== "string" ||
!UUID_RE.test(id)
) {
return null;
}
return { pinned, createdAtMicros, id };
}
16 changes: 13 additions & 3 deletions backend/src/knowledge/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ import {
type ExtractedDocument,
} from "./extract-text";
import { ingestOne, IngestValidationError } from "./ingest";
import { encodeRecordPageCursor, parseRecordPageCursor } from "./list-cursor";
import {
deleteRecord,
listRecords,
listRecordPage,
searchRecords,
setPinned,
type KnowledgeRow,
Expand Down Expand Up @@ -165,15 +166,24 @@ knowledgeRoutes.post("/upload", knowledgeUploadBodyLimit, async (c) => {
});

// GET /api/knowledge — org records, pinned first, newest first; optional ?q= keyword filter.
// Pages: `limit` (1-500, default 200), and `next_cursor` sent back as `?cursor=`
// with the same `q` and `limit` for the next page.
knowledgeRoutes.get("/", async (c) => {
const q = c.req.query("q");
const requestedLimit = Number.parseInt(c.req.query("limit") ?? "", 10);
const limit = Number.isFinite(requestedLimit) ? requestedLimit : undefined;
const rawCursor = c.req.query("cursor");
const cursor = rawCursor === undefined ? null : parseRecordPageCursor(rawCursor);
if (rawCursor !== undefined && !cursor) return c.json({ error: "cursor is invalid" }, 400);
try {
const rows = await listRecords({ orgId: c.get("orgId"), q });
const page = await listRecordPage({ orgId: c.get("orgId"), q, limit, cursor });
// `embeddings` is the observed truth (key present AND the provider answered
// last time); `search_note` explains a keyword-only state to the page.
const unavailable = embeddingsUnavailableReason();
return c.json({
records: rows.map(toApi),
records: page.rows.map(toApi),
has_more: page.nextCursor !== null,
next_cursor: page.nextCursor ? encodeRecordPageCursor(page.nextCursor) : null,
embeddings: unavailable === null,
search_note: unavailable === null ? null : `Search is keyword-only: ${unavailable}.`,
});
Expand Down
54 changes: 48 additions & 6 deletions backend/src/knowledge/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,18 +274,60 @@ const ROW_COLS = sql`
visibility, created_at, updated_at
`;

/** List org records, newest first, pinned first; optional tsvector keyword filter. */
export async function listRecords(opts: { orgId: string; q?: string; limit?: number }): Promise<KnowledgeRow[]> {
/** Where a page of the record list stopped: the last row's full sort key. The
* creation time is whole microseconds since the epoch (a decimal string), the
* precision Postgres stores, so records created in the same millisecond are
* neither repeated nor skipped. */
export interface RecordPageCursor {
readonly pinned: boolean;
readonly createdAtMicros: string;
readonly id: string;
}

export interface RecordPage {
readonly rows: KnowledgeRow[];
/** Pass back as `cursor` for the next page; null on the last page. */
readonly nextCursor: RecordPageCursor | null;
}

/** One page of org records, pinned first, then newest first (id breaks ties),
* after `cursor` when given; optional tsvector keyword filter. */
export async function listRecordPage(opts: {
orgId: string;
q?: string;
limit?: number;
cursor?: RecordPageCursor | null;
}): Promise<RecordPage> {
await ready();
const limit = Math.max(1, Math.min(opts.limit ?? 200, 500));
const q = opts.q?.trim();
return sql<KnowledgeRow[]>`
SELECT ${ROW_COLS} FROM knowledge_records
const cursor = opts.cursor ?? null;
// Every key sorts descending, so "after the cursor" is a row-value less-than.
const rows = await sql<(KnowledgeRow & { cursor_created_at_micros: string })[]>`
SELECT ${ROW_COLS},
((extract(epoch from created_at) * 1000000)::bigint)::text AS cursor_created_at_micros
FROM knowledge_records
WHERE org_id = ${opts.orgId}
${q ? sql`AND tsv @@ ${tsQuery(q)}` : sql``}
ORDER BY pinned DESC, created_at DESC
LIMIT ${limit}
${cursor
? sql`AND (pinned, created_at, id) < (
${cursor.pinned},
'epoch'::timestamptz + ${cursor.createdAtMicros}::bigint * interval '1 microsecond',
${cursor.id}::uuid
)`
: sql``}
ORDER BY pinned DESC, created_at DESC, id DESC
LIMIT ${limit + 1}
`;
const page = rows.slice(0, limit);
const last = page.at(-1);
return {
rows: page.map(({ cursor_created_at_micros: _key, ...row }) => row),
nextCursor:
rows.length > limit && last
? { pinned: last.pinned, createdAtMicros: last.cursor_created_at_micros, id: last.id }
: null,
};
}

export async function getRecord(orgId: string, id: string): Promise<KnowledgeRow | null> {
Expand Down
174 changes: 174 additions & 0 deletions backend/test/knowledge-pages.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
import { describe, expect, test } from "bun:test";
import { ready, sql } from "../src/knowledge/store";
import { createOrgSession, json } from "./helpers";

// Paging `GET /api/knowledge` (the Knowledge page) with `cursor` and
// `next_cursor`, through the real route and database. The expected order comes
// from Postgres directly, never from the code under test.

interface RecordsPage {
records: Array<{ id: string; title: string; pinned: boolean }>;
has_more: boolean;
next_cursor: string | null;
}

/** `count` records in `orgId`, one second apart and newest last by index,
* except that indices in `sameInstant` share one timestamp exactly and those in
* `microApart` sit one microsecond apart. `pinned` indices are pinned. */
async function seedRecords(
orgId: string,
count: number,
options: {
pinned?: ReadonlySet<number>;
sameInstant?: readonly [number, number];
microApart?: readonly [number, number];
title?: (index: number) => string;
} = {},
): Promise<void> {
await ready();
const base = new Date(Date.now() - 3_600_000).toISOString();
for (let index = 0; index < count; index += 1) {
const [sameFrom, sameTo] = options.sameInstant ?? [-1, -1];
const [microFrom, microTo] = options.microApart ?? [-1, -1];
const at =
index >= sameFrom && index <= sameTo
? sql`${base}::timestamptz + ${sameFrom}::int * interval '1 second'`
: index >= microFrom && index <= microTo
? sql`${base}::timestamptz + ${microFrom}::int * interval '1 second'
+ ${index - microFrom}::int * interval '1 microsecond'`
: sql`${base}::timestamptz + ${index}::int * interval '1 second'`;
await sql`
INSERT INTO knowledge_records (
org_id, kind, title, body, external_id, connector_instance_id,
content_hash, distillation_key, pinned, created_at, updated_at
) VALUES (
${orgId}, 'note', ${options.title?.(index) ?? `Record ${index}`}, 'Body text.',
${`record-${index}`}, 'test:pages', ${`hash-${index}`}, ${`key-${index}`},
${options.pinned?.has(index) ?? false}, ${at}, ${at}
)
`;
}
}

async function expectedOrder(orgId: string): Promise<string[]> {
const rows = await sql<{ id: string }[]>`
SELECT id FROM knowledge_records WHERE org_id = ${orgId}
ORDER BY pinned DESC, created_at DESC, id DESC
`;
return rows.map((row) => row.id);
}

async function readPages(path: string, cookies: string): Promise<RecordsPage[]> {
const pages: RecordsPage[] = [];
let cursor: string | null = null;
do {
const url: string = cursor ? `${path}&cursor=${encodeURIComponent(cursor)}` : path;
const response = await json<RecordsPage>(url, { cookies });
expect(response.status, JSON.stringify(response.body)).toBe(200);
expect(response.body.has_more).toBe(response.body.next_cursor !== null);
pages.push(response.body);
cursor = response.body.next_cursor;
expect(pages.length).toBeLessThanOrEqual(60);
} while (cursor);
return pages;
}

describe("knowledge record pages", () => {
test("record 201 is on the second page, pinned records first, none repeated or missing", async () => {
const session = await createOrgSession("knowledge-pages");
await seedRecords(session.orgId, 230, { pinned: new Set([3, 150]) });
const expected = await expectedOrder(session.orgId);

const first = await json<RecordsPage>("/api/knowledge", { cookies: session.cookies });
expect(first.body.records).toHaveLength(200);
expect(first.body.records.slice(0, 2).map((record) => record.title)).toEqual([
"Record 150",
"Record 3",
]);
expect(first.body.has_more).toBe(true);
// The oldest unpinned records, past the newest 200, were out of reach before.
expect(first.body.records.map((record) => record.title)).not.toContain("Record 0");

const pages = await readPages("/api/knowledge?limit=200", session.cookies);
expect(pages.map((page) => page.records.length)).toEqual([200, 30]);
const titles = pages.flatMap((page) => page.records.map((record) => record.title));
expect(titles[200]).toBe("Record 30");
expect(titles.at(-1)).toBe("Record 0");
expect(pages.flatMap((page) => page.records.map((record) => record.id))).toEqual(expected);
});

test("a page cut inside equal and microsecond-apart creation times keeps the id order", async () => {
const session = await createOrgSession("knowledge-page-ties");
await seedRecords(session.orgId, 40, {
pinned: new Set([5, 6, 7]),
sameInstant: [10, 19],
microApart: [25, 32],
});
const expected = await expectedOrder(session.orgId);
for (const limit of [1, 4, 7]) {
const pages = await readPages(`/api/knowledge?limit=${limit}`, session.cookies);
expect(pages.flatMap((page) => page.records.map((record) => record.id))).toEqual(expected);
}
});

test("a keyword filter pages too", async () => {
const session = await createOrgSession("knowledge-page-filter");
await seedRecords(session.orgId, 30, {
title: (index) => (index % 3 === 0 ? `Heron migration ${index}` : `Record ${index}`),
});
const pages = await readPages("/api/knowledge?q=heron&limit=4", session.cookies);
expect(pages.map((page) => page.records.length)).toEqual([4, 4, 2]);
expect(pages.flatMap((page) => page.records.map((record) => record.title))).toEqual(
[27, 24, 21, 18, 15, 12, 9, 6, 3, 0].map((index) => `Heron migration ${index}`),
);
});

test("limit is held between 1 and 500, and a non-number gives 200", async () => {
const session = await createOrgSession("knowledge-page-limit");
await seedRecords(session.orgId, 3);
const one = await json<RecordsPage>("/api/knowledge?limit=0", { cookies: session.cookies });
expect(one.body.records).toHaveLength(1);
expect(one.body.has_more).toBe(true);
const all = await json<RecordsPage>("/api/knowledge?limit=abc", { cookies: session.cookies });
expect(all.body).toMatchObject({ has_more: false, next_cursor: null });
expect(all.body.records).toHaveLength(3);
});

test("a malformed cursor answers 400", async () => {
const session = await createOrgSession("knowledge-page-cursor");
const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url");
for (const cursor of [
"",
"not a cursor",
encode({ pinned: false }),
encode([false, "1793865600123456"]),
encode(["false", "1793865600123456", crypto.randomUUID()]),
encode([false, 1793865600123456, crypto.randomUUID()]),
encode([false, "-1", crypto.randomUUID()]),
encode([false, "999999999999999999", crypto.randomUUID()]),
encode([false, "1793865600123456", "not-a-uuid"]),
]) {
const response = await json<{ error: string }>(
`/api/knowledge?cursor=${encodeURIComponent(cursor)}`,
{ cookies: session.cookies },
);
expect(response.status, cursor).toBe(400);
expect(response.body.error).toBe("cursor is invalid");
}
});

test("a cursor carries nothing across workspaces", async () => {
const owner = await createOrgSession("knowledge-page-owner");
const other = await createOrgSession("knowledge-page-other");
await seedRecords(owner.orgId, 3);
await seedRecords(other.orgId, 2);
const first = await json<RecordsPage>("/api/knowledge?limit=1", { cookies: owner.cookies });
const crossed = await json<RecordsPage>(
`/api/knowledge?limit=10&cursor=${encodeURIComponent(first.body.next_cursor ?? "")}`,
{ cookies: other.cookies },
);
expect(crossed.status).toBe(200);
const otherIds = new Set(await expectedOrder(other.orgId));
expect(crossed.body.records.every((record) => otherIds.has(record.id))).toBe(true);
});
});
4 changes: 2 additions & 2 deletions backend/test/knowledge.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, beforeAll, describe, expect, test } from "bun:test";
import { createOrgSession, json, uid, type OrgSession } from "./helpers";
import { ingestOne } from "../src/knowledge/ingest";
import { findExisting, listRecords } from "../src/knowledge/store";
import { findExisting, listRecordPage } from "../src/knowledge/store";

// Isolate this suite in its own authenticated org (real session, NOT a forged
// x-org-id header) so the boot seed / other suites never collide with our
Expand Down Expand Up @@ -223,7 +223,7 @@ describe("distill grounding + salience (mocked LLM)", () => {
expect(res.stub).toBe(false);
expect(res.grounding).toEqual({ refsDropped: 1, signalsDropped: 1 });

const rows = await listRecords({ orgId: org });
const { rows } = await listRecordPage({ orgId: org });
const row = rows.find((r) => r.external_id === "g-1");
expect(row).toBeDefined();
expect(row!.refs).toEqual(["PR #482"]); // invented PR #999 never persisted
Expand Down
2 changes: 1 addition & 1 deletion docs-site/docs/api/knowledge.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ wiki](/product/knowledge-and-wiki).

| Method | Path | Description | Notes |
| --- | --- | --- | --- |
| GET | `/api/knowledge` | List org records, pinned first, newest first. | Query `q` (optional keyword filter). Returns `{records, embeddings}` (`embeddings` reflects whether embeddings are enabled). |
| GET | `/api/knowledge` | List org records, pinned first, newest first. | Query `q` (optional keyword filter), `limit` (1-500, default 200), `cursor`. Returns `{records, has_more, next_cursor, embeddings, search_note}` (`embeddings` reflects whether embeddings are enabled). Send `next_cursor` back as `cursor`, with the same `q` and `limit`, for the next page; it is `null` on the last page. `400 cursor is invalid`. |
| POST | `/api/knowledge/search` | Hybrid (tsvector + pgvector) retrieval. | Body: `query` (required), `k` (default 8). Returns `{results, mode}` where `mode` is `"hybrid"` or `"keyword"` (falls back to keyword when no embedding is produced). |
| POST | `/api/knowledge/ingest` | The ingestion contract. | Body: `meta`, `text`. `org_id`/`user_id` injected server-side. `400` on validation error. |
| PATCH | `/api/knowledge/:id` | Pin or unpin a record. | Body: `pinned` (boolean, required). `404 record not found`. |
Expand Down
4 changes: 4 additions & 0 deletions docs-site/docs/product/knowledge-and-wiki.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ searchable and revisioned:
| Documents | `GET`, `POST`, `PATCH /api/knowledge/documents` |
| Publish, archive, revisions | `.../documents/:id/publish`, `/archive`, `/revisions` |

The list shows pinned records first, then the newest. It loads 200 records at a
time: once every loaded row is showing, **Show older knowledge** adds the next
ones.

An agent reaches the same material in a run through the knowledge gateway tools.

## Wiki
Expand Down
Loading
Loading