Skip to content

Commit 8baef8b

Browse files
authored
fix(message): restore indexed reserved session request lookup (#1391)
* fix(message): restore canonical expression-index lookup for reserved identities The canonical session lookup for reserved identities had drifted away from the messageSessionIdentity expression index, causing queries to miss the optimised index path. The condition now always anchors on the expression-index column while still allowing owner-scoped lookups to match legacy null-identity rows via the session_id fallback. Unscoped reserved lookups remain narrow and do not pick up unrelated null-identity rows, preserving reserved identity isolation. * test(repository): assert coalesce in owner-scoped legacy identity fallback Extend the reserved identity SQL contract test to verify that the generated where clause uses coalesce when resolving owner-scoped session requests for legacy clients. * test(sessions): strengthen reserved identity query and route coverage Add encoded-identity regression cases to the v1 session requests route test, verifying that URL-encoded session identities (pfx: and sid: prefixed) resolve correctly through the endpoint. Rewrite the repository-level session request query tests to compile the generated SQL via PgDialect instead of string matching, and parameterize them across both pfx: and sid: identity prefixes. The assertions now verify the exact coalesce expression, identity guards, and parameter bindings for both owner-scoped legacy fallback and unscoped canonical lookups. * style(message): normalize comment punctuation to half-width comma
1 parent 43fb589 commit 8baef8b

3 files changed

Lines changed: 66 additions & 31 deletions

File tree

‎src/repository/message.ts‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -77,12 +77,13 @@ function messageSessionLookup(identityOrPhysicalId: string, ownerUserId?: number
7777

7878
function messageCanonicalSessionLookup(identity: string, ownerUserId?: number) {
7979
const canonicalCondition = isReservedSessionIdentity(identity)
80-
? ownerUserId !== undefined
81-
? or(
82-
eq(messageRequest.sessionIdentity, identity),
83-
and(isNull(messageRequest.sessionIdentity), eq(messageRequest.sessionId, identity))
84-
)
85-
: eq(messageRequest.sessionIdentity, identity)
80+
? and(
81+
// 保留 expression index 入口, 同时避免 reserved identity 混入同名物理 Session.
82+
eq(messageSessionIdentity, identity),
83+
ownerUserId !== undefined
84+
? or(eq(messageRequest.sessionIdentity, identity), isNull(messageRequest.sessionIdentity))
85+
: eq(messageRequest.sessionIdentity, identity)
86+
)
8687
: eq(messageSessionIdentity, identity);
8788

8889
return and(

‎tests/api/v1/sessions/sessions.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,16 @@ describe("v1 session endpoints", () => {
137137
expect(requests.response.status).toBe(200);
138138
expect(getSessionRequestsMock).toHaveBeenCalledWith("s1", 2, 5, "desc");
139139

140+
for (const identity of ["pfx:scope:fingerprint", "sid:canonical-session"]) {
141+
const encodedRequests = await callV1Route({
142+
method: "GET",
143+
pathname: `/api/v1/sessions/${encodeURIComponent(identity)}/requests?page=1&pageSize=20&order=desc`,
144+
headers,
145+
});
146+
expect(encodedRequests.response.status).toBe(200);
147+
expect(getSessionRequestsMock).toHaveBeenLastCalledWith(identity, 1, 20, "desc");
148+
}
149+
140150
await callV1Route({
141151
method: "GET",
142152
pathname: "/api/v1/sessions/s1/requests",

‎tests/unit/repository/message-session-request-query.test.ts‎

Lines changed: 49 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { beforeEach, describe, expect, test, vi } from "vitest";
2+
import { PgDialect } from "drizzle-orm/pg-core";
23
import { messageRequest } from "@/drizzle/schema";
34
import { keys as keysTable } from "@/drizzle/schema";
45
import {
@@ -50,6 +51,12 @@ type RequestRow = Pick<
5051

5152
const firstCreatedAt = new Date("2026-05-04T10:00:00.000Z");
5253
const secondCreatedAt = new Date("2026-05-04T10:01:00.000Z");
54+
const dialect = new PgDialect();
55+
56+
function compileWhere(values: readonly unknown[]) {
57+
const query = dialect.sqlToQuery(values.at(0) as never);
58+
return { sql: query.sql.toLowerCase(), params: query.params };
59+
}
5360

5461
describe("message repository session request queries", () => {
5562
beforeEach(() => {
@@ -237,33 +244,50 @@ describe("message repository session request queries", () => {
237244
expect(rowsWhere.match(/shared-session/g)).toHaveLength(1);
238245
});
239246

240-
test("includes a legacy null-identity physical fallback for owner-scoped reserved identities", async () => {
241-
const count = createDrizzleQuery([{ count: 1 }]);
242-
const rows = createDrizzleQuery<readonly RequestRow[]>([]);
243-
boundary.select.mockReturnValueOnce(count).mockReturnValueOnce(rows);
244-
245-
await findRequestsBySessionIdentity("pfx:legacy-client", { ownerUserId: 17 } as never);
246-
247-
for (const where of [sqlText(count.trace.where), sqlText(rows.trace.where)]) {
248-
expect(where).toContain("user_id");
249-
expect(where).toContain("is null");
250-
expect(where).toContain("session_id");
251-
expect(where.match(/pfx:legacy-client/g)).toHaveLength(2);
247+
test.each(["pfx:legacy-client", "sid:legacy-client"])(
248+
"includes an owner-scoped legacy fallback without aliasing a non-null identity: %s",
249+
async (identity) => {
250+
const count = createDrizzleQuery([{ count: 1 }]);
251+
const rows = createDrizzleQuery<readonly RequestRow[]>([]);
252+
boundary.select.mockReturnValueOnce(count).mockReturnValueOnce(rows);
253+
254+
await findRequestsBySessionIdentity(identity, { ownerUserId: 17 } as never);
255+
256+
for (const where of [count.trace.where, rows.trace.where]) {
257+
const compiled = compileWhere(where);
258+
expect(compiled.sql).toContain(
259+
'coalesce("message_request"."session_identity", "message_request"."session_id") ='
260+
);
261+
expect(compiled.sql).toContain(
262+
'("message_request"."session_identity" = $2 or "message_request"."session_identity" is null)'
263+
);
264+
expect(compiled.sql).not.toContain('or "message_request"."session_id" =');
265+
expect(compiled.sql).toContain('"message_request"."user_id" = $3');
266+
expect(compiled.params.slice(0, 3)).toEqual([identity, identity, 17]);
267+
}
252268
}
253-
});
254-
255-
test("does not add the legacy physical fallback for unscoped reserved identities", async () => {
256-
const count = createDrizzleQuery([{ count: 1 }]);
257-
const rows = createDrizzleQuery<readonly RequestRow[]>([]);
258-
boundary.select.mockReturnValueOnce(count).mockReturnValueOnce(rows);
259-
260-
await findRequestsBySessionIdentity("pfx:canonical", {} as never);
261-
262-
for (const where of [sqlText(count.trace.where), sqlText(rows.trace.where)]) {
263-
expect(where).not.toContain("session_identity is null");
264-
expect(where.match(/pfx:canonical/g)).toHaveLength(1);
269+
);
270+
271+
test.each(["pfx:canonical", "sid:canonical"])(
272+
"uses the canonical expression index with an explicit unscoped identity guard: %s",
273+
async (identity) => {
274+
const count = createDrizzleQuery([{ count: 1 }]);
275+
const rows = createDrizzleQuery<readonly RequestRow[]>([]);
276+
boundary.select.mockReturnValueOnce(count).mockReturnValueOnce(rows);
277+
278+
await findRequestsBySessionIdentity(identity, {} as never);
279+
280+
for (const where of [count.trace.where, rows.trace.where]) {
281+
const compiled = compileWhere(where);
282+
expect(compiled.sql).toContain(
283+
'coalesce("message_request"."session_identity", "message_request"."session_id") = $1 and "message_request"."session_identity" = $2'
284+
);
285+
expect(compiled.sql).not.toContain('"message_request"."session_identity" is null');
286+
expect(compiled.sql).not.toContain('or "message_request"."session_id" =');
287+
expect(compiled.params.slice(0, 2)).toEqual([identity, identity]);
288+
}
265289
}
266-
});
290+
);
267291

268292
test("does not treat a reserved canonical identity as a physical Session alias", async () => {
269293
const locator = createDrizzleQuery([

0 commit comments

Comments
 (0)