Skip to content

fix(storage): tolerate malformed legacy session headers during import - #1426

Merged
Astro-Han merged 7 commits into
apache:mainfrom
sunheyi6:fix/legacy-session-malformed-header-tolerance
Jul 24, 2026
Merged

Astro-Han merged 7 commits into
apache:mainfrom
sunheyi6:fix/legacy-session-malformed-header-tolerance

Conversation

@sunheyi6

@sunheyi6 sunheyi6 commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A malformed legacy session.jsonl header no longer blocks startup migration or hides every valid session. The importer skips only repairable legacy-content failures, writes no deletion tombstone, and retries the session on a later launch so a repaired header can be imported.

The error boundary now preserves the existing fail-closed behavior for filesystem failures and invalid current-format session_transcript markers. A private structured error identifies only legacy framing, JSON, and header-decoding failures; message matching, cause-chain inspection, and filesystem error-code heuristics have been removed.

The public SessionStore tests cover empty and truncated files, a complete valid header beyond the 1 MiB limit, the reported turn_state first-record failure, invalid current marker identities/schema versions, repair and reopen, no tombstones, and no partial import on environmental or marker failures. Repeated recovery cases are table-driven.

Verification

  • npm --workspace @maka/storage test — 478 passed, 1 existing Windows-only test skipped
  • npm run format:check — passed
  • npm run lint — passed
  • npm --workspace @maka/storage run typecheck — passed
  • Targeted session-metadata-transfer and sqlite-session-store suites — 18 passed
  • Mutation check: temporarily raising the production limit to 2 MiB made the >1 MiB regression test fail by importing the oversized valid header, confirming the test isolates the size cap; the production limit was restored before commit
  • GitHub CI on d1fae87f7 — typecheck, test, and e2e passed

Root cause

The legacy migration originally treated every non-ENOENT read/decode failure as fatal. An intermediate fix then wrapped all non-filesystem failures as malformed legacy headers, which also swallowed validation errors from current-format transcript markers. The final implementation assigns recoverable status at the source: legacy framing/JSON/header errors use one private error type, while current marker validation and real I/O errors propagate unchanged.

sunheyi6 added 2 commits July 24, 2026 09:12
A corrupt session.jsonl whose first line is not a valid SessionHeader
(e.g. a turn_state record written without a preceding header) would
crash importLegacySessionMetadataTree, taking down onboarding:getSnapshot
and sessions:list and rendering the app unusable.

Gracefully skip the corrupt session: if it already has canonical SQLite
metadata, leave it untouched; otherwise tombstone it via destination.remove()
so it is not retried on every subsequent launch.  All remaining valid
sessions continue to import normally.

Update the existing test from 'rejects one malformed header' to
'skips a malformed header and tombstones it while importing valid sessions'
to verify the new fail-soft behaviour.
The malformed-header tolerance change left sqlite-session-store still expecting fail-closed import. Align the startup migration test with skip-and-tombstone behavior so CI matches the new contract.

@Astro-Han Astro-Han left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The malformed-header recovery works as intended. I found two non-blocking issues:

  • [P2] readLegacySessionMetadataEntry() wraps every failure from opening, reading, parsing, decoding, and closing the file as Invalid legacy session header. isMalformedLegacySessionHeader() then accepts that outer message by itself, so a transient EACCES, EIO, or close failure is treated as corrupt data and permanently tombstones the session. Classify the underlying parse or validation errors instead of the generic wrapper. A test that injects a non-ENOENT filesystem failure would lock this down.
  • [P2] Malformed-session tombstones are written through destination.remove() while the scan is still in progress, before importEntries() starts its transaction. If a later directory has a missing transcript marker or the final import conflicts, the import rejects but the earlier tombstone remains committed. A repaired legacy header will then stay suppressed on the next startup. Commit the tombstones with the successful import, or roll them back when the scan or import fails. The current test covers only the success path.

Approving because neither issue is a P0 or P1, but both cases should be covered before this migration path is treated as failure-safe.

@Astro-Han Astro-Han left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Skipping a bad legacy header is the right behavior, but this patch can turn a read failure into permanent deletion state.

[P2] destination.remove() writes the same tombstone used for user deletion. Once that happens, importEntries() will keep skipping the session even if its header is repaired. For malformed legacy content, skip the session without calling remove(). If persistent quarantine is required, it needs separate semantics from deletion.

[P2] remove() runs during the scan, before the final importEntries() transaction. If a later marker check or import fails, the earlier tombstone remains committed. That leaves a partial migration even though the function promises a single transaction. Keep the scan free of writes, or commit quarantine state with the import batch.

…cy import

Address P2 review comments from apache#1426:

1. Classify underlying errors instead of generic wrapper:
   readLegacySessionMetadataEntry now lets file I/O errors (EACCES, EIO,
   EISDIR, etc.) propagate without wrapping them as 'Invalid legacy session
   header'. Only parse/decode failures (JSON.parse, decodeSessionHeader,
   decodeSessionTranscriptMarker) are wrapped, so transient filesystem
   errors are no longer mistaken for corrupt data and do not permanently
   tombstone repairable sessions.

2. Defer tombstone writes until after scan and import succeed:
   Tombstone session IDs are collected during the scan and applied only
   after importEntries completes. If a later scan step fails (e.g. missing
   transcript marker) or the import throws, no tombstones are committed,
   so the malformed session will be retried on the next launch instead of
   being permanently suppressed.

Added two tests:
- 'does not tombstone a session when a non-ENOENT filesystem error occurs':
  replaces a session file with a directory (EISDIR) and verifies the import
  throws without tombstoning.
- 'does not tombstone a malformed header when a later scan step fails':
  creates a malformed header + orphan transcript marker, verifies the
  scan failure prevents tombstoning, then removes the orphan and verifies
  a re-run succeeds and tombstones correctly.
@sunheyi6

Copy link
Copy Markdown
Contributor Author

Thanks for the review! I've pushed a commit addressing both P2 issues:

P2-1: Classify underlying errors instead of generic wrapper

readLegacySessionMetadataEntry now calls readFirstJsonlRecord outside the try-catch, so filesystem I/O errors (EACCES, EIO, EISDIR, etc.) propagate without being wrapped as "Invalid legacy session header". Only parse/decode failures (JSON.parse, decodeSessionHeader, decodeSessionTranscriptMarker) are wrapped, so isMalformedLegacySessionHeader() no longer matches transient filesystem errors.

Test added: does not tombstone a session when a non-ENOENT filesystem error occurs — replaces a session file with a directory (EISDIR) and verifies the import throws without tombstoning.

P2-2: Defer tombstones until after scan and import succeed

Tombstone session IDs are now collected during the scan and applied only after importEntries() completes. If a later scan step fails (e.g. missing transcript marker) or the import throws, no tombstones are committed — the malformed session will be retried on the next launch instead of being permanently suppressed.

Test added: does not tombstone a malformed header when a later scan step fails — creates a malformed header + an orphan transcript-marker directory with no SQLite metadata, verifies the scan failure prevents tombstoning, then removes the orphan and verifies a re-run succeeds and tombstones correctly.

All 6 tests pass.

sunheyi6 added a commit to sunheyi6/maka-agent that referenced this pull request Jul 24, 2026
Address second round of P2 review comments from apache#1426:

destination.remove() uses the same tombstone as user deletion, which
permanently suppresses a session even if its header is later repaired.
For malformed legacy content, skip the session without calling remove()
so it will be retried on the next launch. If the header is repaired, the
next import picks it up; if still corrupt, it is harmlessly skipped again.

Updated tests:
- 'skips a malformed header without tombstoning it while importing valid
  sessions': verifies skip-without-tombstone, then repairs the header and
  verifies it is imported on the next run.
- 'skips a malformed header without tombstoning when a later scan step
  fails': verifies no tombstone is written when a later scan step fails,
  and re-running after removing the orphan imports the valid session while
  skipping (not tombstoning) the malformed one.
@sunheyi6

Copy link
Copy Markdown
Contributor Author

Updated to address the second round of P2 comments — thank you for catching this.

Skip without tombstoning (both P2 comments)

destination.remove() uses the same tombstone as user deletion, which permanently suppresses a session even if its header is later repaired. For malformed legacy content, the scan now simply skips the session (continue) without calling remove(). This means:

  • A malformed session is retried on the next launch (harmless — it will be skipped again until repaired).
  • If the header is repaired, the next import picks it up normally.
  • No permanent deletion state is written for corrupt data.
  • The scan is free of writes, so there is no partial migration to roll back.

Test updates

  • 'skips a malformed header without tombstoning it while importing valid sessions': verifies skip-without-tombstone, then repairs the header and verifies it is imported on the next run.
  • 'skips a malformed header without tombstoning when a later scan step fails': verifies no tombstone is written when a later scan step fails, and re-running after removing the orphan imports the valid session while skipping (not tombstoning) the malformed one.

All 6 tests pass.

Address second round of P2 review comments from apache#1426:

destination.remove() uses the same tombstone as user deletion, which
permanently suppresses a session even if its header is later repaired.
For malformed legacy content, skip the session without calling remove()
so it will be retried on the next launch. If the header is repaired, the
next import picks it up; if still corrupt, it is harmlessly skipped again.

Updated tests:
- 'skips a malformed header without tombstoning it while importing valid
  sessions': verifies skip-without-tombstone, then repairs the header and
  verifies it is imported on the next run.
- 'skips a malformed header without tombstoning when a later scan step
  fails': verifies no tombstone is written when a later scan step fails,
  and re-running after removing the orphan imports the valid session while
  skipping (not tombstoning) the malformed one.
@Astro-Han

Copy link
Copy Markdown
Contributor

Unit test is falling, Would need to fix it before merging.

@sunheyi6
sunheyi6 force-pushed the fix/legacy-session-malformed-header-tolerance branch from ebd5019 to 90c371a Compare July 24, 2026 06:33
@sunheyi6

Copy link
Copy Markdown
Contributor Author

Unit test is falling, Would need to fix it before merging.

done

…undary tests

Move readFirstJsonlRecord back inside the try-catch in
readLegacySessionMetadataEntry, but re-throw filesystem I/O errors
(errors with a .code property like EACCES, EIO, EISDIR) without wrapping.
This ensures framing/content errors (empty file, no newline, oversized
header) are wrapped as 'Invalid legacy session header' and caught by
isMalformedLegacySessionHeader(), while transient I/O failures still
propagate.  Without this fix, an empty or truncated session.jsonl would
crash the import — the exact startup failure this PR is meant to prevent.

Add comprehensive tests at the public SessionStore boundary covering:
- Empty session.jsonl
- Truncated JSON without a newline
- First record over the 1 MiB limit
- turn_state first record (the original bug scenario)
- EISDIR filesystem failure (asserts actual error code)

Each corrupt-content test verifies store.list() resolves, the valid
session is visible, the corrupt session is absent with no tombstone,
and that repairing the file allows the session to be imported on the
next launch.  The EISDIR test asserts the error code and verifies no
metadata or tombstone is written.
@Astro-Han

Copy link
Copy Markdown
Contributor

The current schema-error and repair tests cover one branch. To close this out, please make the additional cases assert behavior at the public SessionStore boundary rather than only checking that some promise rejects.

I would cover these cases:

  • Empty session.jsonl: store.list() resolves, valid sessions remain visible, the corrupt session is absent, and no tombstone is written.
  • Truncated JSON without a newline: the same catalog-level assertions as the empty-file case.
  • A first record over the 1 MiB limit: the catalog remains usable and the session is skipped without a tombstone.
  • A real turn_state first record, matching the failure described in the PR: valid sessions remain available through createSessionStore().
  • A file-system failure such as EISDIR: assert the actual error code or class, not only assert.rejects(), and verify that neither metadata nor a tombstone was written.

For each corrupt-content case, repair the file, reopen the store, and assert that the session is imported. That locks in the user-visible contract and avoids testing only an internal error-message shape.

Also we got to fix typecheck.

Biome format:check was failing on the public SessionStore boundary tests, which blocked the typecheck CI job.
@sunheyi6

Copy link
Copy Markdown
Contributor Author

Addressed the latest review feedback:

Public SessionStore boundary tests (already on head, reformatted)

Assert behavior through createSessionStore() / store.list() rather than internal promise rejection shapes:

  • Empty session.jsonl: list resolves, valid session visible, corrupt absent, no tombstone; repair → reimport works
  • Truncated JSON without newline: same catalog-level contract + repair path
  • First record over 1 MiB: same + repair path
  • turn_state first record (the original bug): valid sessions remain available + repair path
  • EISDIR: asserts error.code === 'EISDIR', and verifies neither metadata nor tombstone was written

Typecheck / format

Biome format:check was failing on the boundary-test helpers. Pushed a format-only fix (ad8a7d68).

CI is green: typecheck / test / e2e all pass.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants