From edd202c42d3628924572fa9adc714f01f3eb1185 Mon Sep 17 00:00:00 2001 From: garrytan Date: Sat, 31 Oct 2026 18:46:52 +0000 Subject: [PATCH] fix(plan-tune): lock developer-profile writes and give derive a unique temp file (#3437) Concurrent background --derive runs shared developer-profile.json.tmp and rewrote the whole profile unlocked, so renames failed with ENOENT and a concurrent --log-session was dropped. Every read-modify-write now holds developer-profile.json.lock and writes a mktemp file. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- bin/gstack-developer-profile | 105 ++++++++++++++++++++------ test/gstack-developer-profile.test.ts | 84 +++++++++++++++++++++ 2 files changed, 164 insertions(+), 25 deletions(-) diff --git a/bin/gstack-developer-profile b/bin/gstack-developer-profile index b5db052621..f60f03be09 100755 --- a/bin/gstack-developer-profile +++ b/bin/gstack-developer-profile @@ -25,6 +25,10 @@ # `completed` events in projects/*/timeline.jsonl. # Idempotent; backfilled rows count for tenure only. # +# Writers (--derive, --log-session, --reconcile, --migrate) hold +# developer-profile.json.lock for their read-modify-write and exit 5 when +# another writer keeps it past the give-up window (#3437). +# # Profile file: ~/.gstack/developer-profile.json (unified schema — see # docs/designs/PLAN_TUNING_V0.md). Event file: ~/.gstack/projects/{SLUG}/ # question-events.jsonl. @@ -52,10 +56,63 @@ SLUG="${SLUG:-unknown}" CMD="${1:---read}" shift || true +# ----------------------------------------------------------------------- +# Profile lock (#3437). Every subcommand that rewrites the profile reads, +# changes and renames the whole file, and gstack-question-log starts a +# background --derive after every append, so writers overlap: a shared temp +# name made renames fail and an unlocked rewrite dropped a concurrent +# --log-session. Writers hold a mkdir lock (.lock/ with an owner +# token; release is ownership-checked) from before their read until after +# their rename, and write a unique temp file. A lock older than 30 s belongs +# to a crashed writer and is taken over by atomic rename. A writer that +# cannot get the lock within the give-up window writes nothing and exits 5. +# Same shape as bin/gstack-settings-hook's mutation lock. +# ----------------------------------------------------------------------- +LOCK_DIR="$PROFILE_FILE.lock" +LOCK_TOKEN="" +PROFILE_TMP="" + +cleanup() { + if [ -n "$PROFILE_TMP" ]; then rm -f "$PROFILE_TMP"; fi + if [ -n "$LOCK_TOKEN" ] && [ "$(cat "$LOCK_DIR/owner" 2>/dev/null || true)" = "$LOCK_TOKEN" ]; then + rm -rf "$LOCK_DIR" + fi +} +trap cleanup EXIT +trap 'exit 130' INT +trap 'exit 143' TERM + +acquire_lock() { + if [ -n "$LOCK_TOKEN" ]; then return 0; fi + mkdir -p "$GSTACK_HOME" + # GSTACK_PROFILE_LOCK_TIMEOUT_MS: test-only override for the give-up. + local give_up_ms="${GSTACK_PROFILE_LOCK_TIMEOUT_MS:-10000}" waited_ms=0 mtime stale + local token="$-$RANDOM$RANDOM" + while ! mkdir "$LOCK_DIR" 2>/dev/null; do + # GNU stat first: BSD-style stat -f on Linux prints a filesystem block. + mtime=$(stat -c %Y "$LOCK_DIR" 2>/dev/null || stat -f %m "$LOCK_DIR" 2>/dev/null || echo "") + case "$mtime" in *[!0-9]*) mtime="" ;; esac + if [ -n "$mtime" ] && [ $(( $(date +%s) - mtime )) -gt 30 ]; then + stale="$LOCK_DIR.stale.$-$RANDOM" + if mv "$LOCK_DIR" "$stale" 2>/dev/null; then rm -rf "$stale"; fi + continue + fi + if [ "$waited_ms" -ge "$give_up_ms" ]; then + echo "gstack-developer-profile: another writer held $LOCK_DIR for ${give_up_ms} ms, so nothing was written (exit 5). A lock left by a crashed writer is taken over once it is 30 s old." >&2 + exit 5 + fi + sleep 0.05 + waited_ms=$(( waited_ms + 50 )) + done + printf '%s\n' "$token" > "$LOCK_DIR/owner" + LOCK_TOKEN="$token" +} + # ----------------------------------------------------------------------- # Migration: builder-profile.jsonl → developer-profile.json # ----------------------------------------------------------------------- do_migrate() { + acquire_lock if [ ! -f "$LEGACY_FILE" ]; then echo "MIGRATE: no legacy file to migrate" return 0 @@ -68,9 +125,7 @@ do_migrate() { fi # Run migration in a temp file, then atomic rename. - local TMPOUT - TMPOUT=$(mktemp "$GSTACK_HOME/developer-profile.json.tmp.XXXXXX") - trap 'rm -f "$TMPOUT"' EXIT + PROFILE_TMP=$(mktemp "$GSTACK_HOME/developer-profile.json.tmp.XXXXXX") cat "$LEGACY_FILE" | bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" -e " const lines = (await Bun.stdin.text()).trim().split('\n').filter(Boolean); @@ -113,11 +168,11 @@ do_migrate() { schema_version: 1, }; console.log(JSON.stringify(profile, null, 2)); - " > "$TMPOUT" + " > "$PROFILE_TMP" # Atomic rename. - mv "$TMPOUT" "$PROFILE_FILE" - trap - EXIT + mv "$PROFILE_TMP" "$PROFILE_FILE" + PROFILE_TMP="" # gbrain-sync: enqueue the migrated file for cross-machine sync (no-op if off). SCRIPT_DIR_E="$(cd "$(dirname "$0")" && pwd)" @@ -205,13 +260,12 @@ do_log_session() { *) echo "gstack-developer-profile: bun printed no verdict while validating the session; nothing was logged" >&2; return 1 ;; esac + acquire_lock ensure_profile - local TMPOUT - TMPOUT=$(mktemp "$GSTACK_HOME/developer-profile.json.tmp.XXXXXX") - trap 'rm -f "$TMPOUT"' EXIT + PROFILE_TMP=$(mktemp "$GSTACK_HOME/developer-profile.json.tmp.XXXXXX") - PROFILE_FILE_PATH="$PROFILE_FILE" RECORD_INPUT="$INPUT" TMPOUT_PATH="$TMPOUT" bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" -e " + PROFILE_FILE_PATH="$PROFILE_FILE" RECORD_INPUT="$INPUT" TMPOUT_PATH="$PROFILE_TMP" bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" -e " const fs = require('fs'); const entry = JSON.parse(process.env.RECORD_INPUT); if (!entry.ts) entry.ts = new Date().toISOString(); @@ -238,8 +292,8 @@ do_log_session() { fs.writeFileSync(process.env.TMPOUT_PATH, JSON.stringify(profile, null, 2)); " - mv "$TMPOUT" "$PROFILE_FILE" - trap - EXIT + mv "$PROFILE_TMP" "$PROFILE_FILE" + PROFILE_TMP="" "$SCRIPT_DIR/gstack-brain-enqueue" "developer-profile.json" 2>/dev/null & } @@ -252,13 +306,12 @@ do_log_session() { # rewritten only when something was added. # ----------------------------------------------------------------------- do_reconcile() { + acquire_lock ensure_profile - local TMPOUT - TMPOUT=$(mktemp "$GSTACK_HOME/developer-profile.json.tmp.XXXXXX") - trap 'rm -f "$TMPOUT"' EXIT + PROFILE_TMP=$(mktemp "$GSTACK_HOME/developer-profile.json.tmp.XXXXXX") - PROFILE_FILE_PATH="$PROFILE_FILE" PROJECTS_DIR="$GSTACK_HOME/projects" TMPOUT_PATH="$TMPOUT" bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" -e " + PROFILE_FILE_PATH="$PROFILE_FILE" PROJECTS_DIR="$GSTACK_HOME/projects" TMPOUT_PATH="$PROFILE_TMP" bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" -e " const fs = require('fs'); const path = require('path'); const profile = JSON.parse(fs.readFileSync(process.env.PROFILE_FILE_PATH, 'utf-8')); @@ -313,13 +366,13 @@ do_reconcile() { console.log('RECONCILE: ' + added + ' backfilled from ' + runs.length + ' office-hours run(s)'); " - if [ -s "$TMPOUT" ]; then - mv "$TMPOUT" "$PROFILE_FILE" - trap - EXIT + if [ -s "$PROFILE_TMP" ]; then + mv "$PROFILE_TMP" "$PROFILE_FILE" + PROFILE_TMP="" "$SCRIPT_DIR/gstack-brain-enqueue" "developer-profile.json" 2>/dev/null & else - rm -f "$TMPOUT" - trap - EXIT + rm -f "$PROFILE_TMP" + PROFILE_TMP="" fi } @@ -494,6 +547,7 @@ function accumulateSignals(lines, QUESTIONS, SIGNAL_MAP, dims) { # Derive: recompute inferred dimensions from question-events.jsonl # ----------------------------------------------------------------------- do_derive() { + acquire_lock ensure_profile local EVENTS="$GSTACK_HOME/projects/$SLUG/question-log.jsonl" local REGISTRY="$ROOT_DIR/scripts/question-registry.ts" @@ -503,8 +557,9 @@ do_derive() { exit 1 fi + PROFILE_TMP=$(mktemp "$GSTACK_HOME/developer-profile.json.tmp.XXXXXX") cd "$ROOT_DIR" - PROFILE_FILE_PATH="$PROFILE_FILE" EVENTS_PATH="$EVENTS" bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" -e " + PROFILE_FILE_PATH="$PROFILE_FILE" EVENTS_PATH="$EVENTS" TMPOUT_PATH="$PROFILE_TMP" bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" -e " import('./scripts/question-registry.ts').then(async (regmod) => { const sigmod = await import('./scripts/psychographic-signals.ts'); const fs = require('fs'); @@ -556,12 +611,12 @@ do_derive() { profile.gap = gap; profile.derived_at = new Date().toISOString(); - const tmp = profilePath + '.tmp'; - fs.writeFileSync(tmp, JSON.stringify(profile, null, 2)); - fs.renameSync(tmp, profilePath); + fs.writeFileSync(process.env.TMPOUT_PATH, JSON.stringify(profile, null, 2)); console.log('DERIVE: ok — ' + count + ' events, ' + skills.size + ' skills, ' + qids.size + ' questions'); }).catch(err => { console.error('DERIVE:', err.message); process.exit(1); }); " + mv "$PROFILE_TMP" "$PROFILE_FILE" + PROFILE_TMP="" } # ----------------------------------------------------------------------- diff --git a/test/gstack-developer-profile.test.ts b/test/gstack-developer-profile.test.ts index 11685bb644..b8b46a8456 100644 --- a/test/gstack-developer-profile.test.ts +++ b/test/gstack-developer-profile.test.ts @@ -752,6 +752,90 @@ describe('gstack-developer-profile --log-session (#1671 fix)', () => { }); }); +// ----------------------------------------------------------------------- +// Concurrent writers (#3437). gstack-question-log starts a background +// --derive after every append, and a multi-question AskUserQuestion logs +// several rows at once, so derives overlap each other and /office-hours' +// --log-session. Each subcommand rewrites the whole profile, so every +// read-modify-write holds the profile lock and writes a unique temp file. +// ----------------------------------------------------------------------- + +async function runDevAsync(...args: string[]): Promise<{ stdout: string; stderr: string; status: number }> { + const proc = Bun.spawn([BIN_DEV, ...args], { + env: { ...process.env, GSTACK_HOME: tmpHome }, + cwd: ROOT, + stdout: 'pipe', + stderr: 'pipe', + }); + const timer = setTimeout(() => proc.kill(), 60_000); + const [stdout, stderr, status] = await Promise.all([ + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + proc.exited, + ]); + clearTimeout(timer); + return { stdout, stderr, status }; +} + +describe('gstack-developer-profile concurrent writers (#3437)', () => { + const lockDir = () => path.join(tmpHome, 'developer-profile.json.lock'); + + test('--derive does not write through a fixed temp path', () => { + fs.mkdirSync(path.join(tmpHome, 'developer-profile.json.tmp')); + const r = runDev('--derive'); + expect(r.stderr).toBe(''); + expect(r.status).toBe(0); + expect(typeof (readProfile() as { derived_at?: string }).derived_at).toBe('string'); + }); + + test('a held profile lock keeps --derive and --log-session from writing', () => { + expect(runDev('--derive').status).toBe(0); + const before = fs.readFileSync(path.join(tmpHome, 'developer-profile.json'), 'utf-8'); + fs.mkdirSync(lockDir()); + fs.writeFileSync(path.join(lockDir(), 'owner'), 'another-writer\n'); + const env = { ...process.env, GSTACK_HOME: tmpHome, GSTACK_PROFILE_LOCK_TIMEOUT_MS: '300' }; + for (const args of [['--derive'], ['--log-session', JSON.stringify({ date: '2026-10-31', mode: 'builder' })]]) { + const res = spawnSync(BIN_DEV, args, { env, encoding: 'utf-8', cwd: ROOT, timeout: 30_000 }); + expect(res.status).toBe(5); + expect(res.stderr).toContain('developer-profile.json.lock'); + } + expect(fs.readFileSync(path.join(tmpHome, 'developer-profile.json'), 'utf-8')).toBe(before); + expect(fs.readFileSync(path.join(lockDir(), 'owner'), 'utf-8')).toBe('another-writer\n'); + }); + + test('a stale lock left by a crashed writer is taken over', () => { + fs.mkdirSync(lockDir()); + const old = new Date(Date.now() - 120_000); + fs.utimesSync(lockDir(), old, old); + const r = runDev('--log-session', JSON.stringify({ date: '2026-10-31', mode: 'builder', project_slug: 'p' })); + expect(r.status).toBe(0); + expect((readProfile() as { sessions: unknown[] }).sessions.length).toBe(1); + expect(fs.existsSync(lockDir())).toBe(false); + }); + + test('overlapping derives and log-sessions keep every session and leave valid JSON', async () => { + for (let i = 0; i < 5; i++) { + logQuestion({ skill: 'plan-ceo-review', question_id: 'plan-ceo-review-mode', question_summary: 'mode', user_choice: 'expand', session_id: 's' + i }); + } + expect(runDev('--derive').status).toBe(0); + const rounds = 6; + for (let round = 0; round < rounds; round++) { + const runs = await Promise.all([ + ...Array.from({ length: 6 }, () => runDevAsync('--derive')), + runDevAsync('--log-session', JSON.stringify({ date: '2026-10-31', mode: 'builder', project_slug: 'round-' + round })), + ]); + for (const r of runs) { + expect(r.stderr).toBe(''); + expect(r.status).toBe(0); + } + } + const p = readProfile() as { sessions: Array<{ project_slug: string }>; inferred: { sample_size: number } }; + expect(p.sessions.map((s) => s.project_slug).sort()).toEqual(Array.from({ length: rounds }, (_, i) => 'round-' + i).sort()); + expect(p.inferred.sample_size).toBe(5); + expect(fs.readdirSync(tmpHome).filter((f) => f.startsWith('developer-profile.json.'))).toEqual([]); + }, 120_000); +}); + // ----------------------------------------------------------------------- // SESSION_COUNT / TIER / NUDGE_ELIGIBLE must ignore mode:resources entries. //