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
6 changes: 6 additions & 0 deletions .changeset/strict-cache-long-test-id.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'e2e': patch
'@e2e-dev/core': patch
---

`--strict-cache` no longer fails with `REPLAY_STALE` a never-recorded step whose test id, target, or agent name is over 300 characters and starts like a recorded one.
1 change: 1 addition & 0 deletions docs/cache.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,7 @@ CI=1 bunx e2e run --strict-cache
| `invalid-entry`, `wrong-context`, `target-not-found`, `target-ambiguous`, `viewport-changed`, `action-failed`, `action-uncertain`, `end-mismatch`: the app or the entry changed | A step never recorded (a new or edited instruction or params) |
| `no-entry`, when the cache directory holds a recording of the same step under another key | A `gap` or a `truncated` recording |
| | A step whose store read fails |
| | A step whose test's `testId` in `report.json`, target name, or agent name is over 300 characters, when an earlier `e2e` version recorded it under another key and no `read-write` run of this version has replayed it since |

A recording under another key comes from an `e2e` upgrade that changed the
keys, or a change to the project id, the app's identity, or the agent's
Expand Down
1 change: 1 addition & 0 deletions docs/ja/cache.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,7 @@ CI=1 bunx e2e run --strict-cache
| `invalid-entry`、`wrong-context`、`target-not-found`、`target-ambiguous`、`viewport-changed`、`action-failed`、`action-uncertain`、`end-mismatch`: アプリまたはエントリーが変わった | 一度も記録されていないステップ(新規または編集済みの指示やパラメーター) |
| `no-entry`: キャッシュディレクトリに同じステップの記録が別のキーで存在する場合 | `gap` または `truncated` の記録 |
| | ストアの読み取りが失敗したステップ |
| | テストの `report.json` の `testId`、ターゲット名、エージェント名のいずれかが 300 文字を超えるステップで、以前の `e2e` バージョンが別のキーで記録し、その後このバージョンの `read-write` の実行で再生されていないもの |

別のキーの記録は、キーを変える `e2e` のアップグレード、プロジェクト ID、アプリの識別情報、エージェントのコンテキストの変更などで生じます。メッセージにはそのファイルと、現行バージョンで作られた記録なら変更点も示されます。何も再生しなくなったファイルは削除してください。この検査は、独自の `cache.store` には適用されません。

Expand Down
1 change: 1 addition & 0 deletions docs/zh/cache.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,7 @@ CI=1 bunx e2e run --strict-cache
| `invalid-entry`、`wrong-context`、`target-not-found`、`target-ambiguous`、`viewport-changed`、`action-failed`、`action-uncertain`、`end-mismatch`:应用或条目发生了变化 | 从未录制过的步骤(新建或编辑过的指令或参数) |
| `no-entry`,且缓存目录中存在使用其他键的同一步骤录制记录 | `gap` 或 `truncated` 录制记录 |
| | 从存储读取失败的步骤 |
| | 测试在 `report.json` 中的 `testId`、目标名称或智能体名称超过 300 个字符的步骤,且其录制记录由较早的 `e2e` 版本以其他键生成,之后也没有此版本的 `read-write` 运行回放过它 |

其他键下的录制记录可能来自改变键的 `e2e` 升级,也可能来自项目 ID、应用标识或智能体上下文的变化。消息会指出该文件;如果记录由当前版本生成,还会说明变化内容。如果已无回放使用该文件,请删除它。此检查不涵盖自定义 `cache.store`。

Expand Down
24 changes: 14 additions & 10 deletions packages/core/src/cache/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,8 @@ import type { JsonValue } from '../types.ts';
* stands. A kept entry carries no payload, so the replay's expansion of it
* (every `unique()` slot filled with this run's value) can never be written;
* confirmed, the file keeps its bytes and `createdAt`, and a committed cache
* directory stays clean, unless its provenance predates the step's
* occurrence fields (`recordedFor`, as stored), which the replay proved and
* are then written in. Unconfirmed, both kinds are evicted alike.
* directory stays clean, but for the provenance the replay proved, which
* `completeProvenance` writes in. Unconfirmed, both kinds are evicted alike.
*/
export type StagedTrace = {
readonly keyHash: string;
Expand Down Expand Up @@ -140,15 +139,19 @@ function flowOf(trace: ActionTrace): string {
}

/**
* Writes the step's full provenance into a kept entry recorded before the
* occurrence fields were, leaving every other entry untouched. Its replay
* proved which step it belongs to, and `cache.strict` matches only entries
* that say so exactly (`rekeyed.ts`).
* Writes the step's full provenance into a kept entry whose stored provenance
* lacks the occurrence fields, or whose identity digest is not the step's:
* missing while the step has one, different, or present while the step has
* none. Every other entry is left untouched. Its replay proved which step it
* belongs to, and `cache.strict` matches only entries that say so exactly
* (`rekeyed.ts`).
*/
async function completeProvenance(store: CacheStore, keyHash: string, recordedFor: TraceProvenance): Promise<void> {
const existing = await store.read(keyHash);
if (existing.status !== 'hit' || existing.entry.payload.recordedFor?.callIndex !== undefined) return;
await store.write(keyHash, { ...existing.entry.payload, recordedFor });
if (existing.status !== 'hit') return;
const stored = existing.entry.payload.recordedFor;
const complete = stored?.callIndex !== undefined && stored.identityDigest === recordedFor.identityDigest;
Comment thread
samanyudas marked this conversation as resolved.
Resolved
if (!complete) await store.write(keyHash, { ...existing.entry.payload, recordedFor });
}

/** How an attempt ended, as the settlement of its staged entries reads it. */
Expand Down Expand Up @@ -200,7 +203,8 @@ export interface SurvivedFailure {
* no settlement: interruption implicates nothing, so it writes nothing and
* evicts nothing. An entry a step replayed whole is staged too,
* so the same rule evicts it when nothing confirmed it; when something did,
* it is left exactly as it was found, but for provenance it lacked.
* it is left exactly as it was found, but for what `completeProvenance`
* writes in.
*/
export async function settleStagedTraces(context: AgentCacheContext, settlement: AttemptSettlement | undefined): Promise<ReadonlyMap<number, CacheWrite>> {
const outcomes = new Map<number, CacheWrite>();
Expand Down
14 changes: 10 additions & 4 deletions packages/core/src/cache/recorder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ import {
type TraceTargetDescriptor,
} from './trace.ts';
import { readRecordedModel } from './trace-fields.ts';
import { bound } from '../internal/text.ts';
import { sha256Hex } from '../internal/ids.ts';
import { bound, boundIsAmbiguous } from '../internal/text.ts';

/** The summary a run-time value gap records; the prose a project-tool gap would carry for a tool of that name. */
const DERIVED_GAP_SUMMARY = 'tool type (run-time value)';
Expand Down Expand Up @@ -342,12 +343,17 @@ function sameTarget(a: TraceTargetDescriptor | undefined, b: TraceTargetDescript
* the store holds.
*/
export function recordedProvenance(provenance: TraceProvenance, redact: (text: string) => string): TraceProvenance {
const testId = redact(provenance.testId);
const targetId = redact(provenance.targetId);
const agent = provenance.agent === undefined ? undefined : redact(provenance.agent);
const ambiguous = [testId, targetId, agent ?? ''].some((text) => boundIsAmbiguous(text, MAX_TRACE_DESCRIPTOR_CHARS));
return {
testId: bound(redact(provenance.testId), MAX_TRACE_DESCRIPTOR_CHARS),
targetId: bound(redact(provenance.targetId), MAX_TRACE_DESCRIPTOR_CHARS),
testId: bound(testId, MAX_TRACE_DESCRIPTOR_CHARS),
targetId: bound(targetId, MAX_TRACE_DESCRIPTOR_CHARS),
instructionDigest: provenance.instructionDigest,
...(provenance.paramsDigest === undefined ? {} : { paramsDigest: provenance.paramsDigest }),
...(provenance.callIndex === undefined ? {} : { callIndex: provenance.callIndex }),
...(provenance.agent === undefined ? {} : { agent: bound(redact(provenance.agent), MAX_TRACE_DESCRIPTOR_CHARS) }),
...(agent === undefined ? {} : { agent: bound(agent, MAX_TRACE_DESCRIPTOR_CHARS) }),
...(ambiguous ? { identityDigest: sha256Hex(JSON.stringify([testId, targetId, agent ?? null])) } : {}),
};
}
10 changes: 7 additions & 3 deletions packages/core/src/cache/rekeyed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,13 @@ export function storedRecordingsFor(cache: ResolvedCacheConfig): StoredRecording
return new StoredRecordings(new FileCacheStore({ directory: cache.dir, maxBytes: MAX_CACHE_WIRE_BYTES, writable: false }));
}

/** The whole step as one map key, or undefined when the provenance does not record all of it. */
/**
* The whole step as one map key, or undefined when the provenance does not
* record all of it. When an entry could store a name cut, the key includes
* `identityDigest`, so such a step never matches an entry without one.
*/
function stepKey(step: TraceProvenance): string | undefined {
const { testId, targetId, instructionDigest, paramsDigest, callIndex, agent } = step;
const { testId, targetId, instructionDigest, paramsDigest, callIndex, agent, identityDigest } = step;
if (paramsDigest === undefined || callIndex === undefined || agent === undefined) return undefined;
return JSON.stringify([testId, targetId, instructionDigest, paramsDigest, callIndex, agent]);
return JSON.stringify([testId, targetId, instructionDigest, paramsDigest, callIndex, agent, identityDigest ?? null]);
}
10 changes: 9 additions & 1 deletion packages/core/src/cache/trace-read.ts
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,11 @@ function readPosition(document: unknown): TracePosition | undefined {
return { index: index as number, of: of as number };
}

/** Whether a provenance field that may be absent is absent or a SHA-256 hex digest. */
function isOptionalDigest(value: unknown): value is string | undefined {
return value === undefined || (typeof value === 'string' && SHA256_HEX.test(value));
}

function readProvenance(document: unknown): TraceProvenance | undefined {
if (typeof document !== 'object' || document === null || Array.isArray(document)) {
return undefined;
Expand All @@ -419,20 +424,23 @@ function readProvenance(document: unknown): TraceProvenance | undefined {
if (testId === undefined || targetId === undefined) return undefined;
if (typeof instructionDigest !== 'string' || !SHA256_HEX.test(instructionDigest)) return undefined;
const paramsDigest = raw['paramsDigest'];
if (paramsDigest !== undefined && (typeof paramsDigest !== 'string' || !SHA256_HEX.test(paramsDigest))) return undefined;
if (!isOptionalDigest(paramsDigest)) return undefined;
const callIndex = raw['callIndex'];
if (callIndex !== undefined && (typeof callIndex !== 'number' || !Number.isSafeInteger(callIndex) || callIndex < 0)) {
return undefined;
}
const agent = raw['agent'] === undefined ? undefined : readBoundedText(raw['agent'], MAX_TRACE_DESCRIPTOR_CHARS);
if (raw['agent'] !== undefined && agent === undefined) return undefined;
const identityDigest = raw['identityDigest'];
if (!isOptionalDigest(identityDigest)) return undefined;
return {
testId,
targetId,
instructionDigest,
...(paramsDigest === undefined ? {} : { paramsDigest }),
...(callIndex === undefined ? {} : { callIndex }),
...(agent === undefined ? {} : { agent }),
...(identityDigest === undefined ? {} : { identityDigest }),
};
}

Expand Down
7 changes: 7 additions & 0 deletions packages/core/src/cache/trace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,13 @@ export interface TraceProvenance {
readonly callIndex?: number;
/** Name of the configured agent the step ran with. */
readonly agent?: string;
/**
* SHA-256 of the whole redacted test id, target id, and agent name, only
* when one of them is longer than an entry keeps or ends like a cut (a
* `createAgent` cache key can): two steps whose stored text is the same
* share the digest only when their names differ in a secret value alone.
*/
readonly identityDigest?: string;
}

/**
Expand Down
8 changes: 8 additions & 0 deletions packages/core/src/internal/text.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ export function bound(text: string, maxChars: number): string {
return `${text.slice(0, end)}…`;
}

/**
* Whether `bound(text, maxChars)` could equal what `bound` makes of a
* different text: it cuts `text`, or `text` already ends like a cut.
*/
export function boundIsAmbiguous(text: string, maxChars: number): boolean {
return text.length > maxChars || (text.length >= maxChars - 1 && text.endsWith('…'));
}

/**
* Normalizes text by trimming leading/trailing whitespace and replacing every
* nonempty run of Unicode whitespace with one ASCII space.
Expand Down
54 changes: 53 additions & 1 deletion packages/e2e/tests/unit/step-cache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ import { join } from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { settleStagedTraces, type AgentCacheContext, type ClaimedKey } from '@e2e-dev/core/lib/cache/context';
import { instructionDigest, paramsDigest } from '@e2e-dev/core/lib/cache/identity';
import { recordedProvenance } from '@e2e-dev/core/lib/cache/recorder';
import { StoredRecordings } from '@e2e-dev/core/lib/cache/rekeyed';
import { FileCacheStore, MAX_CACHE_WIRE_BYTES } from '@e2e-dev/core/lib/cache/store';
import { buildTraceEntry, type ActionTrace, type DerivedReason, type TraceEntry } from '@e2e-dev/core/lib/cache/trace';
import { buildTraceEntry, MAX_TRACE_DESCRIPTOR_CHARS, type ActionTrace, type DerivedReason, type TraceEntry } from '@e2e-dev/core/lib/cache/trace';
import { failedStepOutcome, recordedVerdictOf, StepTraceSession, type StepCacheHost, type StepCacheOptions } from '@e2e-dev/core/lib/agent/step-cache';
import { AgentError } from '@e2e-dev/core/lib/agent/error';
import type { ExecutorActions } from '@e2e-dev/core/lib/agent/executor';
Expand Down Expand Up @@ -1394,6 +1395,57 @@ describe('cache.strict and a step whose key changed under its recording', () =>
}
});

describe.each(['testId', 'targetId', 'agent'] as const)('when the %s is longer than an entry keeps', (field) => {
const long = 'checkout for a signed in customer with a saved card '.repeat(6);
const stepWith = (value: string) => ({ ...exampleStep, [field]: value });
const sessionFor = (context: AgentCacheContext, step: typeof exampleStep) =>
makeSession({ ...context, claimKey: () => ({ keyHash: OWN_KEY, context: exampleContext, step }) }, makeHost(['/']));

it('runs live when only another step that starts the same way was recorded', async () => {
const context = await rekeyedContext(recordedPayload(recordedProvenance(stepWith(`${long} first`), (text) => text)));
const session = sessionFor(context, stepWith(`${long} second`));
await expect(session.begin()).resolves.toBeUndefined();
expect(session.cacheInfo).toMatchObject({ mode: 'missed', reason: 'no-entry' });
});

it('fails with REPLAY_STALE when its own recording sits under another key', async () => {
const step = stepWith(`${long} first`);
const stored = recordedProvenance(step, (text) => text);
expect(stored[field]).toHaveLength(MAX_TRACE_DESCRIPTOR_CHARS);
const session = sessionFor(await rekeyedContext(recordedPayload(stored)), step);
await expect(session.begin()).rejects.toMatchObject({ code: 'REPLAY_STALE' });
});

it('runs live against an entry that cut it before entries kept an identity digest', async () => {
const step = stepWith(`${long} first`);
const { identityDigest: _digest, ...legacy } = recordedProvenance(step, (text) => text);
await expect(sessionFor(await rekeyedContext(recordedPayload(legacy)), step).begin()).resolves.toBeUndefined();
});

it('runs live when its whole name equals the cut name of another step, stored without an identity digest', async () => {
const { identityDigest: _digest, ...legacy } = recordedProvenance(stepWith(`${long} first`), (text) => text);
const step = stepWith(legacy[field]!);
await expect(sessionFor(await rekeyedContext(recordedPayload(legacy)), step).begin()).resolves.toBeUndefined();
});

it('fails with REPLAY_STALE when its whole name ends like a cut and its own recording sits under another key', async () => {
for (const length of [MAX_TRACE_DESCRIPTOR_CHARS - 1, MAX_TRACE_DESCRIPTOR_CHARS]) {
const step = stepWith(`${'x'.repeat(length - 1)}…`);
const stored = recordedProvenance(step, (text) => text);
expect(stored.identityDigest, String(length)).toMatch(/^[a-f0-9]{64}$/u);
const session = sessionFor(await rekeyedContext(recordedPayload(stored)), step);
await expect(session.begin(), String(length)).rejects.toMatchObject({ code: 'REPLAY_STALE' });
}
});

it(`fails with REPLAY_STALE at exactly ${MAX_TRACE_DESCRIPTOR_CHARS} characters, which an entry keeps whole`, async () => {
const step = stepWith('x'.repeat(MAX_TRACE_DESCRIPTOR_CHARS));
const stored = recordedProvenance(step, (text) => text);
expect(stored).toEqual(step);
await expect(sessionFor(await rekeyedContext(recordedPayload(stored)), step).begin()).rejects.toMatchObject({ code: 'REPLAY_STALE' });
});
});

it('runs live when the only recording is truncated or records no step', async () => {
const tapUpgrade = { name: 'tap', summary: 'tap button "Upgrade"', target: { role: 'button', name: 'Upgrade' } } as const;
const truncated = recordedPayload(exampleStep, { actions: Array.from({ length: 50 }, () => tapUpgrade), truncated: true });
Expand Down
13 changes: 12 additions & 1 deletion packages/e2e/tests/unit/text.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { runInNewContext } from 'node:vm';
import { describe, expect, it } from 'vitest';
import { bound, compareText, matchesText, normalizeRegexpFlags, normalizeText, toTextPattern } from '@e2e-dev/core/lib/internal/text';
import { bound, boundIsAmbiguous, compareText, matchesText, normalizeRegexpFlags, normalizeText, toTextPattern } from '@e2e-dev/core/lib/internal/text';

describe('normalizeText', () => {
it('trims and collapses unicode whitespace runs to one ASCII space', () => {
Expand Down Expand Up @@ -86,3 +86,14 @@ describe('bound', () => {
expect(bound(`ab😀def`, 5)).toBe('ab😀…');
});
});

describe('boundIsAmbiguous', () => {
it('holds for text bound cuts and for text that ends like one of its cuts, and for nothing else', () => {
expect(boundIsAmbiguous('abcdef', 5)).toBe(true);
expect(boundIsAmbiguous('abcd…', 5)).toBe(true);
expect(boundIsAmbiguous('abc…', 5)).toBe(true);
expect(boundIsAmbiguous('abcde', 5)).toBe(false);
expect(boundIsAmbiguous('ab…', 5)).toBe(false);
expect(boundIsAmbiguous('loading…', 300)).toBe(false);
});
});
Loading
Loading