Skip to content

Commit 0243357

Browse files
fix(rest): a failed saved-dataset read on the dataset door answers 503 SERVICE_UNAVAILABLE, not 404 (#31807)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9HLWFFbydxZ9SpmExahzcbB)_ Fixes #31774 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:数据集查询接口(`POST /analytics/dataset/query`,按名称查已保存数据集)在“读取已保存数据集”这一步本身失败时,现在回答 503「服务暂不可用」,不再回答 404「数据集不存在」。 - 为什么改:原来读取失败被当成空列表,元数据后端故障时仪表盘会告诉用户“数据集不存在”,用户可能误删或重建;运维在日志里只看到 404 而看不到故障。AI 工具 `query_dataset` 对同一失败已回答 503,两个入口现在一致。 - 风险与回滚:只影响读取抛错这一条路径;读取成功但没有该名称仍是原样的 404,找到则照常查询。回滚即还原 `analytics-routes.ts` 一处改动。 - 先看:`packages/rest/src/analytics-routes.ts`(数据集读取的 try/catch 一段)、`packages/rest/src/analytics-routes.test.ts` 与 `packages/rest/src/analytics-dataset-ai-tools-parity.test.ts`(新增的 describe)。 - 两分钟验证:`pnpm --filter @objectstack/rest exec vitest run src/analytics-routes.test.ts src/analytics-dataset-ai-tools-parity.test.ts`,预期 25 个测试全部通过。 - 需要你做的:无,席位落地。 ## What changes `packages/rest/src/analytics-routes.ts` read the saved datasets with `p.getMetaItems?.(datasetRequest).catch(() => null)`, so a read that threw became an empty list and the door answered `404 {"code":"NOT_FOUND","message":"Dataset \"X\" not found."}`. Now a throwing read is turned into a declared refusal (`code: 'SERVICE_UNAVAILABLE'`, `status: 503`, `refusal: true`, `cause` = the read's own error) and thrown into the handler's existing catch. That catch already answers every producer-declared 5xx through `declaredServerFaultAnswer` (`@objectstack/types`), and its `logError` runs before that arm, so: - the client gets `503 {"error":"The dataset \"X\" could not be resolved: the dataset read failed. This is a server-side fault, not a missing dataset.","code":"SERVICE_UNAVAILABLE"}`; - the store's own text (a driver or connection message) is withheld from the client, as for every 5xx at this door, and reaches the operator log through `cause`. Same code and status as the AI tool `query_dataset` (PR #31772, `dataset-tools.ts`) for the same failed read. Its sentence is built inline there and not exported (re-read on `main` after #31772 merged), and `packages/services/service-analytics/**` is outside this card's surface, so there is no shared wording to import yet. This door uses the same sentence without the parenthetical store text (withheld here; see open question 1 in the report). Unchanged: - A read that succeeds and lacks the name: `404 {"code":"NOT_FOUND","message":"Dataset \"X\" not found."}`, byte-identical (pinned with `toEqual` on the whole body). - A found dataset: served as before. - A protocol with no `getMetaItems` method: today's answer is that same `404 NOT_FOUND` (optional chaining reads no list). Kept and pinned. ### Other door reads in `analytics-routes.ts` (seat ruling 3) Checked every `catch` in the file on `e253f3ab`: | Site | Shape | Disposition | |---|---|---| | saved-dataset read (was line 199) | `.catch(() => null)` then `404 NOT_FOUND` | fixed here | | `resolveService` (line 108) | `catch { return undefined; }` then `501 NOT_IMPLEMENTED` "not available on this deployment" | **out-of-scope finding**: a throwing environment resolution or analytics provider (environment kernel not acquirable) answers 501 "not available" rather than an outage status. The file's header comment states this posture as deliberate for #30011 ("or could not be acquired, the answer is the 501 below"). Not changed; named for the seat. | | dataset schema parse (line ~289) | `catch (verr)` then `400 VALIDATION_FAILED` | correct: a parse refusal, not a read | | handler catch (line ~304) | classification arms | the arm this fix routes through | No other `.catch(() => null)` exists in the file. ## Tests New top-level `describe` in the existing harness file `packages/rest/src/analytics-routes.test.ts` (no new file): - `answers 503 SERVICE_UNAVAILABLE, not 404, when getMetaItems throws`: status 503, `code`, the sentence's first clause, no "not found" anywhere in the body, the store text (`ECONNREFUSED`) absent from the body, the original error reaching `console.error` as `cause`, and `queryDataset` never called. - CONTROL: a read that succeeds without the name → the whole 404 body, byte-identical. - CONTROL: a read that finds the name → 200, served. - CONTROL: a protocol without `getMetaItems` → the same 404 body. And one parity pin in `packages/rest/src/analytics-dataset-ai-tools-parity.test.ts` (the four-face harness #31772 landed), as its own top-level `describe`: with the same thrown read, the REST door and `query_dataset` (through the tools' `execute`, on the real `AnalyticsServicePlugin` service) both refuse `{ status: 503, code: 'SERVICE_UNAVAILABLE' }`, and the two answers are equal. Test edits to existing harness code, named: - `analytics-dataset-ai-tools-parity.test.ts`: the `protocol` double built in `beforeAll` is now a module-level `let` (was a `const` inside `beforeAll`), so the new case can make one read throw with `mockRejectedValueOnce`. Every existing case is unchanged and green. - `analytics-routes.test.ts`: a module-top `import '@objectstack/objectql';` (the convention `check:test-source-alias` names for an edited test file whose server under test reaches objectql through a handler's dynamic import; precedent `email-send-door-bounds.test.ts`). No assertion changed. ## Acceptance notes - The 503 body has this door's declared-5xx shape (`error` + `code`), the one it already gives any producer-declared 503, while the door's hand-built 4xx refusals (the 404 included) use `code` + `message`. Choosing the shared arm over a hand-built `{code, message}` 503 keeps one classification for every declared 5xx at this door. Open question 2 in the report. ## Verification Head `cab19e73`, branch `claude/project-thread-xv4xgu`, `origin/main` merged at `2b752aa4` (includes #31772). <details><summary>Red first (test commit 3df5f46, fix absent)</summary> ``` × answers 503 SERVICE_UNAVAILABLE, not 404, when getMetaItems throws AssertionError: expected 404 to be 503 // Object.is equality Tests 1 failed | 17 passed (18) VERDICT command-exit 1 ``` </details> <details><summary>Green (fix commit)</summary> ``` src/analytics-routes.test.ts + src/analytics-dataset-ai-tools-parity.test.ts Tests 25 passed (25) VERDICT command-exit 0 on head cab19e7: pnpm --filter @objectstack/rest test && typecheck: Test Files 396 passed (396) · Tests 7638 passed | 332 skipped (7970) · check:test-typecheck OK · VERDICT command-exit 0 eslint --no-inline-config on the three touched files: exit 0 ``` </details> <details><summary>Ablations (scripts/ablation-replace.mjs, src-imported suite, on-disk proof each leg, restore proven by an empty git diff HEAD)</summary> ``` A1 put the swallow back (.catch(() => null)) anchor 1 -> 0, blob d823bbe -> 6082cb92 × answers 503 … AssertionError: expected 404 to be 503 A2 drop cause: readError (operator log) anchor 1 -> 0, blob d823bbe -> d4739bb5 × answers 503 … AssertionError: expected false to be true A3 append the store text to the sentence anchor 1 -> 0, blob d823bbe -> b672b144 × answers 503 … expected '{"error":"The dataset \"sales\" could…' not to contain 'ECONNREFUSED' A4 (after the merge, both files) put the swallow back anchor 1 -> 0, blob d823bbe -> 6082cb92 × answers 503 SERVICE_UNAVAILABLE, not 404, when getMetaItems throws × both answer 503 SERVICE_UNAVAILABLE, neither 404 expected { refused: { status: 404, … } } to deeply equal { refused: { status: 503, … } } Tests 2 failed | 23 passed (25) restore: git diff HEAD empty after each leg ``` </details> <details><summary>Derived gates (dispatch-gates --commands, 65 commands)</summary> On head `cab19e73` (full `turbo run build --filter='./packages/**'` first, for the dist-reading families). `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` → 65 commands, each exit captured before any pipe: ``` node scripts/check-adr-0087-registration.mjs --base origin/main :: exit 0 node scripts/check-adr-0087-registration.mjs --self-test :: exit 0 node scripts/check-changeset-no-major.mjs --base origin/main :: exit 0 node scripts/check-closing-keyword-parity.mjs :: exit 0 node scripts/check-closing-keyword-parity.mjs --self-test :: exit 0 node scripts/check-comment-mask-adoption.mjs :: exit 0 node scripts/check-comment-mask-adoption.mjs --self-test :: exit 0 node scripts/check-comment-mask-corpus.mjs :: exit 0 node scripts/check-dts-emitted.mjs --self-test :: exit 0 node scripts/check-empty-changeset.mjs --base origin/main :: exit 0 node scripts/check-empty-changeset.mjs --self-test :: exit 0 node scripts/check-issue-citations.mjs :: exit 0 node scripts/check-plugin-teardown-shape.mjs :: exit 0 node scripts/check-plugin-teardown-shape.mjs --self-test :: exit 0 node scripts/ci/assert-turbo-remote-cache.mjs --self-test :: exit 0 node scripts/ci/plan-test-core-shards.mjs --self-test :: exit 0 node scripts/ci/prune-turbo-cache.mjs --self-test :: exit 0 node scripts/ci/snapshot-next.mjs --self-test :: exit 0 node scripts/docs-audit/check-affected-docs.mjs :: exit 0 node scripts/docs-audit/check-drift-comment.mjs :: exit 0 node scripts/pm/release-rehearsal-clone.mjs --self-test :: exit 0 node scripts/release-pending-publish.mjs --self-test :: exit 0 pnpm --filter @objectstack/spec run check:duration-unit-keys :: exit 0 pnpm --filter @objectstack/spec run check:error-code-provenance :: exit 0 pnpm check:changeset-gate-self-tests :: exit 0 pnpm check:ci-filter-parity :: exit 0 pnpm check:closed-ceremony-text :: exit 0 pnpm check:cross-package-test-inputs :: exit 0 pnpm check:dispatcher-error-vocabulary :: exit 0 pnpm check:doc-authoring :: exit 0 pnpm check:driver-memory-census :: exit 0 pnpm check:dts-closure :: exit 0 pnpm check:dual-build-cjs-loads :: exit 0 pnpm check:engine-double-contract :: exit 0 pnpm check:error-status-conformance :: exit 0 pnpm check:gitlink-declared :: exit 0 pnpm check:issue-citations :: exit 0 pnpm check:keyed-text-bounds :: exit 0 pnpm check:lean-entry-closure :: exit 0 pnpm check:logger-receiver-detach :: exit 0 pnpm check:meta-type-normalized :: exit 0 pnpm check:nul-bytes :: exit 0 pnpm check:object-def-param-keys :: exit 0 pnpm check:objectql-double-limit :: exit 0 pnpm check:optional-error-sink :: exit 0 pnpm check:org-identifier :: exit 0 pnpm check:page-declaration-shape :: exit 0 pnpm check:platform-object-tenancy-census :: exit 0 pnpm check:published-files :: exit 0 pnpm check:query-options-erasure :: exit 0 pnpm check:refd-timer-probe :: exit 0 pnpm check:registry-log-declared :: exit 0 pnpm check:rest-log-spy-declared :: exit 0 pnpm check:route-envelope :: exit 0 pnpm check:slot-lookup :: exit 0 pnpm check:sourcemap-no-sources-content :: exit 0 pnpm check:system-context-census :: exit 0 pnpm check:test-source-alias :: exit 0 pnpm check:tier-file-adoption :: exit 0 pnpm check:type-check-coverage :: exit 0 pnpm check:type-check-debt :: exit 0 pnpm check:undeclared-dep-imports :: exit 0 pnpm check:vouch-for-reference-callers :: exit 0 pnpm check:watch-hint-literal :: exit 0 pnpm check:where-matcher :: exit 0 ``` ``` Run reconciliation — 65 derived, 65 run, 0 NOT-MEASURED, 0 UNRUN. ✓ dispatch-gates --ran: 65 derived famil(ies) accounted for — 65 run, 0 NOT-MEASURED (a DERIVED zero — all 65 recorded an exit code and none of them is 3). ``` Earlier round on `98c93211`, three non-zero exits, all cleared before this one: `check:test-source-alias` named the edited harness file (fixed by the module-top objectql import above); `check-plugin-teardown-shape --self-test` exit 3 and `check:dual-build-cjs-loads` exit 3 were prerequisites (shallow clone missing a pinned fixture commit, fetched; no `dist/` before the full build), not verdicts. </details> Dogfood battery: n/a, no `!` in the title and no `(narrowing)` arm. Session: `session_01ADHkmQ7H4b6yCoAFuheonF` (card thread, os-dev) for seat `domain:server#2`. --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmQ7H4b6yCoAFuheonF)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 74e85da commit 0243357

4 files changed

Lines changed: 142 additions & 3 deletions

File tree

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
'@objectstack/rest': patch
3+
---
4+
5+
Clause-②: no
6+
Metadata-protocol: none
7+
8+
`POST /analytics/dataset/query` with a `datasetName` now answers `503 SERVICE_UNAVAILABLE` when the saved-dataset read itself fails (for example, the metadata store is unreachable), instead of `404 NOT_FOUND` "Dataset … not found.". The answer says the dataset read failed and that this is a server-side fault, not a missing dataset; the store's own error text is withheld from the client and logged for the operator. This matches the AI tool `query_dataset`, which answers the same failed read `503 SERVICE_UNAVAILABLE`. A read that succeeds without the name still answers `404 NOT_FOUND`, unchanged.

‎packages/rest/src/analytics-dataset-ai-tools-parity.test.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ type FaceAnswer = { rows: Record<string, unknown>[] } | { refused: { status: num
132132
let engine: ObjectQL;
133133
let service: AnalyticsService;
134134
let restRoute: any;
135+
let protocol: { getMetaItems: ReturnType<typeof vi.fn> } & Record<string, unknown>;
135136

136137
const byKey = (rows: Record<string, unknown>[]) =>
137138
[...rows].map((r) => JSON.stringify(Object.keys(r).sort().map((k) => [k, r[k]]))).sort();
@@ -197,7 +198,7 @@ beforeAll(async () => {
197198
await new AnalyticsServicePlugin().init(ctx as never);
198199
service = registered.analytics as AnalyticsService;
199200

200-
const protocol = {
201+
protocol = {
201202
getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '' } }),
202203
getMetaTypes: vi.fn().mockResolvedValue([]),
203204
getMetaItems: vi.fn().mockImplementation(async () => SAVED.map((d) => ({ ...d }))),
@@ -276,3 +277,26 @@ describe('[ADR-0149 D4] query_dataset returns the rows the REST door and the ser
276277
expect(admin.datasets[0].membersWithheld).toBeUndefined();
277278
});
278279
});
280+
281+
describe('a FAILED saved-dataset read is answered alike by the REST door and query_dataset', () => {
282+
// A read that threw is a server-side fault, not an absent dataset: neither
283+
// face may answer it as `404 NOT_FOUND`, and both answer it the same way.
284+
it('both answer 503 SERVICE_UNAVAILABLE, neither 404', async () => {
285+
const outage = new Error('the metadata store is unreachable');
286+
const selection = { measures: ['revenue'] };
287+
288+
protocol.getMetaItems.mockRejectedValueOnce(outage);
289+
const rest = await faces.rest('u_me', selection);
290+
291+
const tools = service.datasetTools({ loadDatasets: async () => { throw outage; } });
292+
let chatTool: FaceAnswer | undefined;
293+
try {
294+
await tools.execute({ toolName: 'query_dataset', input: { datasetName: DATASET.name, selection } }, callers.u_me);
295+
} catch (e) {
296+
chatTool = { refused: refusalOf(e) };
297+
}
298+
299+
expect(rest).toEqual({ refused: { status: 503, code: 'SERVICE_UNAVAILABLE' } });
300+
expect(chatTool).toEqual(rest);
301+
});
302+
});

‎packages/rest/src/analytics-routes.test.ts‎

Lines changed: 74 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
22

3-
import { describe, it, expect, vi } from 'vitest';
3+
import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest';
44
import { RestServer } from './rest-server';
5+
// The server under test reaches `@objectstack/objectql` only through a dynamic
6+
// import inside a handler (`meta-object-state-routes.ts`), so the first case to
7+
// call one would pay that module graph's load inside its clocked window. This
8+
// module-top import pays it during collection instead.
9+
import '@objectstack/objectql';
510

611
// ── helpers ──────────────────────────────────────────────────────────────────
712

@@ -259,3 +264,71 @@ describe('POST /analytics/dataset/query', () => {
259264
expect(res.body.code).toBe('DATASET_INVALID');
260265
});
261266
});
267+
268+
// ── a FAILED saved-dataset read is not an absent dataset ─────────────────────
269+
// The `datasetName` lookup used to swallow a throwing `getMetaItems` into an
270+
// empty list, so a metadata-store outage answered `404 NOT_FOUND "Dataset …
271+
// not found."`: a dashboard told its user the dataset was gone, and the
272+
// operator read a 404 instead of an outage. The AI tool `query_dataset` answers
273+
// the same failed read `503 SERVICE_UNAVAILABLE`; this door now agrees.
274+
describe('POST /analytics/dataset/query — a failed saved-dataset read', () => {
275+
let consoleError: ReturnType<typeof vi.spyOn>;
276+
beforeEach(() => {
277+
// The harness silences this package's fault log; the outage must reach it.
278+
vi.stubEnv('OS_REST_LOG', 'info');
279+
consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
280+
});
281+
afterEach(() => {
282+
consoleError.mockRestore();
283+
vi.unstubAllEnvs();
284+
});
285+
286+
const send = async (protocol: any, datasetName = 'sales') => {
287+
const queryDataset = vi.fn().mockResolvedValue({ rows: [{ region: 'NA', revenue: 100 }], fields: [] });
288+
const { route } = buildServer(async () => ({ queryDataset }), protocol);
289+
const res = mockRes();
290+
await route!.handler({ method: 'POST', params: {}, headers: {}, body: { datasetName, selection } } as any, res);
291+
return { res, queryDataset };
292+
};
293+
294+
it('answers 503 SERVICE_UNAVAILABLE, not 404, when getMetaItems throws', async () => {
295+
const outage = new Error('connect ECONNREFUSED 10.0.0.7:5432');
296+
const protocol = { ...mockProtocol(), getMetaItems: vi.fn().mockRejectedValue(outage) };
297+
const { res, queryDataset } = await send(protocol);
298+
299+
expect(res.statusCode).toBe(503);
300+
expect(res.body.code).toBe('SERVICE_UNAVAILABLE');
301+
// The answer names the dataset and says the READ failed, never "not found".
302+
expect(res.body.error).toMatch(/^The dataset "sales" could not be resolved: the dataset read failed\./);
303+
expect(JSON.stringify(res.body)).not.toMatch(/not found/i);
304+
// The store's own text is withheld from the client and kept for the operator.
305+
expect(JSON.stringify(res.body)).not.toContain('ECONNREFUSED');
306+
const logged = consoleError.mock.calls.flat();
307+
expect(logged.some((a: any) => a?.cause === outage)).toBe(true);
308+
expect(queryDataset).not.toHaveBeenCalled();
309+
});
310+
311+
it('CONTROL: a read that succeeds without the name still answers 404, byte-identical', async () => {
312+
const protocol = { ...mockProtocol(), getMetaItems: vi.fn().mockResolvedValue({ items: [{ ...inlineDataset }] }) };
313+
const { res, queryDataset } = await send(protocol, 'nope');
314+
expect(res.statusCode).toBe(404);
315+
expect(res.body).toEqual({ code: 'NOT_FOUND', message: 'Dataset "nope" not found.' });
316+
expect(queryDataset).not.toHaveBeenCalled();
317+
});
318+
319+
it('CONTROL: a read that finds the name is served', async () => {
320+
const protocol = { ...mockProtocol(), getMetaItems: vi.fn().mockResolvedValue({ items: [{ ...inlineDataset }] }) };
321+
const { res, queryDataset } = await send(protocol);
322+
expect(res.statusCode).toBe(200);
323+
expect(res.body.rows).toEqual([{ region: 'NA', revenue: 100 }]);
324+
expect(queryDataset.mock.calls[0][0].name).toBe('sales');
325+
});
326+
327+
it('CONTROL: a protocol with no getMetaItems keeps its answer, 404 NOT_FOUND', async () => {
328+
const { getMetaItems: _absent, ...protocol } = mockProtocol();
329+
const { res, queryDataset } = await send(protocol);
330+
expect(res.statusCode).toBe(404);
331+
expect(res.body).toEqual({ code: 'NOT_FOUND', message: 'Dataset "sales" not found.' });
332+
expect(queryDataset).not.toHaveBeenCalled();
333+
});
334+
});

‎packages/rest/src/analytics-routes.ts‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,41 @@ export function registerAnalyticsEndpoints(this: AnalyticsRouteHost, basePath: s
196196
if (!dataset && body.datasetName) {
197197
const p = await this.resolveProtocol(environmentId, req);
198198
const datasetRequest: GetMetaItemsRequest = { type: 'dataset', previewDrafts };
199-
const items: any = await p.getMetaItems?.(datasetRequest).catch(() => null);
199+
// [#31774] A read that FAILED is not a read that came
200+
// back without the name. The `.catch(() => null)` that
201+
// stood here turned a metadata-store outage into an
202+
// empty list, so the door answered `404 "Dataset … not
203+
// found."`: a dashboard told its user the dataset was
204+
// gone, and the operator read a 404 instead of an
205+
// outage. The AI tool `query_dataset` answers the same
206+
// failed read `503 SERVICE_UNAVAILABLE`, so this door
207+
// does too.
208+
//
209+
// The refusal is THROWN, declared, into this handler's
210+
// own catch, never answered by hand: its declared-5xx arm
211+
// (`declaredServerFaultAnswer`, #11718) is the one this
212+
// door already answers every producer-declared 503 with,
213+
// and its `logError` runs first, so the store's own text
214+
// — withheld from the client like every 5xx's (#5437) —
215+
// reaches the operator on `cause`. `refusal: true` lets
216+
// the sentence below, which this code wrote for the
217+
// caller, through that arm.
218+
//
219+
// Unchanged: a read that succeeds without the name is the
220+
// `404` below, and a protocol with no `getMetaItems` at
221+
// all reads no list and answers that same `404`.
222+
let items: any;
223+
try {
224+
items = await p.getMetaItems?.(datasetRequest);
225+
} catch (readError) {
226+
throw Object.assign(
227+
new Error(
228+
`The dataset "${body.datasetName}" could not be resolved: the dataset read failed. `
229+
+ 'This is a server-side fault, not a missing dataset.',
230+
),
231+
{ code: 'SERVICE_UNAVAILABLE', status: 503, refusal: true, cause: readError },
232+
);
233+
}
200234
const list = Array.isArray(items?.items) ? items.items : (Array.isArray(items) ? items : []);
201235
dataset = list.find((d: any) => d?.name === body.datasetName);
202236
if (!dataset) {

0 commit comments

Comments
 (0)