Log Session Header Write Mode
What Happened

The Dakka log system needed a session header (timestamp, process ID, config snapshot) on first write, then append-only for all subsequent entries. Using appendFileSync for everything caused duplicate headers from crashed sessions to pile up at the top of the file. Switching to writeFileSync for everything overwrote all previous entries : only the last flush survived. Both approaches were wrong.
Root Cause
See definitions/root-cause-analysis for the analytical framework. Specific cause: two conflicting requirements : each session needs a clean header block, but within a session entries must accumulate. Neither pure-append nor pure-overwrite satisfies both simultaneously. The state that determines which write mode to use (has the header been written for this session?) was not being tracked.
How to Avoid
Use writeFileSync for the first flush (writes the session header plus the first batch of entries), then switch to appendFileSync for all subsequent flushes. Track the mode with a boolean flag per log file:
let headerWritten = false;
function flush(entries: string[]) {
const payload = headerWritten
? entries.join('\n') + '\n'
: formatHeader(session) + '\n' + entries.join('\n') + '\n';
if (!headerWritten) {
fs.writeFileSync(logPath, payload);
headerWritten = true;
} else {
fs.appendFileSync(logPath, payload);
}
}
Related
- projects/dakka/_index : parent project
- log-buffer-requeue-on-flush-failure : companion STATE pitfall: what happens when the append itself fails