mirror of
https://github.com/morluto/rea.git
synced 2026-11-11 17:28:08 +00:00
* feat(sqlite): page selected rows with a stated order and row offset readRows read `NOT INDEXED LIMIT ?` with no ORDER BY and reported order: "unspecified", so an agent could not reach rows past row_limit deterministically: raising row_limit hits the fixed 16 MiB reply budget, and the sampled order depends on whichever index SQLite happened to scan. Read the window in a unique, stated order and expose the position: - rowid tables order by rowid unless all of rowid, _rowid_ and oid are declared columns, in which case the order stays unspecified. - WITHOUT ROWID tables order by the primary-key columns, reusing each key's DESC flag and declared collation from pragma_index_xinfo so the plan keeps index order instead of materialising a sorter. - rows.order, rows.row_offset and rows.next_row_offset report the window; next_row_offset is null once the window reaches the end. - row_offset (CLI --row-offset) requires table and defaults to 0. A non-zero offset is refused when the table declares no usable order, because the skipped prefix would be arbitrary. The schema now checks next_row_offset against truncated and the offset so a worker reply cannot claim a page it did not read. One attribution fix came with it: adding ORDER BY text can push an over-wide projection past SQLite's SQL-text limit, which fails as SQLITE_TOOBIG before the result-column limit is reported. Attribute that case to column capacity too, so a 250k-column request still reads as capacity rather than a byte budget. Verified: npm run check:fast, npm run format:check on the touched files, npm run verify:module-boundaries, npm run docs:check, and 196 tests across the sqlite boundary, application and CLI/MCP suites. A 1002-row inspection and in-memory EXPLAIN QUERY PLAN checks confirmed the WITHOUT ROWID path adds no sorter. Full check:pr and the complete test suite were not run. * fix(sqlite): resolve the rowid alias and keep paging claims reachable Three defects in the row paging added alongside row_offset: - readRowOrder emitted ORDER BY rowid for every rowid table, but a table that declares a rowid column shadows that spelling, so the sort used the stored column and could repeat or drop rows across pages. Order now names the first alias the table leaves unbound, read from raw name bytes so an unrelated malformed identifier is not decoded just to choose an order. - The inventory projection could hide the primary key a WITHOUT ROWID table orders by, silently degrading a paginated read to unspecified order. The order key is now read from the table itself rather than from the columns the caller asked to see. - A truncated table with no stated order reported a next_row_offset that the row_offset rule then refused. It is null there, and the reply limitation no longer claims an unspecified order for windows that have one. rowEvaluationFailure also probed the first rows of the table instead of the requested window, so a failure confined to a later page was attributed to columns that evaluate fine there. * test(sqlite): assert the concatenated pages The paging regression checked only counts, offsets and flags, so a second page that repeated the first page's rows would still pass. Assert the values read across all three pages instead. * fix(sqlite): decode row keys in the database encoding readRowKeyFacts decoded primary-key names as UTF-8 and probed a fixed hidden set, so two supported schemas could not be paged at all: - A UTF-16 database stores key names as UTF-16 bytes, so "k" decoded to NUL-padded text and ORDER BY named an identifier that does not exist. Pass the detected encoding, as readColumns and the index-metadata path already do. - A virtual generated column named rowid (hidden=2) was absent from the shadow check, so ORDER BY rowid evaluated the generated expression instead of the rowid and could sort non-uniquely or fail outright. Include generated columns in the alias probe. Also stop decoding primary-key names for rowid tables: their ORDER BY names an alias, never a declared key, so an unselected malformed key name could abort an otherwise readable selection. The page-concatenation assertion now narrows SqliteValue before reading .value, which the null/blob arms do not carry; this was failing the Static checks typecheck job. * fix(sqlite): order WITHOUT ROWID rows by the index's own key sequence `readRowOrder` filed `pragma_index_xinfo` key terms into a map keyed by column name, so a valid composite key that repeats a column — `PRIMARY KEY(a COLLATE BINARY, a COLLATE NOCASE DESC)` — collapsed to one term. The generated clause then overstated uniqueness: it omitted the BINARY term, so `A`/`a` ties survived, and the `row_offset` paging advertised a `primary_key` order that the actual key does not establish. Build the terms from the index rows in `seqno` order instead, keeping repetitions, and bail to `unspecified` if any declared key column never appears in the index. The declared collation stays explicit so a caller column's own collation cannot re-sort the window. Verified against a real SQLite database that the repeated key is accepted and that the old clause orders A, a, B while the index orders A, B, a. * fix(sqlite): accept a null next offset on unordered truncated rows readRows already withholds next_row_offset when a table shadows rowid, _rowid_ and oid and declares no primary key, because every non-zero offset is refused there. The reply schema still required the offset whenever truncated was set, so the provider rejected its own worker result and the first sample never reached CLI or MCP. Require the offset only when the order is stated. * fix(sqlite): probe row keys only for ordinary tables and name row_offset readRowKeyFacts ran for a selected virtual shadow table before readRows could reject it, so an unavailable module surfaced as SQLite's "no such module" instead of the selection refusal. Probe the key only when the selected kind is an ordinary table and leave the order unspecified otherwise, since no rows are read for that kind. The unordered-offset refusal also reported the generic selection reason, which callers see against table. Give it its own reason so the failure is attributed to row_offset. * feat(sqlite)!: page selected rows with a stated order and row offset Selected-row inspection currently reports only rows.order: "unspecified" and offers no way to reach rows past the first sample deterministically. Main also refuses non-zero row_offset today, so nothing relies on that omission; this change makes the stated order and the offset the contract, reports the next offset the caller feeds back, and keeps the existing byte, heap, statement and deadline limits. BREAKING CHANGE: rows.order becomes rowid | primary_key | unspecified, and rows gains required row_offset and next_row_offset members. A client that validates selected-table output against the previous schema (where order was the only permitted value) rejects a now-valid reply. Migration: accept the two new members and treat order: "rowid" | "primary_key" as the stated order the offset applies to; a null next_row_offset means the window reached the end. * docs(sqlite): say a null next offset also means no stated order The selected-rows limitation described next_row_offset as null only when the window reached the end. An unordered table whose row_limit truncates the sample also publishes null, because an offset there would name a request the row-offset rule refuses, so the Evidence read as if the sample were complete. State the second cause and pin it in the existing regression. * test(sqlite): drop the limitation wording assertion and state the unordered exception The boundary test pinned the sentence a caller reads in `limitations`, so a harmless rewrite of that text failed a paging test whose real subject is `order`, `truncated` and `next_row_offset`. docs/development/testing.md asks for facts over frozen explanatory prose, and the three structured expectations already fail if the paging fact changes. The tool contract promised that retained rows always have a unique order and can be paged. A rowid table that shadows rowid, _rowid_ and oid and declares no primary key has no such order: it returns order=unspecified with a null next offset and refuses a non-zero row_offset. Say so in the description so callers do not plan a continuation the tool always refuses. * docs(sqlite): say unordered tables cannot be paged The description told callers that a truncated table without a stated order needs "the table read without offsets", but omitting row_offset starts at zero again: with an unchanged row_limit the next call repeats the first sample instead of continuing past it. Say that these tables cannot be paged and point at row_limit for a larger first sample. * style(cli): wrap the native data type path description The `inspect-native-data-type` argument description line is 82 columns, over the repository's 80-column `.oxfmtrc.json` limit, so `npm run format:check` fails on main and on every branch merged from it. It came in with #9465 and the following commits to this file did not touch it. Reformat the one call the formatter objects to; no behaviour change. * fix(sqlite): bound rowid alias comparison by name byte length readRowKeyFacts decoded every column name before testing it against three short aliases, so a table declaring a multi-megabyte name could exhaust the worker heap even when the caller projected the column away. Reject names that cannot be an alias by their byte length, accounting for the database encoding, before building any string. --------- Co-authored-by: 2SinceJuly <202121119+2SinceJuly@users.noreply.github.com> Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
355 lines
13 KiB
TypeScript
355 lines
13 KiB
TypeScript
import { safeParseUtf8Json } from "../domain/safeJson.js";
|
|
import {
|
|
bindArtifactFileCleanup,
|
|
artifactFileCancellationCause,
|
|
} from "../artifacts/ArtifactFileOperation.js";
|
|
import { randomUUID } from "node:crypto";
|
|
import { writeFile } from "node:fs/promises";
|
|
import { join } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import { z } from "zod";
|
|
import type {
|
|
AnalysisCapturedOutput,
|
|
AnalysisError,
|
|
} from "../domain/analysisErrorBase.js";
|
|
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
|
|
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
|
import {
|
|
AnalysisCancelledError,
|
|
AnalysisInputError,
|
|
AnalysisCapabilityUnavailableError,
|
|
AnalysisOutputError,
|
|
AnalysisResourceConstraintError,
|
|
} from "../domain/analysisErrorCore.js";
|
|
import {
|
|
sqliteDatabaseSchema,
|
|
type InspectSqliteDatabaseInput,
|
|
} from "../domain/sqlite/sqliteDatabase.js";
|
|
import {
|
|
completedStableArtifact,
|
|
readStableArtifact,
|
|
} from "../artifacts/readStableArtifact.js";
|
|
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
|
|
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
|
|
import { runOwnedCommand } from "../process/OwnedCommand.js";
|
|
import type {
|
|
ProviderProcessSupervisor,
|
|
ProviderProcessStopResult,
|
|
} from "../process/ProviderProcess.js";
|
|
import { capturedSqliteOutput } from "./SqliteDatabaseFailures.js";
|
|
import {
|
|
SQLITE_DATABASE_LIMITS,
|
|
SQLITE_INSPECTION_REASONS,
|
|
SQLITE_STRUCTURED_INSPECTION_REASONS,
|
|
} from "./SqliteDatabaseLimits.js";
|
|
|
|
const operation = "inspect_sqlite_database";
|
|
const {
|
|
artifact: _artifactSchema,
|
|
wal: _walSchema,
|
|
worker_timeout_ms: _workerTimeoutSchema,
|
|
...inspectionShape
|
|
} = sqliteDatabaseSchema.shape;
|
|
const inspectionSchema = z.strictObject(inspectionShape);
|
|
const replySchema = z.union([
|
|
z.strictObject({ ok: z.literal(true), inspection: inspectionSchema }),
|
|
z.strictObject({
|
|
ok: z.literal(false),
|
|
reason: z
|
|
.enum(SQLITE_INSPECTION_REASONS)
|
|
.exclude(SQLITE_STRUCTURED_INSPECTION_REASONS),
|
|
message: z.string(),
|
|
}),
|
|
z.strictObject({
|
|
ok: z.literal(false),
|
|
reason: z.literal("column-evaluation"),
|
|
message: z.string(),
|
|
readable_columns: z.array(z.string()),
|
|
}),
|
|
z.strictObject({
|
|
ok: z.literal(false),
|
|
reason: z.literal("column-limit"),
|
|
message: z.string(),
|
|
selected_columns: z.int().positive(),
|
|
engine_column_limit: z.int().positive(),
|
|
}),
|
|
]);
|
|
/** Replaceable launcher retains the shared owned-process supervision boundary. */
|
|
export type SqliteWorkerLauncher = NonNullable<
|
|
Parameters<typeof runOwnedCommand>[2]
|
|
>["launcher"];
|
|
|
|
/** Validated worker facts and the exact reply descriptor's finalization outcome. */
|
|
interface SqliteWorkerInspection {
|
|
readonly inspection: z.output<typeof inspectionSchema>;
|
|
readonly finalization: AnalysisError | undefined;
|
|
}
|
|
|
|
// Each input rejection names the caller argument that requires correction.
|
|
const rejectedArgument = {
|
|
format: "path",
|
|
unsupported: "path",
|
|
selection: "table",
|
|
"column-selection": "columns",
|
|
"row-offset": "row_offset",
|
|
} as const;
|
|
|
|
const rejectedReply = (
|
|
reply: z.output<typeof replySchema> & { ok: false },
|
|
selectedPath: string,
|
|
capturedOutput: AnalysisCapturedOutput,
|
|
) => {
|
|
if (reply.reason === "unavailable")
|
|
return new AnalysisCapabilityUnavailableError(
|
|
"sqlite",
|
|
operation,
|
|
reply.message,
|
|
{ capturedOutput, userMessage: reply.message },
|
|
);
|
|
if (reply.reason === "column-evaluation") {
|
|
const readable = reply.readable_columns;
|
|
return new AnalysisCapabilityUnavailableError(
|
|
"sqlite",
|
|
operation,
|
|
reply.message,
|
|
{
|
|
capturedOutput,
|
|
userMessage: reply.message,
|
|
remediationAction: `The database is readable; only the listed column values failed. REA's SQLite connection loads no extensions or application functions and disables schema trust. ${
|
|
readable.length === 0
|
|
? "No other readable column was found"
|
|
: `Select columns whose values were read: columns: ${JSON.stringify(readable)} (CLI: one --column per name)`
|
|
}; omit table and use schema_scope: database to read the stored declarations without evaluating rows. Obtaining the failed values needs a SQLite connection able to evaluate them. Do not repeat the unchanged request.`,
|
|
},
|
|
);
|
|
}
|
|
if (reply.reason === "row-evaluation")
|
|
return new AnalysisCapabilityUnavailableError(
|
|
"sqlite",
|
|
operation,
|
|
reply.message,
|
|
{
|
|
capturedOutput,
|
|
userMessage: reply.message,
|
|
diagnostics: { selected_path: selectedPath },
|
|
remediationAction:
|
|
"SQLite read the selected schema but could not prepare or evaluate the requested rows. REA's private connection loads no extensions, application functions or application collations. The SQLite reason may identify a missing dependency; an unidentified query failure does not establish database corruption. Omit table and use schema_scope: database to inspect stored declarations. Obtaining the requested values may require the application's supported consistent export. Do not repeat the unchanged row request.",
|
|
},
|
|
);
|
|
if (reply.reason === "memory")
|
|
return new AnalysisResourceConstraintError(
|
|
operation,
|
|
"memory",
|
|
reply.message,
|
|
{
|
|
javascript_heap_bytes: 256 * 1024 * 1024,
|
|
},
|
|
{ capturedOutput, diagnostics: { selected_path: selectedPath } },
|
|
);
|
|
if (reply.reason === "output-limit")
|
|
return new AnalysisResourceConstraintError(
|
|
operation,
|
|
"transport",
|
|
reply.message,
|
|
{
|
|
sqlite_value_or_record_bytes: SQLITE_DATABASE_LIMITS.outputBytes,
|
|
sqlite_sql_statement_bytes: SQLITE_DATABASE_LIMITS.outputBytes,
|
|
worker_reply_bytes: SQLITE_DATABASE_LIMITS.outputBytes,
|
|
},
|
|
{
|
|
capturedOutput,
|
|
diagnostics: { selected_path: selectedPath },
|
|
retryable: false,
|
|
remediationAction:
|
|
"The SQLite value/record, SQL statement and worker JSON reply allowances are each fixed at 16 MiB; this refusal does not identify which was exceeded. worker_timeout_ms and client deadlines do not raise them. If it preserves the requested facts, select exact columns, reduce row_limit, or use schema_scope: inventory instead of database. This worker refusal leaves no completed Evidence to retrieve. Do not repeat the unchanged request or truncate required database bytes.",
|
|
},
|
|
);
|
|
if (reply.reason === "column-limit")
|
|
return new AnalysisResourceConstraintError(
|
|
operation,
|
|
"capacity",
|
|
reply.message,
|
|
{
|
|
selected_result_columns: reply.selected_columns,
|
|
engine_result_column_limit: reply.engine_column_limit,
|
|
},
|
|
{
|
|
capturedOutput,
|
|
diagnostics: { selected_path: selectedPath },
|
|
retryable: false,
|
|
remediationAction: `The selected database is readable; only the combined projection exceeded this connection's native result-column limit. Request at most ${String(reply.engine_column_limit)} columns per call, splitting wider facts across calls, or omit table to inspect stored declarations with schema_scope: database. The limit belongs to SQLite's connection, so worker_timeout_ms and client deadlines do not raise it. Do not repeat the unchanged request.`,
|
|
},
|
|
);
|
|
const argument = rejectedArgument[reply.reason];
|
|
return new AnalysisInputError(operation, { capturedOutput }, [
|
|
{
|
|
path: [argument],
|
|
reason: "invalid_format",
|
|
// The worker sees only the private snapshot, so name the caller's selection here.
|
|
message:
|
|
argument === "path"
|
|
? `Selected SQLite database is invalid (${reply.message}): ${selectedPath}`
|
|
: reply.message,
|
|
},
|
|
]);
|
|
};
|
|
|
|
/** Execute only the private snapshot and validate the bounded worker protocol. */
|
|
export const executeSqliteDatabaseWorker = async (request: {
|
|
readonly input: InspectSqliteDatabaseInput;
|
|
readonly root: string;
|
|
readonly snapshotPath: string;
|
|
readonly timeoutMs: number;
|
|
readonly environment: Readonly<NodeJS.ProcessEnv>;
|
|
readonly resourceScope: ArtifactResourceScope;
|
|
readonly launcher?: SqliteWorkerLauncher;
|
|
readonly signal?: AbortSignal;
|
|
readonly captured: (output: AnalysisCapturedOutput) => void;
|
|
readonly retainCleanup?: (
|
|
owner: ProviderProcessSupervisor,
|
|
result: Extract<ProviderProcessStopResult, { status: "incomplete" }>,
|
|
) => void;
|
|
}): Promise<SqliteWorkerInspection> => {
|
|
const requestPath = join(request.root, "request.json");
|
|
const replyPath = join(request.root, "reply.json");
|
|
await writeFile(
|
|
requestPath,
|
|
JSON.stringify({
|
|
snapshot_path: request.snapshotPath,
|
|
reply_path: replyPath,
|
|
input: request.input,
|
|
}),
|
|
{ flag: "wx", mode: 0o600 },
|
|
);
|
|
const { NODE_OPTIONS: _ambientNodeOptions, ...environment } =
|
|
request.environment;
|
|
const execution = await runOwnedCommand(
|
|
{
|
|
command: process.execPath,
|
|
arguments: [
|
|
"--max-old-space-size=256",
|
|
fileURLToPath(new URL("./SqliteDatabaseWorker.js", import.meta.url)),
|
|
requestPath,
|
|
],
|
|
cwd: request.root,
|
|
expectedCommand: null,
|
|
runId: `rea-sqlite-database-${randomUUID()}`,
|
|
hostEnvironment: environment,
|
|
},
|
|
{
|
|
timeoutMs: request.timeoutMs,
|
|
diagnosticBytes: SQLITE_DATABASE_LIMITS.diagnosticBytes,
|
|
},
|
|
{
|
|
...(request.signal === undefined ? {} : { signal: request.signal }),
|
|
...(request.launcher === undefined ? {} : { launcher: request.launcher }),
|
|
...(request.retainCleanup === undefined
|
|
? {}
|
|
: { retainCleanup: request.retainCleanup }),
|
|
},
|
|
);
|
|
const capturedOutput = capturedSqliteOutput(execution);
|
|
request.captured(capturedOutput);
|
|
let reply: z.output<typeof replySchema>;
|
|
let finalization: AnalysisError | undefined;
|
|
try {
|
|
let file;
|
|
try {
|
|
file = await readStableArtifact(
|
|
replyPath,
|
|
SQLITE_DATABASE_LIMITS.outputBytes,
|
|
request.signal,
|
|
undefined,
|
|
request.resourceScope,
|
|
);
|
|
} catch (cause: unknown) {
|
|
const completed = completedStableArtifact(cause);
|
|
if (!(cause instanceof ArtifactReaderFailure) || completed === undefined)
|
|
throw cause;
|
|
finalization = sqliteReplyCompletionFailure(cause, capturedOutput);
|
|
file = completed;
|
|
}
|
|
const decoded = safeParseUtf8Json(file.bytes);
|
|
if (!decoded.ok) throw decoded.cause;
|
|
reply = replySchema.parse(decoded.value);
|
|
} catch (cause: unknown) {
|
|
throw sqliteReplyFinalizationFailure(
|
|
sqliteReplyReadFailure(cause, capturedOutput),
|
|
finalization,
|
|
);
|
|
}
|
|
if (!reply.ok)
|
|
throw sqliteReplyFinalizationFailure(
|
|
rejectedReply(reply, request.input.path, capturedOutput),
|
|
finalization,
|
|
);
|
|
return { inspection: reply.inspection, finalization };
|
|
};
|
|
|
|
const sqliteReplyReadFailure = (
|
|
cause: unknown,
|
|
capturedOutput: AnalysisCapturedOutput,
|
|
): AnalysisError => {
|
|
const options = {
|
|
cause,
|
|
capturedOutput,
|
|
...(cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined
|
|
? { cleanup: cause.cleanup }
|
|
: {}),
|
|
};
|
|
const error =
|
|
cause instanceof ArtifactReaderFailure && cause.reason === "cancelled"
|
|
? new AnalysisCancelledError(operation, {
|
|
...options,
|
|
cause: artifactFileCancellationCause(cause),
|
|
})
|
|
: new AnalysisOutputError(
|
|
operation,
|
|
`Owned SQLite worker reply is missing or malformed: ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
options,
|
|
);
|
|
bindArtifactFileCleanup(cause, error);
|
|
return error;
|
|
};
|
|
|
|
/** Stable bytes remain usable when only their descriptor's final close failed. */
|
|
const sqliteReplyCompletionFailure = (
|
|
cause: ArtifactReaderFailure,
|
|
capturedOutput: AnalysisCapturedOutput,
|
|
): AnalysisError => {
|
|
if (cause.cleanup === undefined)
|
|
return sqliteReplyReadFailure(cause, capturedOutput);
|
|
const cleanup = new ProviderCleanupError(
|
|
"sqlite",
|
|
cause.cleanup.resources,
|
|
{ phase: "reply_descriptor_close", reason: cause.cleanup.reason },
|
|
{ operation, cause, capturedOutput },
|
|
);
|
|
bindArtifactFileCleanup(cause, cleanup);
|
|
if (cause.reason !== "cancelled") return cleanup;
|
|
const cancellation = new AnalysisCancelledError(operation, {
|
|
cause: artifactFileCancellationCause(cause),
|
|
capturedOutput,
|
|
});
|
|
return analysisErrorWithCleanupFailure(
|
|
cancellation,
|
|
cleanup,
|
|
operation,
|
|
).bindCleanupDependencies([cancellation, cleanup]);
|
|
};
|
|
|
|
/** A malformed reply or producer refusal stays primary over its later close. */
|
|
export const sqliteReplyFinalizationFailure = (
|
|
primary: AnalysisError,
|
|
finalization: AnalysisError | undefined,
|
|
): AnalysisError =>
|
|
finalization === undefined
|
|
? primary
|
|
: finalization.cleanupIncomplete
|
|
? analysisErrorWithCleanupFailure(
|
|
primary,
|
|
finalization,
|
|
operation,
|
|
).bindCleanupDependencies([primary, finalization])
|
|
: primary.retainSecondaryFailure(finalization);
|