mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-31 14:16:39 +01:00
## Thinking Path > - Paperclip manages work performed by AI agents. > - Native execution crosses the plugin worker, Runner, sidecar, and durable event boundaries. > - Existing outer spans leave repeated preparation and admission work unattributed. > - Optimizations need a common baseline with accurate ownership and event meanings. > - This change extends the existing opt-in tracing contract with bounded timing receipts. > - It preserves execution policy and keeps provider internals opaque where the API provides no timing proof. ## Linked Issues or Issue Description **What existing behavior does this improve?** Attribution of native task preparation, retained/cold Runner handoff, and completion-to-text work. **Current behavior** Worker spans use a flat provider contract. Workspace calls lack a consistent dispatch envelope. Submitted-to-started timing is named as a provider queue even though it includes other work. The transport does not expose a shared breakdown of its waits. **Proposed improvement** Add invocation-scoped nesting, bounded numeric remote receipts, current-run transport timing, durable receipt intervals, and distinct completion/text milestones. Reuse the existing exporter. No latency optimization is included. Related public work: #17842 consolidates existing startup tracing tests; it does not add this runtime coverage. ## What Changed - Extend the optional SDK tracer with nested async scopes and completed timing receipts. Keep the host responsible for parent identity, capability checks, attributes, clocks, depth, and count limits. - Add dispatch and bounded host-read timings for environment and workspace providers. - Resolve transport parents on each call so retained sessions do not retain an earlier run's trace. - Split cold/resume/attach/prepare/registration/command/started-event waits. Add opt-in numeric ACPX Runner/sidecar status and prompt-start receipts. - Distinguish first completion request, validated tool receipt, final result commit, first nonempty text, and event persistence. Rename the submitted-to-started interval to match its meaning. - Link completed earlier remote lifecycles to their host-owned observer rather than placing them under a later polling request. Preserve sampling, timestamp limits and budgets. - Document the versioned coverage map, causal clock limits, and baseline acceptance requirements. ## Verification - Current head: GitHub CI is fully green. Standard Greptile and Apex are both 5/5, with no unresolved review threads. Full-suite validation was performed in CI; follow-up local validation was limited to affected packages and tests. - Review follow-up: early rejection, missing provider capability and startup-parent regressions were reproduced and fixed. The affected worker/SDK/timing set passes 128 tests; 28 timing/context tests, SDK typecheck and direct server TypeScript checking pass. The server typecheck wrapper reached an unrelated Runner rebuild and stopped because Cargo was absent from PATH; full Runner/image validation remains in CI. - CI failure accounting: the earlier Turbo cache/force conflict and Linux OpenCode shell assertion were reproduced and diagnosed. A direct proc probe ruled out permissions; a portable shell comparison identified Bash skipping BASH_ENV with stripped SHLVL and socket stdin. Upstream #18230 now supplies the CI and ignored-stdin fixture fixes; this PR adopts them without duplicate CI changes. The strict Linux OOM assertion passed before this source-equivalent merge. - Retry follow-up: the three insertion/replay/failure timing cases and server typecheck pass. The existing database regression now asserts a single marker across identical result replay; the current-head CI integration gate passes. - Upstream CI alignment: all three real-Turbo 2.11.10 integration cases pass. The repository policy gate rejected committing a generated lockfile; the final PR contains no lockfile edit and uses the maintained inline stale-lockfile recovery. - Linked-lifecycle follow-up: 44 focused host/export tests pass (three optional SDK-dependent cases skip); SDK and server typechecks pass. The API contract test verifies an explicit root context, host-owned observer link and unsampled suppression. - SDK typecheck and focused worker/invocation tests: 30 passed, including clock changes, bounded legacy IPC, and manual-span creation-scope parentage. - Focused reviewed host/native/transaction-boundary checks: 44 passed. The 86-test worker-manager suite passes after updating its exact assertions for the host-owned timing budget found by CI. Earlier preparation/first-text checks also passed. - Affected server and Runner TypeScript checks pass after building local workspace declarations. - Merge follow-up: the profile/candidate startup subset passes 94 tests, the four Grok source-identity checks pass, and Runner TypeScript checking passes. A subsequent execution-factory merge passes 21 focused timing/trace tests and server TypeScript checking. - Pinned Rust build and the ACPX Rust subset pass. The hostile receipt projection test passes. Source profile compatibility checks: 127 passed, one existing skip. Grok identity checks: four passed. - Broad transport/ACPX suite: 410 passed after building all fake provider binaries. Earlier attempts failed on missing Runner/fake-provider outputs; building the required fixtures resolved those failures. - The first CI run correctly rejected stale source attestations. After integrating current master, Grok advances 13→14 and Copilot 84→85; master’s historical fixtures and Pi 35 stay byte-identical. Provider dependencies, models and permission defaults are unchanged. Identity generation/checks now pass. - The added real-Postgres result lock regression could not initialize its local embedded cluster. The insertion/replay/failure unit regressions pass. The current-head CI integration gate passes. - Comprehensive repository checks and image builds are delegated to CI, as requested for this instrumentation pass. No deployment, model run, collector-ingestion proof, or latency improvement is claimed. ## Risks The new SDK methods are optional. Legacy span calls and endpoint-off behavior remain supported. The host accepts only closed timing names and bounded attributes. Remote durations are anchored at local receipt; transport/scheduling uncertainty remains explicit. Trace trees have count/depth limits. The first rollout must inspect actual collector exports before treating the baseline as accepted. Fresh live qualification for the new source identities remains a rollout requirement. Revert these commits to remove the new measurements; no schema migration is required. ## Model Used OpenAI Codex, GPT-6 family, with reasoning and local code/tool execution. The exact runtime model ID and context-window size are not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have described the issue in-PR following the enhancement template - [x] I have not referenced internal/instance-local Paperclip issues or links - [x] My branch name describes the change and contains no internal issue details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Standard Greptile and Apex are both 5/5, with no unresolved findings - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
165 lines
8.9 KiB
TypeScript
165 lines
8.9 KiB
TypeScript
import { getActiveStepContext, runWithRuntimeParent } from "@paperclipai/adapter-utils/acpx-engine/startup-timing";
|
|
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
|
import { createRunPreparationTiming, measureRunPhase, recordRepositoryObjectCacheDetail, withRunExecutionTiming, withRunWorkspaceFinalizationTiming } from "./execution-preparation-timing.js";
|
|
import { ROOT_CONTEXT, trace, SpanStatusCode, type Context } from "@opentelemetry/api";
|
|
import { createHash } from "node:crypto";
|
|
|
|
const handles = vi.hoisted(() => ({ getTracer: vi.fn(), startActiveSpan: vi.fn() }));
|
|
vi.mock("@opentelemetry/api", async importOriginal => {
|
|
const api = await importOriginal<typeof import("@opentelemetry/api")>();
|
|
return { ...api, trace: { ...api.trace, getTracer: handles.getTracer, getActiveSpan: () => undefined } };
|
|
});
|
|
beforeEach(() => {
|
|
vi.stubEnv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://collector.test");
|
|
handles.getTracer.mockReturnValue({ startActiveSpan: handles.startActiveSpan });
|
|
});
|
|
afterEach(() => vi.unstubAllEnvs());
|
|
|
|
it.each(["lookup", "start", "after_callback", "missing_callback", "rejected", "end", "status"])("runs work once and preserves its result or error when tracing fails at %s", async failure => {
|
|
const broken = () => { throw new Error("tracing failed"); };
|
|
handles.getTracer.mockImplementation(failure === "lookup" ? broken : () => ({ startActiveSpan: handles.startActiveSpan }));
|
|
handles.startActiveSpan.mockImplementation((_name, _options, _context, callback) => {
|
|
if (failure === "start") throw new Error("tracer failed before callback");
|
|
if (failure === "missing_callback") return undefined;
|
|
if (failure === "rejected") return Promise.reject(new Error("tracer rejected"));
|
|
const result = callback({ end: failure === "end" ? broken : vi.fn(), setStatus: failure === "status" ? broken : vi.fn() });
|
|
if (failure === "after_callback") throw new Error("tracer failed after callback");
|
|
return result;
|
|
});
|
|
const timing = createRunPreparationTiming("private-run", "native.controller");
|
|
const result = {};
|
|
const work = vi.fn(async () => result);
|
|
await expect(timing("backend_setup", work)).resolves.toBe(result);
|
|
expect(work).toHaveBeenCalledOnce();
|
|
const error = new Error("original private failure");
|
|
const failedWork = vi.fn(async () => { throw error; });
|
|
await expect(timing("assigned_mcp", failedWork)).rejects.toBe(error);
|
|
expect(failedWork).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
it.each([undefined, "", " "])("does not consult tracing for endpoint %s", async endpoint => {
|
|
vi.stubEnv("OTEL_EXPORTER_OTLP_ENDPOINT", endpoint);
|
|
handles.getTracer.mockClear();
|
|
const warn = vi.spyOn(console, "warn");
|
|
const error = vi.spyOn(console, "error");
|
|
try {
|
|
await expect(createRunPreparationTiming("run", "native.controller")("backend_setup", () => 42)).resolves.toBe(42);
|
|
await expect(withRunWorkspaceFinalizationTiming("run", () => 42)).resolves.toBe(42);
|
|
for (const phase of ["execution.usage_startup", "execution.mcp_handoff", "execution.dispatch_admission", "execution.budget_reservation",
|
|
"skills.inventory", "skills.inventory.wait", "skills.cache.acquire", "skills.version.materialize", "skills.consume"] as const) {
|
|
const result = {};
|
|
const work = vi.fn(() => {
|
|
recordRepositoryObjectCacheDetail({ outcome: "hit", referenceSupplied: true });
|
|
return result;
|
|
});
|
|
await expect(withRunExecutionTiming("run", () => measureRunPhase(phase, work))).resolves.toBe(result);
|
|
expect(work).toHaveBeenCalledOnce();
|
|
const original = new Error("original startup failure");
|
|
const failed = vi.fn(() => { throw original; });
|
|
await expect(withRunExecutionTiming("run", () => measureRunPhase(phase, failed))).rejects.toBe(original);
|
|
expect(failed).toHaveBeenCalledOnce();
|
|
}
|
|
expect(handles.getTracer).not.toHaveBeenCalled();
|
|
expect(warn).not.toHaveBeenCalled();
|
|
expect(error).not.toHaveBeenCalled();
|
|
} finally {
|
|
warn.mockRestore();
|
|
error.mockRestore();
|
|
}
|
|
});
|
|
|
|
it("parents concurrent deferred copyback phases to their own finalization roots and preserves failure", async () => {
|
|
const spans: Array<{ name: string; attributes: Record<string, unknown>; context: Context;
|
|
span: { end: ReturnType<typeof vi.fn>; setStatus: ReturnType<typeof vi.fn> } }> = [];
|
|
handles.startActiveSpan.mockImplementation((name, options, context, callback) => {
|
|
const span = { end: vi.fn(), setStatus: vi.fn() };
|
|
spans.push({ name, attributes: options.attributes, context, span });
|
|
return callback(span);
|
|
});
|
|
await Promise.all(["first", "second"].map(runId => withRunWorkspaceFinalizationTiming(runId, async () => {
|
|
await Promise.resolve();
|
|
await measureRunPhase("workspace_sync.restore", async () => {});
|
|
})));
|
|
for (const runId of ["first", "second"]) {
|
|
const hash = createHash("sha256").update(runId).digest("hex").slice(0, 12);
|
|
const owned = spans.filter(span => span.attributes["paperclip.task.run.run_id"] === hash);
|
|
expect(owned).toHaveLength(2);
|
|
const root = owned.find(span => span.name === "task.workspace_finalization")!;
|
|
const child = owned.find(span => span.name === "workspace_sync.restore")!;
|
|
expect(root.context).toBe(ROOT_CONTEXT);
|
|
expect(trace.getSpan(child.context)).toBe(root.span);
|
|
expect(root.span.end).toHaveBeenCalledOnce();
|
|
expect(Object.keys(root.attributes)).toEqual(["paperclip.task.run.run_id"]);
|
|
}
|
|
const original = new Error("private finalization failure");
|
|
const work = vi.fn(() => { throw original; });
|
|
await expect(withRunWorkspaceFinalizationTiming("failed", work)).rejects.toBe(original);
|
|
expect(work).toHaveBeenCalledOnce();
|
|
expect(spans.at(-1)!.span.setStatus).toHaveBeenCalledWith({ code: SpanStatusCode.ERROR });
|
|
expect(spans.at(-1)!.span.end).toHaveBeenCalledOnce();
|
|
expect(JSON.stringify(spans)).not.toContain(original.message);
|
|
});
|
|
|
|
it("keeps cache outcomes and clone references on their owning concurrent phases", async () => {
|
|
const spans: Array<{ name: string; attributes: Record<string, unknown> }> = [];
|
|
handles.startActiveSpan.mockImplementation((name, options, _context, callback) => {
|
|
const record = { name, attributes: { ...options.attributes } };
|
|
spans.push(record);
|
|
return callback({
|
|
end: vi.fn(), setStatus: vi.fn(),
|
|
setAttribute: (key: string, value: unknown) => { record.attributes[key] = value; },
|
|
});
|
|
});
|
|
await Promise.all([
|
|
withRunExecutionTiming("first", () => measureRunPhase("workspace.checkout.cache_lookup", async () => {
|
|
await Promise.resolve();
|
|
recordRepositoryObjectCacheDetail({ outcome: "hit" });
|
|
})),
|
|
withRunExecutionTiming("second", () => measureRunPhase("workspace.checkout.git_clone", async () => {
|
|
await Promise.resolve();
|
|
recordRepositoryObjectCacheDetail({ referenceSupplied: false });
|
|
})),
|
|
]);
|
|
expect(spans.find(span => span.name === "workspace.checkout.cache_lookup")?.attributes).toMatchObject({
|
|
"paperclip.execution.repositoryCache.outcome": "hit",
|
|
});
|
|
expect(spans.find(span => span.name === "workspace.checkout.git_clone")?.attributes).toMatchObject({
|
|
"paperclip.execution.repositoryCache.reference_supplied": false,
|
|
});
|
|
expect(spans.filter(span => span.name === "task.execution_attempt").every(span =>
|
|
Object.keys(span.attributes).every(key => key === "paperclip.task.run.run_id"))).toBe(true);
|
|
});
|
|
|
|
it("does not let cache attribute failures replace the operation result", async () => {
|
|
handles.startActiveSpan.mockImplementation((_name, _options, _context, callback) => callback({
|
|
end: vi.fn(), setStatus: vi.fn(),
|
|
setAttribute: () => { throw new Error("tracer failed"); },
|
|
}));
|
|
const work = vi.fn(() => {
|
|
recordRepositoryObjectCacheDetail({ outcome: "published", referenceSupplied: true });
|
|
return 42;
|
|
});
|
|
await expect(withRunExecutionTiming("run", () => measureRunPhase("workspace.checkout.cache_publish", work))).resolves.toBe(42);
|
|
expect(work).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
it("keeps plugin dispatch beneath its active startup step and gives the worker the dispatch parent", async () => {
|
|
const parents = new Map<string, Context>();
|
|
const spans = new Map<string, { end: ReturnType<typeof vi.fn>; setStatus: ReturnType<typeof vi.fn> }>();
|
|
handles.startActiveSpan.mockImplementation((name, _options, parent, callback) => {
|
|
parents.set(name, parent);
|
|
const span = { end: vi.fn(), setStatus: vi.fn() };
|
|
spans.set(name, span);
|
|
return callback(span);
|
|
});
|
|
const step = trace.wrapSpanContext({ traceId: "1".repeat(32), spanId: "2".repeat(16), traceFlags: 1 });
|
|
const stepContext = trace.setSpan(ROOT_CONTEXT, step);
|
|
await withRunExecutionTiming("startup", () => runWithRuntimeParent(stepContext, async () => {
|
|
await measureRunPhase("execution.plugin_dispatch", () => {
|
|
expect(trace.getSpan(getActiveStepContext()!.parentContext as Context)).toBe(spans.get("execution.plugin_dispatch"));
|
|
});
|
|
expect(getActiveStepContext()!.parentContext).toBe(stepContext);
|
|
}));
|
|
expect(parents.get("execution.plugin_dispatch")).toBe(stepContext);
|
|
});
|