mirror of
https://github.com/openai/codex-security.git
synced 2026-12-04 01:55:06 +08:00
fix(deep-scan): reconcile recovered usage and native build fixtures
This commit is contained in:
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import {
|
||||
copyFileSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
rmSync,
|
||||
@@ -20,10 +21,15 @@ const testDirectory = join(output, "policy-proof");
|
||||
const helper = join(testDirectory, "helpers.cjs");
|
||||
if (process.argv[2] === "build") {
|
||||
const mcpApp = join(root, "../mcp-app");
|
||||
const mcpModules = join(mcpApp, "node_modules");
|
||||
const esbuild = "esbuild/bin/esbuild";
|
||||
const modules = existsSync(join(mcpModules, esbuild))
|
||||
? mcpModules
|
||||
: join(root, "../../../sdk/typescript/node_modules");
|
||||
execFileSync(
|
||||
process.execPath,
|
||||
[
|
||||
join(mcpApp, "node_modules/esbuild/bin/esbuild"),
|
||||
join(modules, esbuild),
|
||||
join(mcpApp, "helpers-main.ts"),
|
||||
"--bundle",
|
||||
"--platform=node",
|
||||
@@ -32,7 +38,7 @@ if (process.argv[2] === "build") {
|
||||
"--define:import.meta.url=__filename",
|
||||
`--outfile=${helper}`,
|
||||
],
|
||||
{ stdio: "inherit" },
|
||||
{ stdio: "inherit", env: { ...process.env, NODE_PATH: modules } },
|
||||
);
|
||||
const nativeDirectory = join(testDirectory, "native", nativeTarget);
|
||||
mkdirSync(nativeDirectory, { recursive: true });
|
||||
|
||||
@@ -3663,13 +3663,13 @@ export class ScanCostTracker {
|
||||
this.#options.onCost === undefined
|
||||
)
|
||||
return;
|
||||
const receiptCost =
|
||||
cost ??
|
||||
estimateScanCostLowerBound(
|
||||
this.#options.model,
|
||||
usage,
|
||||
this.#options.pricingContext,
|
||||
);
|
||||
const receiptCost = cost
|
||||
? { ...cost, coverage: "partial" as const }
|
||||
: estimateScanCostLowerBound(
|
||||
this.#options.model,
|
||||
usage,
|
||||
this.#options.pricingContext,
|
||||
);
|
||||
const liveCost = estimateScanCostLowerBound(
|
||||
this.#options.model,
|
||||
liveUsage,
|
||||
|
||||
@@ -84,7 +84,7 @@ import {
|
||||
runReadOnlyCodex,
|
||||
matchScanFindingsInternal,
|
||||
} from "../src/scan-comparison.js";
|
||||
import { normalizeTarget } from "../src/targets.js";
|
||||
import { abortable, normalizeTarget } from "../src/targets.js";
|
||||
import {
|
||||
copyCompletedScan,
|
||||
copyCredentialTestPlugin,
|
||||
@@ -3591,6 +3591,7 @@ if __name__ == "__main__":
|
||||
async (consolidating) => {
|
||||
const { repository, codexHome, scanDir } = await scanDirectories();
|
||||
const updates: DeepScanProgress[] = [];
|
||||
const progressReads: Array<readonly string[]> = [];
|
||||
const observerErrors: unknown[] = [];
|
||||
const warnings: string[] = [];
|
||||
const environment = { CODEX_CLI_PATH: process.execPath };
|
||||
@@ -3604,8 +3605,8 @@ if __name__ == "__main__":
|
||||
args: readonly string[],
|
||||
input?: string,
|
||||
): Promise<JsonObject> => {
|
||||
if (args[0] === "get-scan") {
|
||||
expect(args).toContain("--progress-only");
|
||||
if (args[0] === "get-scan" && args.includes("--progress-only")) {
|
||||
progressReads.push(args);
|
||||
return {
|
||||
scan: {
|
||||
progress: {
|
||||
@@ -3640,6 +3641,12 @@ if __name__ == "__main__":
|
||||
}),
|
||||
).rejects.toThrow("deep progress captured");
|
||||
await Bun.sleep(0);
|
||||
expect(progressReads).toContainEqual([
|
||||
"get-scan",
|
||||
"--scan-id",
|
||||
"scan_example_001",
|
||||
"--progress-only",
|
||||
]);
|
||||
if (consolidating === true) {
|
||||
expect(updates).toEqual([
|
||||
{ completed: 3, active: 2, maximum: 40, consolidating: true },
|
||||
@@ -15373,6 +15380,31 @@ if __name__ == "__main__":
|
||||
);
|
||||
await writeFile(path, lines.join("\n"));
|
||||
};
|
||||
// The SDK publishes indexed usage while independently checking native floors.
|
||||
// Mirror each emitted rollout snapshot in the synthetic workbench.
|
||||
const initialInput = 800;
|
||||
const unpricedWorker = measuredScanUsage(100, 0, 10);
|
||||
const mixedUsage = {
|
||||
...measuredScanUsage(
|
||||
knownUsage.input_tokens + 100,
|
||||
knownUsage.cached_input_tokens,
|
||||
knownUsage.output_tokens + 10,
|
||||
),
|
||||
threadCount: 2,
|
||||
byRole: { workers: { threadCount: 1 } },
|
||||
modelUsage: [
|
||||
{
|
||||
model: "gpt-5.6-sol",
|
||||
...measuredScanUsage(
|
||||
knownUsage.input_tokens,
|
||||
knownUsage.cached_input_tokens,
|
||||
knownUsage.output_tokens,
|
||||
),
|
||||
},
|
||||
{ model: "synthetic-unpriced-model", ...unpricedWorker },
|
||||
],
|
||||
};
|
||||
let indexedUsage = measuredScanUsage(initialInput, 0, 0);
|
||||
const client = new TestClient(
|
||||
{},
|
||||
{
|
||||
@@ -15383,6 +15415,7 @@ if __name__ == "__main__":
|
||||
repositoryRevision: async () => "deadbeef",
|
||||
runWorkbench: async (_options, args, input) => {
|
||||
commands.push(args);
|
||||
if (args[0] === "read-scan-usage") return indexedUsage;
|
||||
if (args[0] === "get-scan")
|
||||
return { scan: { id: "scan_example_001" } };
|
||||
if (args[0] === "complete-budget-exhausted-scan")
|
||||
@@ -15400,16 +15433,17 @@ if __name__ == "__main__":
|
||||
async function* events(): AsyncGenerator<ThreadEvent> {
|
||||
if (raised) {
|
||||
await writePricedUsage({
|
||||
input_tokens: 800,
|
||||
input_tokens: initialInput,
|
||||
output_tokens: 0,
|
||||
});
|
||||
} else {
|
||||
await writePricedUsage(knownUsage);
|
||||
await writeUnpricedUsage();
|
||||
indexedUsage = mixedUsage;
|
||||
}
|
||||
yield { type: "thread.started", thread_id: "scan-thread" };
|
||||
if (raised) {
|
||||
await increased;
|
||||
await abortable(() => increased, options.signal);
|
||||
await writeUnpricedUsage();
|
||||
const path = join(
|
||||
codexHome,
|
||||
@@ -15429,6 +15463,7 @@ if __name__ == "__main__":
|
||||
},
|
||||
}) + "\n",
|
||||
);
|
||||
indexedUsage = mixedUsage;
|
||||
}
|
||||
await new Promise<void>((resolve) => {
|
||||
if (options.signal.aborted) resolve();
|
||||
|
||||
@@ -222,7 +222,10 @@ async function interruptedScan(
|
||||
{
|
||||
type: "turn_context",
|
||||
timestamp: new Date().toISOString(),
|
||||
payload: { turn_id: "synthetic-scan-turn", model: "gpt-5.6-sol" },
|
||||
payload: {
|
||||
turn_id: "synthetic-scan-turn",
|
||||
model: recipe.config["model"],
|
||||
},
|
||||
},
|
||||
]
|
||||
.map((event) => JSON.stringify(event))
|
||||
@@ -862,6 +865,7 @@ test.each(["completed", "failed"] as const)(
|
||||
f.sessionPath,
|
||||
JSON.stringify({
|
||||
type: "event_msg",
|
||||
timestamp: new Date().toISOString(),
|
||||
payload: {
|
||||
type: "token_count",
|
||||
info: {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { afterEach, expect, test } from "bun:test";
|
||||
import { build } from "esbuild";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { copyFile, mkdir, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { cp, writeFile } from "node:fs/promises";
|
||||
import { basename, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { pythonExecutable } from "./support/python.js";
|
||||
import { createApiTestFixtures } from "./support/temporary-directories.js";
|
||||
@@ -29,8 +29,9 @@ const laterFrame = Buffer.from(
|
||||
const workerFrames = {
|
||||
first:
|
||||
"KLUv/WBuADUGADJMJR5gZ9sGBqGhvdpM+qNbLXaX7jcEObew2na8jABwIXjFe+8hB5PCFltObT9Iu9VeDZFSogMq1Q8e6NyOYUuVZJcO2dtbYOvnzdyqxNSwrfCSmimBHk3x3pUW6NFVNbf8cwFEZIAQAwhoENAAOPA4OrNksy6rf97U0BZhNLdVOHqy3qAnuYdEMj/P1iWxXczKR1cm0W8CEQB4BKBhOOxn96XiBlC+dhIAT6kAapxW/0zxeiGCZlZi8irGIav12lWPyMtFAQ==",
|
||||
// A legacy child proves its task began after its session was created.
|
||||
child:
|
||||
"KLUv/W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 @@ const workerFrames = {
|
||||
async function fixture() {
|
||||
const root = await temporaryDirectory();
|
||||
const plugin = join(root, "plugin");
|
||||
const paths = [
|
||||
"scripts/workbench_scan_usage.py",
|
||||
"scripts/windows_scan_local_files.py",
|
||||
"scripts/read_codex_session.mjs",
|
||||
"scripts/workbench/__init__.py",
|
||||
"scripts/workbench/storage.py",
|
||||
];
|
||||
for (const path of paths) {
|
||||
await mkdir(dirname(join(plugin, path)), { recursive: true });
|
||||
await copyFile(join(sourcePlugin, path), join(plugin, path));
|
||||
}
|
||||
await cp(join(sourcePlugin, "scripts"), join(plugin, "scripts"), {
|
||||
recursive: true,
|
||||
filter: (source) => basename(source) !== "__pycache__",
|
||||
});
|
||||
await cp(join(sourcePlugin, "schemas"), join(plugin, "schemas"), {
|
||||
recursive: true,
|
||||
});
|
||||
await build({
|
||||
entryPoints: [join(sourcePlugin, "mcp-app/src/session-decompression.ts")],
|
||||
outfile: join(plugin, "mcp/session-decompression.mjs"),
|
||||
@@ -94,15 +91,16 @@ with sqlite3.connect(":memory:") as db:
|
||||
db.row_factory = sqlite3.Row
|
||||
db.execute("CREATE TABLE workspaces (id TEXT, thread_id TEXT)")
|
||||
db.execute("INSERT INTO workspaces VALUES ('workspace', ?)", (options["owner"],))
|
||||
db.execute("CREATE TABLE deep_scan_attempt_sessions (scan_id TEXT, sdk_thread_id TEXT)")
|
||||
db.execute("CREATE TABLE deep_scan_worker_threads (scan_id TEXT, sdk_thread_id TEXT)")
|
||||
db.execute("CREATE TABLE deep_scan_runs (scan_id TEXT, worker_usage_gap INTEGER)")
|
||||
db.execute("CREATE TABLE deep_scan_runs (scan_id TEXT, worker_usage_gap INTEGER, workflow_version TEXT)")
|
||||
db.execute("CREATE TABLE deep_scan_workers (scan_id TEXT, kind TEXT, artifact_dir TEXT, started_at TEXT, sdk_thread_id TEXT, attempt INTEGER)")
|
||||
mode = "deep" if options.get("workerKind") else "standard"
|
||||
if mode == "deep":
|
||||
db.execute("INSERT INTO deep_scan_runs VALUES ('scan', 0)")
|
||||
db.execute("INSERT INTO deep_scan_runs VALUES ('scan', 0, 'deep-security-scan/v1')")
|
||||
db.execute("INSERT INTO deep_scan_workers VALUES ('scan', ?, ?, '2026-01-01T00:00:01Z', 'current-worker', 2)", (options["workerKind"], str(root / "artifacts" / "worker")))
|
||||
db.execute("INSERT INTO deep_scan_worker_threads VALUES ('scan', 'current-worker')")
|
||||
scan = db.execute("SELECT 'scan' AS id, 'workspace' AS workspace_id, ? AS mode, ? AS scan_dir, '2026-01-01T00:00:00.500123Z' AS started_at, '2026-01-01T00:00:05Z' AS completed_at, NULL AS deep_scan_owner_thread_id", (mode, str(root))).fetchone()
|
||||
scan = db.execute("SELECT 'scan' AS id, 'workspace' AS workspace_id, ? AS mode, ? AS scan_dir, '2026-01-01T00:00:00.500123Z' AS started_at, '2026-01-01T00:00:05Z' AS completed_at, NULL AS deep_scan_owner_thread_id, NULL AS recipe_json, NULL AS continuation_thread_id", (mode, str(root))).fetchone()
|
||||
print(json.dumps(collect_scan_usage(db, scan)))
|
||||
`;
|
||||
return JSON.parse(
|
||||
|
||||
Reference in New Issue
Block a user