Skip to content

bug: session-metadata.json is replaced without fsync, so a crash can empty it #1547

Closed

Description

@huang195

What happens

SaveMetadata (core/observe/claude/harvest.go:2009-2037) replaces ~/.cortex/session-metadata.json by writing a temp file and renaming it over the old one, without flushing the temp file to disk first.

If the machine loses power or the kernel panics soon after a save, the rename can reach disk before the file's data does. The file is then empty or partial.

Why it matters

  • What is lost: on the next start the harvest finds the file unreadable and rebuilds it from the Claude Code transcripts still on disk. Titles for transcripts that have since been pruned cannot be rebuilt, and are gone.
  • How often it is exposed: the file is rewritten often, 4 times in 5 minutes on a busy laptop (769 KB, 1,912 entries).
  • Prior art: every other state file Cortex writes this way does flush first:
    • the plugin store, core/storage/filestore/store.go:382-389, flushes then renames;
    • the archive's session.json (core/session/archive/meta.go:71) flushes the file, renames, then flushes the directory;
    • the ledger appends, then flushes.

Fix

Add f.Sync() before f.Close(), folded into the same err the comment at :2014 guards:

_, err = writeAll(f, body)
if err == nil {
	err = f.Sync()
}
if cerr := f.Close(); err == nil {
	err = cerr
}

Optionally also flush the directory after the rename, as the archive does.

Related (not a bug today)

The file never evicts entries: October alone added 1,316 of its 1,912. Past its 16 MB read cap, Harvest returns ErrCorruptMetadata on every run and titles stop updating. At today's rate that is years away, so it is not filed.


Found by an experiment-driven audit of main at 43cf553; every number above was re-measured on that commit.

Assisted-By: Claude (Anthropic AI) [email protected]

Activity

  1. added
    bug
    laptop
    on Oct 29, 2026
  2. self-assigned this
    on Oct 29, 2026
  3. huang195 commented on Oct 29, 2026

    @huang195
    MemberAuthor

    CI guard for this bug class: #1554. The same scan finds 12 functions that write a temp file and rename it without Sync, including the TLS bridge CA, ~/.claude/settings.json and ~/.cortex/config.yaml. The list is in #1554.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

buglaptop

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions