OpenViking icon indicating copy to clipboard operation
OpenViking copied to clipboard

[Bug]: Codex PreCompact discards the resolved session ID

Open ktz03 opened this issue 1 month ago • 0 comments

Issue Origin

Observed or reproduced in a real environment

Bug Description

The Codex PreCompact hook resolves a missing or empty session_id to the shared literal unknown, then performs transcript catch-up, commit, state persistence and end-marker cleanup for that ID. An unidentified hook event can therefore append and commit against an existing cx-unknown session rather than leaving state untouched.

The shared runHookStage already resolves stage.sessionId using session_id ?? sessionId, but pre-compact-capture.mjs discards that value and reads stage.input.session_id || "unknown" again. The same mismatch sends a camel-case compatibility payload to cx-unknown even though the stage resolved its named session. This compatibility input is accepted by the shared stage; I have not observed a native Codex UI sending it.

Steps to Reproduce

  1. Check out main d9352f2a8bac78cbf4ed08b26543d22adcdd4c93.
  2. Run the Node example below from the repository root. It uses the actual hook subprocess and transcript parser with temporary state files and a local HTTP fixture.
  3. The input includes a readable transcript but omits its session ID. Observe the requests, output and persisted state.

Expected Behavior

An unidentified PreCompact event should emit its existing no-op envelope without HTTP writes, state changes or end-marker removal. A named event should use the ID resolved by the shared stage. The existing nonempty snake-case ID behavior and the shared nullish field precedence should remain unchanged.

Actual Behavior

The hook exits successfully, calls /api/v1/sessions/cx-unknown/messages/batch and /api/v1/sessions/cx-unknown/commit, reports that cx-unknown was committed, releases that state's ovSessionId and removes its end marker. A separately seeded named session is left untouched.

The same actual-hook matrix covered ten scenarios: four normal controls passed and six identity cases failed. Missing/null/empty IDs and an empty snake-case ID with a camel-case field all used unknown; camel-only and null-snake-plus-camel also used unknown. Valid snake-case IDs, snake-case precedence, the disabled gate and an unreadable-transcript control retained their existing behavior. These are controlled input scenarios, not reports of six independent production failures.

Minimal Reproducible Example

import { spawn } from "node:child_process";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import http from "node:http";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";

const hook = resolve("examples/codex-memory-plugin/scripts/pre-compact-capture.mjs");
const dir = await mkdtemp(join(tmpdir(), "ov-precompact-id-"));
const transcript = join(dir, "rollout.jsonl");
const stamp = Date.now() - 10000;
const requests = [];
const server = http.createServer(async (req, res) => {
  for await (const chunk of req) {} // Drain the real request body.
  requests.push(req.url);
  res.setHeader("Content-Type", "application/json");
  res.end(JSON.stringify({ status: "ok", result: {
    ok: true, archived: true, task_id: "fixture", trace_id: "fixture"
  } }));
});
try {
  await writeFile(join(dir, "unknown.json"), JSON.stringify({
    codexSessionId: "unknown", ovSessionId: "cx-unknown",
    capturedTurnCount: 0, captureFormatVersion: 2, peerPinVersion: 3,
    workspacePeerId: "fixture-peer", createdAt: stamp, lastUpdatedAt: stamp
  }));
  await writeFile(join(dir, `unknown.ended.${stamp}`), String(stamp));
  await writeFile(transcript, ["user", "assistant"].map((role) =>
    JSON.stringify({ payload: { message: { role, content: `fixture ${role} turn` } } })
  ).join("\n"));
  await new Promise((done) => server.listen(0, "127.0.0.1", done));
  const env = { ...process.env };
  for (const key of Object.keys(env)) if (key.startsWith("OPENVIKING_") || key === "OV_DEBUG_LOG") delete env[key];
  Object.assign(env, {
    OPENVIKING_URL: `http://127.0.0.1:${server.address().port}`,
    OPENVIKING_CREDENTIAL_SOURCE: "env", OPENVIKING_CODEX_STATE_DIR: dir,
    OPENVIKING_CONFIG_FILE: join(dir, "absent-ov.conf"),
    OPENVIKING_CLI_CONFIG_FILE: join(dir, "absent-cli.conf"),
    OPENVIKING_HOME: join(dir, "home"), OPENVIKING_PENDING_DIR: join(dir, "pending"),
    OPENVIKING_PEER_ID: "fixture-peer", OPENVIKING_MEMORY_ENABLED: "1",
    OPENVIKING_AUTO_COMMIT_ON_COMPACT: "1", OPENVIKING_AUTO_CAPTURE: "1",
    OPENVIKING_CAPTURE_ASSISTANT_TURNS: "1", OPENVIKING_CODEX_LOCK_WAIT_MS: "0"
  });
  const child = spawn(process.execPath, [hook], { cwd: dir, env, stdio: ["pipe", "pipe", "pipe"] });
  let stdout = "", stderr = "";
  child.stdout.on("data", (chunk) => { stdout += chunk; });
  child.stderr.on("data", (chunk) => { stderr += chunk; });
  const finished = new Promise((done, reject) => { child.on("error", reject); child.on("close", done); });
  child.stdin.end(JSON.stringify({ transcript_path: transcript, cwd: dir, trigger: "manual" }));
  console.log({ exitCode: await finished, requests, stdout, stderr });
  console.log(JSON.parse(await readFile(join(dir, "unknown.json"), "utf8")));
} finally {
  await new Promise((done) => server.close(done));
  await rm(dir, { recursive: true, force: true });
}

Error Logs

/health
/api/v1/sessions/cx-unknown/messages/batch
/api/v1/sessions/cx-unknown/commit
{"systemMessage":"OpenViking session cx-unknown is committed (trace_id=fixture)"}

OpenViking Version

main d9352f2a8bac78cbf4ed08b26543d22adcdd4c93; Codex memory plugin 0.10.10

Python Version

Not used by this reproduction; Node.js 24.21.0

Operating System

Windows

Model Backend

Other — local HTTP fixture, no model invocation

Additional Context

Proposed narrow correction: consume stage.sessionId and skip before marker cleanup/locking when it is absent or empty. Keep the shared resolver, nonempty ID behavior, lock ownership, append/commit retry policy and persistence schema unchanged. This is an identity/lifecycle boundary report before implementation, following the contributing guide. Integration is the owning area.

The actual subprocess/HTTP/file behavior was reproduced on Windows. No live Codex UI, deployed OpenViking service, online memory extraction, performance or cross-platform result is claimed.

ktz03 avatar Oct 06 '26 00:10 ktz03