Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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 @@ -393,6 +393,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 id, target name, or agent name is over 300 characters, when its recording under another key was made by an earlier `e2e` version |

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two problems in this row:

  • On this page, "test id" means the app's element test id (lines 162, 206, and 217). Here it means the identity of the test, so readers can confuse the two.
  • The row says "over 300 characters". But boundIsAmbiguous also gives a digest to a whole name of 299 or 300 characters that ends in …. An entry that an earlier version recorded for such a step also runs live.

Suggested text:

Suggested change
| | A step whose test id, target name, or agent name is over 300 characters, when its recording under another key was made by an earlier `e2e` version |
| | A step in a test with a very long title, or with a target or agent name over 300 characters (or of 299 or 300 characters ending in `…`), when its recording under another key was made by an earlier `e2e` version |

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note

🤖 Claude Opus 5.5 responding on behalf of Samanyu Das

Took your "a test with a very long title" wording in 0f8c4599, and left out the … parenthetical. On this page no input can reach that case:

  • Target and agent names must match TARGET_NAME_PATTERN (packages/core/src/config/targets.ts:40, reused for agents at config/resolve.ts:902), which is ASCII only. A target named 'a'.repeat(298) + '…' fails with INVALID_CONFIG.
  • A runner test id ends in a title that encodeTitle percent-encodes, so … is stored as %E2%80%A6.

Only a createAgent cacheKey (core:${cacheKey}) can end like a cut. The identityDigest JSDoc says so, and this page does not cover createAgent.

The row now also ends with "and no read-write run has replayed it since". A confirmed read-write replay writes the digest into the older entry, and after that strict fails it on a rekey like any other entry. The ja and zh tables get the same row (6d373413).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note

🤖 Claude Opus 5.5 responding on behalf of Samanyu Das

I changed the row again in 275d93aa, after a second check showed that "a very long title" undersells the case. Titles are percent-encoded into the id, and each Japanese character becomes 9 characters. A 39-character Japanese title in tests/cart.e2e.ts gives a 370-character id, so two such tests that differ only at the end hit the same collision.

The row now names the field a user can look up, which also avoids the element test id clash:

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

"Of this version" is there because a read-write replay by an older runner writes no digest. The ja and zh rows say the same.


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
12 changes: 7 additions & 5 deletions packages/core/src/cache/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,14 +141,16 @@ 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`).
* occurrence fields or the identity digest 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`).
*/
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
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]);
}
3 changes: 3 additions & 0 deletions packages/core/src/cache/trace-read.ts
Original file line number Diff line number Diff line change
Expand Up @@ -426,13 +426,16 @@ function readProvenance(document: unknown): TraceProvenance | 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 (identityDigest !== undefined && (typeof identityDigest !== 'string' || !SHA256_HEX.test(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
* never share the digest.
*/
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 reads like the cut an entry with no identity digest stored for another step', 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);
});
});
34 changes: 34 additions & 0 deletions packages/e2e/tests/unit/trace-cache-config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ import { chmod, mkdtemp, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { describe, expect, it } from 'vitest';
import { createAgentCacheContext, settleStagedTraces } from '@e2e-dev/core/lib/cache/context';
import { recordedProvenance } from '@e2e-dev/core/lib/cache/recorder';
import { FileCacheStore } from '@e2e-dev/core/lib/cache/store';
import { buildTraceEntry } from '@e2e-dev/core/lib/cache/trace';
import { readTraceEntry } from '@e2e-dev/core/lib/cache/trace-read';
import { SecretLedger } from '@e2e-dev/core/lib/internal/redact';
import { resolveConfig } from '../../src/config/resolve-run.ts';
import type { ActionTrace, CacheStore } from '@e2e-dev/core/lib/types';
import type { E2EConfig } from '../../src/run-types.ts';
Expand Down Expand Up @@ -358,6 +360,19 @@ describe('settleStagedTraces', () => {
expect(readTraceEntry(JSON.parse(store.entries.get(KEY_A)!))?.payload).toEqual({ ...recorded, recordedFor: STEP });
});

it('writes the identity digest into a confirmed kept entry that cut a long test id before entries kept one', async () => {
const store = memoryStore();
const long = { ...STEP, testId: `${STEP.testId}${'x'.repeat(400)}` };
const recordedFor = recordedProvenance(long, (text) => text);
const { identityDigest, ...legacy } = recordedFor;
expect(identityDigest).toMatch(/^[a-f0-9]{64}$/u);
store.entries.set(KEY_A, JSON.stringify(buildTraceEntry({ ...trace('replayed flow'), recordedFor: legacy })));
const context = contextWith(store);
context.staged.push({ kind: 'keep', keyHash: KEY_A, stepIndex: 1, recordedFor });
await settleStagedTraces(context, { lastVerifiedStepIndex: 2, implicatesUnconfirmed: true });
expect(readTraceEntry(JSON.parse(store.entries.get(KEY_A)!))?.payload.recordedFor).toEqual(recordedFor);
});

it('writes what was confirmed and leaves every unconfirmed entry as stored when the failure implicates nothing', async () => {
const KEY_C = 'c'.repeat(64);
const store = memoryStore();
Expand Down Expand Up @@ -399,3 +414,22 @@ describe('settleStagedTraces', () => {
expect(other).not.toBe(first);
});
});

describe('recorded provenance', () => {
it('takes the identity digest over the redacted names, so it never depends on a secret value', () => {
const long = `${STEP.testId}${'x'.repeat(400)}`;
const digestWith = (value: string) => {
const secrets = new SecretLedger();
secrets.register('password', value);
return recordedProvenance({ ...STEP, testId: `${long} as ${value}` }, secrets.redact).identityDigest;
};
expect(digestWith('hunter2')).toMatch(/^[a-f0-9]{64}$/u);
expect(digestWith('hunter2')).toBe(digestWith('swordfish'));
});

it.each([['not-a-digest'], [['a'.repeat(64)]], [42]])('refuses an entry whose identity digest is %j', (identityDigest) => {
const entry = JSON.parse(JSON.stringify(buildTraceEntry({ ...trace('recorded flow'), recordedFor: STEP })));
entry.payload.recordedFor.identityDigest = identityDigest;
expect(readTraceEntry(entry)).toBeUndefined();
});
});
Loading