mirror of
https://github.com/morluto/rea.git
synced 2026-11-23 23:15:58 +00:00
fix(environment): preserve state-backed read match provenance (#13621)
This commit is contained in:
1 parent
f18de40af6
commit
3c51cde2ef
7 files changed
+210
-204
No files matched your search
@@ -172,10 +172,14 @@ describe("replayEnvironmentTool selection", () => {
|
||||
]);
|
||||
const args = { query: ["a", "c"], type: "b" };
|
||||
expect(
|
||||
selectReplayExchange(search, exchanges, args, "?query=a&type=b&query=c"),
|
||||
selectReplayExchange(search, exchanges, args, {
|
||||
observedQuery: "?query=a&type=b&query=c",
|
||||
}),
|
||||
).toMatchObject({ exchange: { ordinal: first }, exact: true });
|
||||
expect(
|
||||
selectReplayExchange(search, exchanges, args, "?query=a&query=c&type=b"),
|
||||
selectReplayExchange(search, exchanges, args, {
|
||||
observedQuery: "?query=a&query=c&type=b",
|
||||
}),
|
||||
).toMatchObject({ exchange: { ordinal: second }, exact: true });
|
||||
expect(selectReplayExchange(search, exchanges, args)).toMatchObject({
|
||||
exchange: { ordinal: first },
|
||||
@@ -195,7 +199,7 @@ describe("replayEnvironmentTool selection", () => {
|
||||
search,
|
||||
translated,
|
||||
{ query: ["seed", "c"], type: "b" },
|
||||
"?query=live&type=b&query=c",
|
||||
{ observedQuery: "?query=live&type=b&query=c" },
|
||||
),
|
||||
).toMatchObject({ exchange: { ordinal: first }, exact: true });
|
||||
});
|
||||
|
||||
@@ -178,18 +178,31 @@ const outranks = (score: MatchScore, best: MatchScore): boolean =>
|
||||
? score.queryMatches > best.queryMatches
|
||||
: score.observedOrderMatches > best.observedOrderMatches;
|
||||
|
||||
/** Choose the record whose path segments, then verbatim spellings, then query values best match the call; ties keep manifest order. */
|
||||
/** The selected recording and whether the call identifies its request exactly. */
|
||||
export interface ReplaySelection {
|
||||
readonly exchange: RecordedExchange;
|
||||
readonly exact: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Choose the record whose path segments, then verbatim spellings, then query values best match the call.
|
||||
* When only some ordinals can supply a response, all cited recordings still inform query-order ambiguity.
|
||||
*/
|
||||
export const selectReplayExchange = (
|
||||
tool: EnvironmentManifestTool,
|
||||
exchanges: ReadonlyMap<number, RecordedExchange>,
|
||||
args: ReplayArguments,
|
||||
observedQuery?: ObservedQuery,
|
||||
):
|
||||
| { readonly exchange: RecordedExchange; readonly exact: boolean }
|
||||
| undefined => {
|
||||
options: {
|
||||
readonly observedQuery?: ObservedQuery | undefined;
|
||||
readonly eligibleOrdinals?: ReadonlySet<number>;
|
||||
} = {},
|
||||
): ReplaySelection | undefined => {
|
||||
const { observedQuery, eligibleOrdinals } = options;
|
||||
let best: { exchange: RecordedExchange; score: MatchScore } | undefined;
|
||||
const argumentsMap = environmentToolArguments(tool);
|
||||
for (const ordinal of tool.record_ordinals) {
|
||||
if (eligibleOrdinals !== undefined && !eligibleOrdinals.has(ordinal))
|
||||
continue;
|
||||
const exchange = exchanges.get(ordinal);
|
||||
if (exchange === undefined) continue;
|
||||
const score = scoreExchange(
|
||||
@@ -209,54 +222,46 @@ export const selectReplayExchange = (
|
||||
ownMember(args, argument) === undefined ? [] : [name],
|
||||
),
|
||||
);
|
||||
const queryWasSupplied = suppliedQueryNames.size > 0;
|
||||
const canInspectQuery = observedQuery !== undefined || queryWasSupplied;
|
||||
const bestPairs = canInspectQuery
|
||||
? [
|
||||
...iterateUrlQueryParameters(
|
||||
best.exchange.query ?? "",
|
||||
suppliedQueryNames,
|
||||
),
|
||||
]
|
||||
: [];
|
||||
const orderAmbiguous =
|
||||
observedQuery === undefined &&
|
||||
queryWasSupplied &&
|
||||
best.score.exact &&
|
||||
tool.record_ordinals.some((ordinal) => {
|
||||
const candidate = exchanges.get(ordinal);
|
||||
if (
|
||||
candidate === undefined ||
|
||||
candidate.ordinal === best.exchange.ordinal
|
||||
if (
|
||||
observedQuery !== undefined ||
|
||||
suppliedQueryNames.size === 0 ||
|
||||
!best.score.exact
|
||||
)
|
||||
return { exchange: best.exchange, exact: best.score.exact };
|
||||
const bestPairs = [
|
||||
...iterateUrlQueryParameters(best.exchange.query ?? "", suppliedQueryNames),
|
||||
];
|
||||
const orderAmbiguous = tool.record_ordinals.some((ordinal) => {
|
||||
const candidate = exchanges.get(ordinal);
|
||||
if (candidate === undefined || candidate.ordinal === best.exchange.ordinal)
|
||||
return false;
|
||||
const score = scoreExchange(
|
||||
tool,
|
||||
argumentsMap.path,
|
||||
argumentsMap.query,
|
||||
candidate,
|
||||
args,
|
||||
);
|
||||
if (
|
||||
score.pathMatches !== best.score.pathMatches ||
|
||||
score.verbatimMatches !== best.score.verbatimMatches ||
|
||||
!score.exact
|
||||
)
|
||||
return false;
|
||||
const pairs = [
|
||||
...iterateUrlQueryParameters(candidate.query ?? "", suppliedQueryNames),
|
||||
];
|
||||
return (
|
||||
pairs.length !== bestPairs.length ||
|
||||
pairs.some(
|
||||
([name, value], index) =>
|
||||
bestPairs[index]?.[0] !== name || bestPairs[index]?.[1] !== value,
|
||||
)
|
||||
return false;
|
||||
const score = scoreExchange(
|
||||
tool,
|
||||
argumentsMap.path,
|
||||
argumentsMap.query,
|
||||
candidate,
|
||||
args,
|
||||
);
|
||||
if (
|
||||
score.pathMatches !== best.score.pathMatches ||
|
||||
score.verbatimMatches !== best.score.verbatimMatches ||
|
||||
!score.exact
|
||||
)
|
||||
return false;
|
||||
const pairs = [
|
||||
...iterateUrlQueryParameters(candidate.query ?? "", suppliedQueryNames),
|
||||
];
|
||||
return (
|
||||
pairs.length !== bestPairs.length ||
|
||||
pairs.some(
|
||||
([name, value], index) =>
|
||||
bestPairs[index]?.[0] !== name || bestPairs[index]?.[1] !== value,
|
||||
)
|
||||
);
|
||||
});
|
||||
);
|
||||
});
|
||||
return {
|
||||
exchange: best.exchange,
|
||||
exact: best.score.exact && !orderAmbiguous,
|
||||
exact: !orderAmbiguous,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -351,12 +356,9 @@ export const replayEnvironmentTool = (
|
||||
args: ReplayArguments,
|
||||
observedQuery?: ObservedQuery,
|
||||
): Result<ReplayResult, AnalysisError> => {
|
||||
const selected = selectReplayExchange(
|
||||
tool,
|
||||
source.exchanges,
|
||||
args,
|
||||
const selected = selectReplayExchange(tool, source.exchanges, args, {
|
||||
observedQuery,
|
||||
);
|
||||
});
|
||||
if (selected === undefined)
|
||||
return err(
|
||||
new AnalysisInputError(
|
||||
|
||||
@@ -73,11 +73,13 @@ it("keeps observed query order distinct from calls supplying only selected field
|
||||
`?q=hit&${ignored}&${ignored}`,
|
||||
])
|
||||
expect(
|
||||
selectReplayExchange(tool, exchanges, args, observed)?.exact,
|
||||
selectReplayExchange(tool, exchanges, args, { observedQuery: observed })
|
||||
?.exact,
|
||||
observed,
|
||||
).toBe(false);
|
||||
expect(
|
||||
selectReplayExchange(tool, exchanges, args, `?${ignored}&${ignored}&q=hit`)
|
||||
?.exact,
|
||||
selectReplayExchange(tool, exchanges, args, {
|
||||
observedQuery: `?${ignored}&${ignored}&q=hit`,
|
||||
})?.exact,
|
||||
).toBe(true);
|
||||
});
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
type StateServing,
|
||||
} from "./environmentStateAnswer.js";
|
||||
import { EnvironmentStateStore } from "./environmentStateStore.js";
|
||||
import type { ObservedQuery } from "./environmentReplay.js";
|
||||
|
||||
const grafana = environmentStateServeInputs();
|
||||
|
||||
@@ -53,27 +54,18 @@ const answer = (
|
||||
serving: StateServing,
|
||||
name: string,
|
||||
args: Readonly<Record<string, unknown>>,
|
||||
observedQuery?: ObservedQuery,
|
||||
) => {
|
||||
const result = answerFromState(serving, toolOf(serving.source, name), args);
|
||||
const result = answerFromState(
|
||||
serving,
|
||||
toolOf(serving.source, name),
|
||||
args,
|
||||
observedQuery,
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
return result.value;
|
||||
};
|
||||
|
||||
it("finds state entities using the recorded path's repeated separators", () => {
|
||||
const serving = servingFrom([
|
||||
["GET", "/api//books/1", { id: 1, title: "Book" }],
|
||||
]);
|
||||
const tool = serving.source.manifest.tools.find(
|
||||
(candidate) => candidate.path_template === "/api//books/{numeric}",
|
||||
);
|
||||
if (tool === undefined) throw new Error("Missing double-separator item tool");
|
||||
const result = answerFromState(serving, tool, { id: "1" });
|
||||
expect(result).toMatchObject({
|
||||
ok: true,
|
||||
value: { body: { id: 1, title: "Book" }, state: { source: "state" } },
|
||||
});
|
||||
});
|
||||
|
||||
const refusal = (
|
||||
serving: StateServing,
|
||||
name: string,
|
||||
@@ -84,51 +76,6 @@ const refusal = (
|
||||
return projectAnalysisError(result.error);
|
||||
};
|
||||
|
||||
/** A list with one proved whole line keeps an entity added to an empty later page off that page. */
|
||||
const expectAddedEntityStaysOffPage = (
|
||||
query: string,
|
||||
args: Readonly<Record<string, unknown>>,
|
||||
membership: "recorded" | "query" = "query",
|
||||
): void => {
|
||||
const alpha = { id: 1, name: "Alpha" };
|
||||
const serving = servingFrom([
|
||||
["GET", "/api/orgs/1/books", [alpha]],
|
||||
["GET", "/api/orgs/1/books/1", alpha],
|
||||
["GET", `/api/orgs/2/books?${query}`, []],
|
||||
]);
|
||||
expect(serving.store.state.views.get("get_orgs_books_by_id")).toMatchObject({
|
||||
shape: "list",
|
||||
membership: "recorded",
|
||||
});
|
||||
load(serving, (entities) => [
|
||||
...entities,
|
||||
{
|
||||
type: "/api/orgs/{numeric}/books",
|
||||
collection: "/api/orgs/2/books",
|
||||
id: "9",
|
||||
fields: { id: 9, name: "Added" },
|
||||
},
|
||||
]);
|
||||
expect(
|
||||
answer(serving, "get_orgs_books_by_id", { id: "2", ...args }),
|
||||
).toMatchObject({
|
||||
body: [],
|
||||
state: { source: "state", membership, listed: 0 },
|
||||
});
|
||||
// Without a proved whole line here, the argument-less call keeps recorded members.
|
||||
expect(answer(serving, "get_orgs_books_by_id", { id: "2" })).toMatchObject({
|
||||
body: [],
|
||||
state:
|
||||
membership === "query"
|
||||
? { source: "state", membership: "recorded", listed: 0 }
|
||||
: { source: "recording", reason: "unrecorded-request" },
|
||||
});
|
||||
};
|
||||
|
||||
/** A list with one proved whole line keeps an entity added to an empty start page off that page. */
|
||||
const expectAddedEntityStaysOffStartPage = (name: string): void =>
|
||||
expectAddedEntityStaysOffPage(`${name}=1`, { [name]: "1" });
|
||||
|
||||
/** Replace the served state with the initial one changed by `edit`. */
|
||||
const load = (
|
||||
serving: ReturnType<typeof servingOf>,
|
||||
@@ -304,21 +251,6 @@ describe("item answers", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("loaded later pages", () => {
|
||||
it.each(["offset", "start", "_start"])(
|
||||
"skips an entity added under an empty ?%s=1 page without whole-collection evidence",
|
||||
expectAddedEntityStaysOffStartPage,
|
||||
);
|
||||
|
||||
it("does not list an entity added under an empty ?page=2&per_page=1 page", () => {
|
||||
expectAddedEntityStaysOffPage(
|
||||
"page=2&per_page=1",
|
||||
{ page: "2", per_page: "1" },
|
||||
"recorded",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("list answers", () => {
|
||||
it("replays repeated query values instead of applying scalar state-query semantics", () => {
|
||||
const serving = servingFrom([
|
||||
@@ -499,6 +431,83 @@ describe("list answer coverage and bounds", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("state-backed request provenance", () => {
|
||||
it("keeps the item envelope while reporting indistinguishable query orders", () => {
|
||||
const books = servingFrom([
|
||||
["GET", "/api/books/1?locale=en&format=json", { id: 1, title: "Book" }],
|
||||
["GET", "/api/books/1?format=json&locale=en", { id: 1, title: "Book" }],
|
||||
]);
|
||||
expect(
|
||||
answer(books, "get_books_by_id", {
|
||||
id: "1",
|
||||
locale: "en",
|
||||
format: "json",
|
||||
}),
|
||||
).toMatchObject({
|
||||
body: { id: 1, title: "Book" },
|
||||
replay: { record_ordinal: 0, exact_match: false },
|
||||
state: { source: "state", view: "item" },
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves query order provenance even after an exact page outgrows its bound", () => {
|
||||
const first = "?size=2&limit=1";
|
||||
const second = "?limit=1&size=2";
|
||||
const books = servingFrom([
|
||||
["GET", `/api/books${first}`, [{ id: 1 }]],
|
||||
["GET", `/api/books${second}`, [{ id: 1 }]],
|
||||
["GET", "/api/books/1", { id: 1 }],
|
||||
]);
|
||||
const args = { size: "2", limit: "1" };
|
||||
expect.soft(answer(books, "get_books", args)).toMatchObject({
|
||||
body: [{ id: 1 }],
|
||||
replay: { record_ordinal: 0, exact_match: false },
|
||||
state: { source: "state", membership: "all" },
|
||||
});
|
||||
expect.soft(answer(books, "get_books", args, second)).toMatchObject({
|
||||
body: [{ id: 1 }],
|
||||
replay: { record_ordinal: 1, exact_match: true },
|
||||
state: { source: "state", membership: "all" },
|
||||
});
|
||||
|
||||
load(books, (entities) => [
|
||||
...entities,
|
||||
{
|
||||
type: "/api/books",
|
||||
collection: "/api/books",
|
||||
id: "2",
|
||||
fields: { id: 2 },
|
||||
},
|
||||
]);
|
||||
expect(answer(books, "get_books", args, second)).toMatchObject({
|
||||
body: [{ id: 1 }],
|
||||
replay: { record_ordinal: 1, exact_match: true },
|
||||
state: { source: "recording", reason: "page-exceeded" },
|
||||
});
|
||||
expect(answer(books, "get_books", args)).toMatchObject({
|
||||
body: [{ id: 1 }],
|
||||
replay: { record_ordinal: 0, exact_match: false },
|
||||
state: { source: "recording", reason: "page-exceeded" },
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the checked list envelope when a later query also matches without order", () => {
|
||||
const books = servingFrom([
|
||||
["GET", "/api/books?size=2&limit=1", [{ id: 1 }]],
|
||||
["GET", "/api/books/1", { id: 1 }],
|
||||
["POST", "/api/books", { id: 2 }, 201, { id: 2 }],
|
||||
["GET", "/api/books?limit=1&size=2", [{ id: 2 }]],
|
||||
]);
|
||||
expect(answer(books, "get_books", { size: "2", limit: "1" })).toMatchObject(
|
||||
{
|
||||
body: [{ id: 1 }],
|
||||
replay: { record_ordinal: 0, exact_match: false },
|
||||
state: { source: "state", membership: "all" },
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("recorded and document answers", () => {
|
||||
it("replays recorded views and tools without a view, saying why", () => {
|
||||
const serving = servingOf();
|
||||
@@ -523,14 +532,11 @@ describe("recorded and document answers", () => {
|
||||
});
|
||||
|
||||
it("caps a state-backed document by its exact serialized UTF-8 body bytes", () => {
|
||||
const capture = timedCaptureEvidence([
|
||||
const serving = servingFrom([
|
||||
["GET", "/api/settings", { theme: "dark" }],
|
||||
["PUT", "/api/settings", { theme: "light" }],
|
||||
["GET", "/api/settings", { theme: "light" }],
|
||||
]);
|
||||
const serving = servingOf(
|
||||
environmentStateServeInputs(environmentStateServeFixture(capture)),
|
||||
);
|
||||
const loadDocument = (value: string) =>
|
||||
load(serving, (entities) => entities, [
|
||||
{ tool: "get_settings", path: "/api/settings", value },
|
||||
@@ -563,27 +569,24 @@ describe("recorded and document answers", () => {
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok)
|
||||
throw new Error("Expected the oversized state answer to be refused");
|
||||
expect(result.error).toMatchObject({
|
||||
_tag: "AnalysisResourceConstraintError",
|
||||
operation: "environment-serve",
|
||||
resource: "capacity",
|
||||
reportedLimits: {
|
||||
max_body_bytes: REPLAY_BODY_LIMIT_BYTES,
|
||||
body_bytes: bodyBytes,
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "resource_constraint",
|
||||
details: {
|
||||
reported_limits: {
|
||||
max_body_bytes: REPLAY_BODY_LIMIT_BYTES,
|
||||
body_bytes: bodyBytes,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(serving.store.snapshot()).toEqual(before);
|
||||
});
|
||||
|
||||
it("answers a document's recorded line with the state's value for it", () => {
|
||||
const capture = timedCaptureEvidence([
|
||||
const serving = servingFrom([
|
||||
["GET", "/api/settings", { theme: "dark", density: "compact" }],
|
||||
["PUT", "/api/settings", { theme: "light", density: "compact" }],
|
||||
["GET", "/api/settings", { theme: "light", density: "compact" }],
|
||||
]);
|
||||
const serving = servingOf(
|
||||
environmentStateServeInputs(environmentStateServeFixture(capture)),
|
||||
);
|
||||
expect(answer(serving, "get_settings", {})).toMatchObject({
|
||||
body: { theme: "dark", density: "compact" },
|
||||
replay: { record_ordinal: 0, exact_match: true },
|
||||
@@ -632,19 +635,6 @@ describe("recorded and document answers", () => {
|
||||
0,
|
||||
"record_ordinal",
|
||||
]);
|
||||
load(serving, (entities) => entities, [
|
||||
{
|
||||
tool: "get_settings",
|
||||
path: "/api/settings",
|
||||
value: "x".repeat(REPLAY_BODY_LIMIT_BYTES),
|
||||
},
|
||||
]);
|
||||
expect(refusal(serving, "get_settings", {})).toMatchObject({
|
||||
code: "resource_constraint",
|
||||
details: {
|
||||
reported_limits: { max_body_bytes: REPLAY_BODY_LIMIT_BYTES },
|
||||
},
|
||||
});
|
||||
load(serving, (entities) => entities);
|
||||
expect(refusal(serving, "get_settings", {})).toMatchObject({
|
||||
message: expect.stringContaining("holds no document"),
|
||||
|
||||
@@ -45,6 +45,7 @@ import {
|
||||
type ObservedQuery,
|
||||
type ReplayArguments,
|
||||
type ReplayResult,
|
||||
type ReplaySelection,
|
||||
} from "./environmentReplay.js";
|
||||
import {
|
||||
ENVIRONMENT_SERVE_OPERATION,
|
||||
@@ -177,7 +178,7 @@ export const recordedJson = (
|
||||
/** The rendered body on the base record's status, content type and provenance; never cut. */
|
||||
export const stateAnswer = (
|
||||
serving: StateServing,
|
||||
base: { readonly exchange: RecordedExchange; readonly exact: boolean },
|
||||
base: ReplaySelection,
|
||||
body: JsonValue,
|
||||
state: StateProvenance,
|
||||
): Result<StateAnswer, AnalysisError> => {
|
||||
@@ -404,7 +405,7 @@ const answerItem = (
|
||||
replayed !== undefined &&
|
||||
!store.createdInto(view.type) &&
|
||||
!startedWithItem(store, view.type, call) &&
|
||||
selectReplayExchange(tool, source.exchanges, args, observedQuery)
|
||||
selectReplayExchange(tool, source.exchanges, args, { observedQuery })
|
||||
?.exact === true
|
||||
)
|
||||
return fromRecording(source, tool, args, replayed, observedQuery);
|
||||
@@ -430,12 +431,10 @@ const answerItem = (
|
||||
refused(tool, `Tool ${tool.name} has no usable recorded envelope.`),
|
||||
);
|
||||
const exact =
|
||||
selectReplayExchange(
|
||||
tool,
|
||||
new Map([[base.ordinal, base]]),
|
||||
args,
|
||||
selectReplayExchange(tool, source.exchanges, args, {
|
||||
observedQuery,
|
||||
)?.exact === true;
|
||||
eligibleOrdinals: new Set([base.ordinal]),
|
||||
})?.exact === true;
|
||||
return stateAnswer(
|
||||
serving,
|
||||
{ exchange: base, exact },
|
||||
@@ -452,11 +451,12 @@ const answerItem = (
|
||||
|
||||
type StateDocumentView = Extract<StateView, { shape: "document" }>;
|
||||
|
||||
/** One tool call: the tool, the arguments it was called with, and whether they name the answering line exactly. */
|
||||
interface ToolCall {
|
||||
/** A list call can name checked lines without distinguishing their query order. */
|
||||
interface ListCall {
|
||||
readonly tool: EnvironmentManifestTool;
|
||||
readonly args: ReplayArguments;
|
||||
readonly exact: boolean;
|
||||
readonly observedQuery: ObservedQuery | undefined;
|
||||
readonly named: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -466,7 +466,7 @@ interface ToolCall {
|
||||
*/
|
||||
const listSelection = (
|
||||
store: EnvironmentStateStore,
|
||||
{ tool, args, exact }: ToolCall,
|
||||
{ tool, args, named }: ListCall,
|
||||
view: StateListView,
|
||||
line: {
|
||||
readonly base: RecordedExchange;
|
||||
@@ -484,7 +484,7 @@ const listSelection = (
|
||||
// A named query line, or a call with query arguments answered on a line it did not name, evaluates the query.
|
||||
const queried =
|
||||
view.query !== undefined &&
|
||||
(exact
|
||||
(named
|
||||
? view.query.record_ordinals.includes(line.base.ordinal)
|
||||
: values.size > 0);
|
||||
if (queried) {
|
||||
@@ -514,19 +514,20 @@ const listSelection = (
|
||||
/** A list call renders the entities its line selects from the state into that line's recorded envelope. */
|
||||
const answerList = (
|
||||
serving: StateServing,
|
||||
call: ToolCall,
|
||||
call: ListCall,
|
||||
view: StateListView,
|
||||
base: RecordedExchange,
|
||||
match: ReplaySelection,
|
||||
): Result<StateAnswer, AnalysisError> => {
|
||||
const { source, store } = serving;
|
||||
const { tool, args, exact } = call;
|
||||
const { tool, args, named, observedQuery } = call;
|
||||
const base = match.exchange;
|
||||
const envelope = recordedJson(base);
|
||||
const recorded =
|
||||
envelope === undefined ? undefined : listItems(envelope, view.pointer);
|
||||
if (envelope === undefined || recorded === undefined)
|
||||
return fromRecording(source, tool, args, "body-unusable");
|
||||
return fromRecording(source, tool, args, "body-unusable", observedQuery);
|
||||
// A requested page the collection has outgrown is answered as recorded, never with more items than it asked for.
|
||||
const size = exact
|
||||
const size = named
|
||||
? pageBound(base.query ?? undefined, recorded.length)
|
||||
: undefined;
|
||||
if (
|
||||
@@ -534,10 +535,16 @@ const answerList = (
|
||||
size !== undefined &&
|
||||
store.inCollection(view.type, collectionPathOf(base, false)).length > size
|
||||
)
|
||||
return fromRecording(source, tool, args, "page-exceeded");
|
||||
return fromRecording(source, tool, args, "page-exceeded", observedQuery);
|
||||
const selection = listSelection(store, call, view, { base, recorded });
|
||||
if (selection === undefined)
|
||||
return fromRecording(source, tool, args, "unrecorded-request");
|
||||
return fromRecording(
|
||||
source,
|
||||
tool,
|
||||
args,
|
||||
"unrecorded-request",
|
||||
observedQuery,
|
||||
);
|
||||
const volatile = new Set(store.type(view.type)?.volatile_fields);
|
||||
const items: JsonObject[] = [];
|
||||
for (const entity of selection.members) {
|
||||
@@ -554,7 +561,7 @@ const answerList = (
|
||||
items,
|
||||
selection.total,
|
||||
);
|
||||
return stateAnswer(serving, { exchange: base, exact }, body, {
|
||||
return stateAnswer(serving, match, body, {
|
||||
source: "state",
|
||||
view: "list",
|
||||
type: view.type,
|
||||
@@ -568,12 +575,12 @@ const answerList = (
|
||||
const answerDocument = (
|
||||
serving: StateServing,
|
||||
tool: EnvironmentManifestTool,
|
||||
base: RecordedExchange,
|
||||
selection: ReplaySelection,
|
||||
): Result<StateAnswer, AnalysisError> => {
|
||||
const current = serving.store.document(tool.name);
|
||||
if (current === undefined)
|
||||
return err(refused(tool, `The state holds no document for ${tool.name}.`));
|
||||
return stateAnswer(serving, { exchange: base, exact: true }, current.value, {
|
||||
return stateAnswer(serving, selection, current.value, {
|
||||
source: "state",
|
||||
view: "document",
|
||||
path: current.path,
|
||||
@@ -602,7 +609,7 @@ const answerCheckedLine = (
|
||||
observedQuery,
|
||||
);
|
||||
const base =
|
||||
named ??
|
||||
named?.exchange ??
|
||||
(view.shape === "list"
|
||||
? (unfilteredLine(
|
||||
serving.source,
|
||||
@@ -620,15 +627,15 @@ const answerCheckedLine = (
|
||||
"unrecorded-request",
|
||||
observedQuery,
|
||||
);
|
||||
// An unfiltered call answers on a line it did not name, so its replay match is not exact.
|
||||
const selection = named ?? { exchange: base, exact: false };
|
||||
return view.shape === "list"
|
||||
? answerList(
|
||||
serving,
|
||||
{ tool, args, exact: named !== undefined },
|
||||
{ tool, args, observedQuery, named: named !== undefined },
|
||||
view,
|
||||
base,
|
||||
selection,
|
||||
)
|
||||
: answerDocument(serving, tool, base);
|
||||
: answerDocument(serving, tool, selection);
|
||||
};
|
||||
|
||||
/** Answer one read tool call from the live state where its view is state-backed, else from its recordings. */
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
selectsRecordedLine,
|
||||
type ObservedQuery,
|
||||
type ReplayArguments,
|
||||
type ReplaySelection,
|
||||
} from "./environmentReplay.js";
|
||||
import type {
|
||||
EnvironmentManifestTool,
|
||||
@@ -50,17 +51,20 @@ export const checkedLine = (
|
||||
checked: readonly number[],
|
||||
args: ReplayArguments,
|
||||
observedQuery?: ObservedQuery,
|
||||
): RecordedExchange | undefined => {
|
||||
const lines = new Map<number, RecordedExchange>();
|
||||
): ReplaySelection | undefined => {
|
||||
const eligible = new Set<number>();
|
||||
for (const ordinal of checked) {
|
||||
const exchange = source.exchanges.get(ordinal);
|
||||
if (
|
||||
exchange !== undefined &&
|
||||
selectsRecordedLine(tool, exchange, args, observedQuery)
|
||||
)
|
||||
lines.set(ordinal, exchange);
|
||||
eligible.add(ordinal);
|
||||
}
|
||||
return selectReplayExchange(tool, lines, args, observedQuery)?.exchange;
|
||||
return selectReplayExchange(tool, source.exchanges, args, {
|
||||
observedQuery,
|
||||
eligibleOrdinals: eligible,
|
||||
});
|
||||
};
|
||||
|
||||
/** For a list of a whole collection, a call that supplies no query argument answers from a checked line of the collection its path arguments name that only pages it, chosen as replay chooses; a requested page answers from its recording. */
|
||||
@@ -90,7 +94,7 @@ export const unfilteredLine = (
|
||||
)
|
||||
lines.set(ordinal, exchange);
|
||||
}
|
||||
return selectReplayExchange(tool, lines, args, observedQuery)?.exchange;
|
||||
return selectReplayExchange(tool, lines, args, { observedQuery })?.exchange;
|
||||
};
|
||||
|
||||
/** A call's query arguments by parameter name. */
|
||||
@@ -134,5 +138,5 @@ export const queryLine = (
|
||||
)
|
||||
lines.set(ordinal, exchange);
|
||||
}
|
||||
return selectReplayExchange(tool, lines, args, observedQuery)?.exchange;
|
||||
return selectReplayExchange(tool, lines, args, { observedQuery })?.exchange;
|
||||
};
|
||||
@@ -410,12 +410,9 @@ export const writeAnswer = (
|
||||
if (plan.response === null || exchange === undefined)
|
||||
return err(refused(tool, `Tool ${tool.name} has no recorded response.`));
|
||||
const exact =
|
||||
selectReplayExchange(
|
||||
tool,
|
||||
new Map([[exchange.ordinal, exchange]]),
|
||||
args,
|
||||
request.observedQuery,
|
||||
)?.exact === true;
|
||||
selectReplayExchange(tool, new Map([[exchange.ordinal, exchange]]), args, {
|
||||
observedQuery: request.observedQuery,
|
||||
})?.exact === true;
|
||||
if (plan.response.shape === "recorded")
|
||||
return ok({ ...replayAnswer(serving.source, exchange, exact), state });
|
||||
if (typeof rendered !== "function" && "body" in rendered)
|
||||
|
||||
Reference in new issue
Block a user