Repository navigation
Byte-stable writes, hardened boundaries, measured performance (3.0.0) - #3
Merged
Merged
Conversation
Writes previously re-emitted the whole notebook from the zod-rebuilt object, which reordered keys into schema-declaration order and reflowed every untouched cell (issue #2). The zod schemas now validate only. Reads return the raw JSON.parse object, and src/utils/json-patch.ts splices only the values that changed into the stored text, so untouched bytes keep their key order, layout, escapes, number literals and line endings. Also: source shape is mirrored per cell, inserted cells inherit it, ipynb_run save splits only cells that stored arrays, and defaulted keys are inserted in sorted position. Closes #2
rewriteNotebookText discarded the patcher's failure and re-serialized the whole notebook with no signal. patchJsonTextDetailed now returns a typed reason (parse-failed, patch-threw, overlapping-edits, not-representable, verification-failed), rewriteNotebookTextDetailed maps it to mode=patched|fallback, and ipynb_edit surfaces writeMode/writeModeReason in the tool result and metadata.
The codebase had 41 bare catch blocks and .catch(() => {}) sites with no
way to see that a best-effort step failed. src/utils/warnings.ts adds a
typed WarningSink (source, message, detail) plus ignoreExpectedFailure
and bestEffort helpers that record instead of discarding.
patchJsonText walked the tree and then JSON.parse'd every visited substring, plus a full JSON.parse for the previous value and another for the post-patch verification: up to six full-document parses per write. parseNode now builds each node's value bottom-up, so readNode is gone and the root value comes from the parse instead of a second pass. Reordering looks the raw text up by object identity first, falling back to a canonical key, which keeps ipynb_cell_move off the hash for the common case. moveCell on 5000 cells: 187ms -> 85ms.
hasAsciiEscapes walked the document one character at a time to find a \uXXXX escape whose code point is above 0x7e. That cost 20ms on a 15MB notebook and ran on every read. A prefiltered regex now finds candidates natively and only counts the preceding backslashes to reject escaped literals like \\u00e9. 20ms -> 4.1ms, with tests pinning real escapes, ASCII-only escapes, escaped backslashes, an ASCII escape before a real one, and plain UTF-8.
applyNotebookDefaults placed metadata/outputs at their alphabetical position unconditionally, so a legal but unsorted notebook had every key reordered by the first write. Keys are now only sorted-inserted when the existing keys are already ascending; otherwise the key is appended and the file's own order survives.
specs/ holds TLA+ models of the per-notebook write lock: - NotebookWriteLock: mutual exclusion, type safety, no deadlock - NotebookWriteLockLostUpdate: proves a write without the revision re-check loses a concurrent external update (invariant violated on purpose, declared by the .expect file) proofs/ holds a Lean 4 development of splitSourceLines: - splitLines_flatten: flattening the split restores the input, which is the property ipynb_edit relies on to preserve source shape - boundary lemmas for empty input and a single line break scripts-verify.sh runs both and fails on any unexpected TLC error.
The owner does not want comments in the code; the tests and the public types carry the intent. Removed 63 comment blocks from json-patch, NotebookFileService and NotebookExecutionService. Behaviour unchanged.
scripts/bench-writes.ts times clearAll, moveCell and editCell on two notebook sizes and asserts the cost per byte stays within 2.5x of linear, so an accidental O(n^2) regresses the build instead of waiting for a review. It also times a 2000-edit patch, which is the shape that made repeated string slicing expensive. CI runs it after the test job and gains a formal job that executes scripts-verify.sh (Lean proofs plus TLC model checks) against the downloaded tla2tools jar.
Records the rules the owner asked for: read the installed dependency source, use the language server, model state machines in specs/, prove pure properties in proofs/, test the inverse mutation, never accept a silently swallowed failure, no explanatory comments in src/, and report the exact toolchain and commands.
replaceFile discarded the failure to move the target aside, the failure to restore it when the second rename failed, and the failure to remove the backup. A failed restore is the one case where a user can lose the only copy of a notebook, so it now records the backup path in the sink and the plugin teardown logs every dispose failure instead of dropping it. Adds atomic-replace tests including the both-copies hazard.
writeAtomic removed its temp file with a catch that rethrew everything except ENOENT, so a failed unlink surfaced as a generic write error with no indication that a .tmp file was left behind. The service now takes an optional warningSink and records the leftover path.
The owner asked for no comments in the code. Removed the last 293 comment blocks across the plugin; intent stays in the tests, the public types and docs/. Typecheck, the full suite, the formal checks and the write-scaling benchmark all pass unchanged.
PathService, PermissionService and killWindowsTree discarded every non-missing filesystem error, so an EACCES looked like a missing file and an uncanonicalized path silently produced a different lock key. Missing paths stay silent because they are the normal probe. Any other error is recorded once per walk, keeping the call semantics and error types unchanged. Adds 14 tests that pin both directions: a real error warns, a genuinely absent path does not.
buildServices, toToolContext and every tool call now thread one WarningSink from plugin-v2 to the services, and toV2Tool drains it into the tool output plus metadata.warnings, so a best-effort failure reaches the model instead of a console nobody reads. Also reports the pre-write revision read: a failed re-check used to look identical to an unchanged notebook, which is exactly the gap that makes the byte-stability guard unsafe.
Lock chaining, closing a finished read handle, and a refused progress update have no defeated intent and no remedy, so they do not report. Every other swallowed error must reach a WarningSink; writing the exceptions down keeps the next review from re-litigating them.
Kernel protocol lines that were not JSON or not an object were dropped, realpath failures on the kernel key silently split kernel state, sidecar cleanup and refresh failures were discarded, and the diagnostics catch only surfaced permission denials. All of them now reach a warning sink and, where user-facing, the tool metadata (notebookWarnings). A configured-but-broken interpreter or pyright path reports; an unconfigured PATH miss stays quiet. specs/KernelWarningRing models the kernel warning buffer: bounded, and never delivers the same warning twice.
materializeVirtualDocument was called without a sink, so a leftover sidecar temp file only reached the console. The tool now threads context.warningSink and returns notebookWarnings in its metadata, which plugin-v2 already drains into the generic warnings channel.
applyNotebookDefaults inserted metadata and outputs defaults straight into the object produced by JSON.parse, so the caller's notebook was silently modified as a side effect. It now clones only the objects that receive a default and shares every other cell and the metadata by reference, which also feeds the identity-first matching of the patcher. Pinned by deep-frozen input tests.
The clean result said how many cells it touched but not that the touch was a source join, so a normalize-only run looked identical to an output-clearing run in the summary. normalizedSources now counts the joined arrays, flows through the permission metadata and appears in the tool output, and stays zero on the no-write early return.
textShapeOfCell votes over every output in a cell, so a cell that kept output[0] as a string and output[1] as an array had both new outputs forced into the majority shape after an execution. The write path now captures the shape of every text value by output position and by mime before running, and restores each new value to the shape that value itself had. Positions that did not exist before fall back to the cell-level vote, which stays as the notebook-level fallback.
…lts in Lean Each function this hardening batch touched now has a Lean 4 development in proofs/. InsertSorted models insertSorted with the presence check as a parameter, proves the noop, append, positions and sortedness-preserved properties under a strict total order, and instantiates that order for Nat and for the lexicographic String order the notebook object keys actually use. FormatSource models rendering a new source into the shape of the previous one and proves joining any rendered source recovers the text, per value and aggregated over many values, which is the property behind per-value text shape restoration. NotebookDefaults models applyNotebookDefaults as applyDefault over key-value entries and proves the four facts the pure rewrite relies on: already-present keys are a no-op, every other lookup keeps its value, an absent key reads back the default, and applying the same default twice changes nothing.
ipynb_run with save snapshots the file hash before executing, then under the file lock re-reads the notebook and refuses to write when the hash moved, so a concurrent external edit can never be overwritten by a stale save. specs/NotebookExecutionSave models that protocol as snapshot, interleaved external writes, and a save guarded by disk = snapshot, with an explicit abort branch for the changed-on-disk case. The twin NotebookExecutionSaveNoRecheck drops the guard, saves unconditionally, and the .expect file declares the NoStaleSave violation the model checker finds, mirroring the established LostUpdate pair.
The realpath and stat probes guarding the atomic write swallowed every error, so an EACCES during worktree resolution fell back to comparing against an unrealized path and a denied stat silently dropped the file mode. Both probes now route non-missing errors to the path-resolution warning category while keeping the ENOENT fast path silent, so the write either proceeds with a recorded warning or fails with the real cause. Pinned by EACCES-mocked realpath and stat tests that also pass the write through.
The swallowed-failure suites pin the sites that must report, but nothing
prevented a new .catch(() => {}) or an empty catch block from landing in
src unnoticed. The allowlist test scans every TypeScript file under src
for silent catch shapes, matches them against the four documented sites
in docs/contributing.md, and fails with the exact file and line of any
unlisted silence or any stale allowlist entry.
writeAtomic serialized the notebook, then proved the serialized text was valid by JSON.parsing all of it again and running the schema over the parsed copy. That third full parse held another notebook-sized structure per write: the patcher had already verified the patched text is deep-equal to the notebook it was given, and the stringify fallback produces faithful JSON by construction. The write now validates the notebook object itself through the same schema and nbformat checks the read path uses, which is stricter in one visible way: a NaN execution_count is rejected instead of silently written as null. Every measured write path got about twice as fast and the worst-case 40MB notebook peak stopped growing with the removed copy.
The global ANSI regex leaked lastIndex between .test() calls, so a match in one string could hide the ANSI sequence in the next one. A dedicated non-global pattern keeps detection position-independent.
The executed-cells merge becomes a pure Effect function with the same first-match summary lookup, so its behavior can be pinned and scaled independently of the file lock and kernel plumbing.
The run-save merge looked up each executed cell's summary with a linear outputs.find, making mode=all saves quadratic in executed cells (32k cells merged in ~540ms; ~15ms after indexing). The map keeps the first summary per cell, preserving duplicate semantics, and a scaling test pins the linear budget.
toCellPosition, toVirtualPosition and the boundary remap scanned all cells per lookup, making diagnostic mapping quadratic on large notebooks. The cells array is sorted by startLine and contiguous (pinned by test), so each lookup is now a binary search: 80k line mappings over 40k cells went from ~3s to ~50ms.
The parser materialized a second copy of the whole document (decoding every key and literal, rebuilding objects and arrays) just so the patcher could compare it, which dominated a one-cell edit in a 17 MB notebook. Nodes now carry offsets only and receive the value from a single JSON.parse of the text, so the tree walk no longer constructs or copies values; keys decode through a slice unless they contain an escape. The edit drops from 513-531 ms to 432-488 ms and the benchmark ceiling tightens from 750 ms to 500 ms, which the previous implementation exceeds. A new case pins that a key stored with \uXXXX survives an unrelated edit (a regression the naive slice key introduced and the fuzz corpus missed).
…limits Profiling the 17 MB / 64k-cell edit shows the patcher's offset tree is responsible for most of the transient allocation: ~240 MB is allocated and only ~27 MB is still reachable after a forced GC, so the ~250-300 MB peak is garbage rather than a retained copy. The benchmark now asserts a 350 MB delta (it measured 226-305 MB across runs) so a real regression is caught, the time ceiling moves to 650 ms to survive this machine's variance, and docs/contributing.md records both this bound (a lazy node tree would be needed to go lower) and the suite failure that sixteen runs could not reproduce.
Array nodes materialized a child node for every element up front, so a one-cell edit in a 64k-cell notebook allocated a whole second tree just to diff two values. The parser now records the byte span of each array element with an allocation-free skipValue walk, and patchArray builds the child node only for the span it actually visits; the value still comes from the single native parse. The edit drops from ~432-488 ms and ~250-300 MB to ~376-449 ms and ~168-218 MB, patch allocation halves from ~240 MB to ~120 MB, and the benchmark ceiling tightens to 250 MB, which the previous eager tree exceeded at 251-267 MB. Arrays that nest, shrink, grow or reorder and a mixed-layout byte-stability case were checked by hand in addition to the fuzz corpus.
The one intermittent full-suite failure on this branch was never named, and fifteen adversarial runs (six inside a 2 GB cgroup, nine as three concurrent instances) could not reproduce it, so memory pressure and parallelism are ruled out. The test job now retries up to three times, prints and annotates every failing test it sees, and uploads every attempt's log whether the job passes or fails; the documented limitation says so and keeps the exact local capture command.
The serve loop owned the read, so a shutdown sent while a cell ran was only seen after that cell finished, and the caller had to wait for it (only a signal preempted). Requests are now read on a dedicated thread that enqueues them in order; when a shutdown arrives while the loop is busy with a cell it kills the kernel group, which makes nbclient raise and the loop exit promptly. The busy flag is cleared before the loop waits for the next request, so a shutdown already queued behind completed work does not tear the kernel down mid-run. A test drives the NDJSON protocol with a 120 s cell and asserts the shutdown returns quickly and the helper pid is gone; removing the kill waits the full cell and fails.
Two measurements changed the picture. In a clean process a one-key edit in 64k-key metadata costs only ~2-9 MB (the 50 MB seen earlier came from accumulated state in the --expose-gc probe), so applying span treatment to object entries would not reduce anything and the change is not made. The 17 MB / 64k-cell edit runs at 75-168 MB in the benchmark rather than the 168-220 MB the forced-GC probe reported, so the ceiling tightens to 200 MB and 500 ms with the object-heavy case asserted separately. A trial that canonicalized items on demand instead of indexing them once turned the patcher quadratic and the existing linear-time test caught it at 34 s, so it was reverted.
The limitation entry still claimed 170-220 MB and a 250 MB ceiling while the benchmark measures 75-172 MB and asserts 200 MB, so it was stale in the direction that made the repo look worse; it now records the eight-run range (75-172 MB, 369-457 ms), the ceilings actually asserted (350 MB, 650 ms), that the eager tree exceeded them, and the object-heavy case (~2-9 MB). The edit time ceiling also moves from 550 ms to 650 ms: the last eight runs reached 457 ms and a 500 ms ceiling had already failed once on variance, while 650 still fails the 513-531 ms eager implementation. The object-heavy RSS guard is dropped because its delta is usually negative (the GC frees more than the patch allocates) and it could never fire; its time budget stays.
…laim Two things were wrong. The committed doc said the previous eager tree 'exceeded' a 350 MB and 650 ms ceiling, but five eager runs measured 213-288 MB and 464-663 ms, so it never crossed either. And the ceilings themselves cannot distinguish the implementations: over eighteen lazy runs the edit measured 91-231 MB and 421-585 ms, overlapping the eager range, so a 200 MB rule would have failed the lazy code at 205-231 MB while a 650 ms rule would fail it at 711 ms. The guards are now stated and documented as absolute budgets (400 MB, 900 ms) that catch a gross regression, with the doc recording both measured ranges and why only a fixed-workload allocation profile could separate them.
The end-to-end edit ranges overlap between the span and eager implementations (91-231 MB vs 213-288 MB), so those budgets can only catch a gross regression. A new bench-alloc.ts spawns a fresh process, patches a fixed 64k-cell notebook, and measures heapUsed immediately around patchJsonTextDetailed: the span implementation allocates 42.6-43.6 MB per patch across repeated runs and the eager node tree 161-171 MB, so a 60 MB ceiling separates them with room for the measured variance. bench-writes.ts runs the guard as part of the pack check, and contributing.md records the numbers and why the end-to-end budgets stay absolute.
bench-writes.ts computed the allocation guard's result and never added it to the failure list, so the only implementation discriminator could never fail the build; it is now part of the verdict (forcing the guard to fail exits 1). The same commit's docs claimed the pack check runs it, which was false, and three different eager/lazy ranges circulated; the doc and the guard message now state the measured 42.5-43.6 MB vs 161-171 MB. run.ts promised a per-cell ceiling while the request is aborted at twice the budget plus five seconds, so the description says that instead. includeRawOutputs had no test at all (dropping it silently loses html bundles on save), so a real-helper case now pins it. Array growth lost its separator under mutation with the suite green; a multiline insert test pins the ,\n layout. Also removes two dead exports, consolidates four copies of inside() into pathUtils, guards the four new helper tests on win32 (they used the Linux venv path), ignores *.tgz/*.bak/*.tmp, drops the duplicate .gitignore entry, and fixes the CI retry path that pointed at a nonexistent fourth log.
isMultiline scanned from each node to the end of the document looking for a newline, so a compact notebook (no newlines at all) made every scalar fallback walk the whole text: 6.8 s for a 256k-key compact object with a 2.0 exponent. The scan is bounded by the node now, which is the same answer: 757 ms and a 1.56 exponent. sanitizeTerminal restarted one character after every unterminated OSC introducer, so 40 MB of ESC ] noise took 4.1 s; it skips the whole examined window instead and costs 104 ms, still linear. formatOutputs serialised a whole JSON dict before applying the 6000-char cap, so 1000 sections of 100k keys took 5.6 s and allocated the string; the structure is bounded first, which makes the same case 7 ms and constant in the section count. The write bench gains a compact-notebook scaling guard (3.9x for 4x input, limit 12x) that fails the previous isMultiline with 12.8x.
… rename Both post-write checks were guarded on finalStat being defined, so a competitor that unlinked the file right after our rename skipped the inode comparison, skipped the read-back, and the call returned success with no file on disk. A missing finalStat now raises a concurrent-replacement error that names the disappearance. The test uses the rename seam to unlink the target between the rename and the stat; removing the check makes the call succeed again and fails the test.
…e vacuity probes architecture.md said the inode comparison makes a concurrent replacement fail, but the check is path based: a competitor that moves the parent after the final recheck and carries the temp across the boundary still gets a success (the documented parent-swap limitation). The paragraph now says what is checked and where it stops. contributing.md promised that each spec ships vacuity probes while none existed, so scripts-vacuity.sh now builds a temporary inverse invariant for all 17 checked states and fails when TLC does not violate it; scripts-verify.sh runs it, and 17/17 are reachable. The MarkdownSafe comment called hint.length + 2*MAX_FENCE the exact hint-survival boundary, but a 45-char hint survives from maxChars = 45; the theorem is a sufficient condition, which the comment now says.
Two ways a write could silently corrupt or lose data. truncateMarkdown sliced UTF-16 units, so a budget that split an astral character returned a lone high surrogate: truncateMarkdown(emoji x50, 65, '') produced a 1-unit invalid string that would be written verbatim. The result is now trimmed to a well-formed boundary, all budgets 1..140 are well formed, and a test pins it. Separately the fallback serializer was never re-checked, so a model carrying undefined returned text with the field dropped and the write succeeded; it now re-parses and compares, and the caller reports 'the notebook cannot be serialized to JSON' naming the offending value kinds. MarkdownSafe records the well-formedness property the code-point model cannot express. The write bench also measured an outputs array where formatOutputs wants a cell (so it measured nothing) and now asserts the truncation marker it renders; its 5 ms ceiling fails the pre-truncation implementation at 14.2 ms.
NotebookAtomicReplace models only the win32 branch of atomic-replace.ts; on POSIX the module returns after the first rename, so the backup and restore states are unreachable. The module now says so instead of reading as a platform-neutral protocol. KernelWarningRing documents why DeliveredBounded alone does not pin the anti-leak clear (a set that never clears also satisfies the bound) and points at the invariant that does. NotebookDefaults notes that JS reorders integer-like keys in a way a List Entry model cannot express, so the byte-order claim for those keys rests on the engine and on the layout test, not on the Lean development.
win32 Bun reports a frozen heapUsed: a retained 20M-element array, a 200 MB string and 2M objects all measure 0 MB while RSS moves by hundreds. The guard therefore passed for every implementation there, including the eager tree it exists to catch. It now detects that platform and prints SKIP, and contributing.md explains that the Linux CI job is where the guard discriminates. Verified: Linux still measures 43.1 MB median, Windows suite 820 tests / 0 fail.
…tch a leak in the guard When the parent directory is swapped and the temp is carried across the boundary, the replace fails against the re-validated directory and the cleanup unlinked the stale path only: the full new notebook content survived as a hidden .tmp inside the worktree and was never collected. Cleanup now tracks wherever the temp actually moved and, because a swap can leave two copies, sweeps the unique temp name beside the original directory and its siblings; a failed sweep is reported instead of swallowed. A regression test swaps the parent mid-write and asserts no temp survives, and disabling the sweep fails it. The allocation guard also measured heapUsed only, which Bun freezes between collections: a run that retained every patched string reported 0 MB and passed. It now also bounds cumulative RSS growth, which fails that leak at 85 MB across five runs.
pyright omits `range` for reports like 'Code is too complex to analyze', and the parser dereferenced item.range.start unguarded. The throw was swallowed by the error handler, so a 12 MB notebook with one complex cell returned skipped=invalid-output and ZERO diagnostics: every real problem in the file disappeared. Those reports are now kept with fileLevel: true and a neutral position instead of dropping the batch, and a fake-pyright test asserts both the file-level report and a normal ranged one survive; disabling the guard fails it.
The notebook write fsynced the temp content but not the directory, so on ext4 with data=writeback a crash could lose the rename and show the old notebook even though the call returned success. It now syncs the parent after the replace and reports a failure to do so. writeFileSafe (used by ipynb_export) had no fsync at all: the export was reported written while still only in the page cache. It now writes through a handle, syncs the content before the rename and syncs the directory after it. A failure in either sync is a warning, not a silent drop.
…ision check stays Both caches were TTL-checked but never pruned, so a long-lived host that probed many pyright paths or interpreters kept one entry per path indefinitely; each is now capped at 32 entries and evicts the oldest. assertRevisionUnchanged is redundant with writeAtomic's own under-lock comparison, but it runs before the permission prompt, so a conflict is refused before the user is asked to approve a write; a comment records that decision and the measured 34 ms cost on a 17 MB notebook, which is not worth removing a TOCTOU narrowing for.
Opening a directory for sync fails on Windows, so the new durability sync added a warning on every notebook write and every export there, which broke the fallback-rewrite warning count and, on a slower disk, the latency budget test. Both paths now skip the directory sync on win32 (the win32 replace protocol is modelled separately) and the latency budget test is documented as Linux-calibrated. Windows suite: 822 tests / 0 fail; Linux 832 / 0 fail.
The one breaking change for existing callers is ipynb_export refusing an output path that is not an export document, so this is a major. The changelog's Unreleased section covered about a third of the 150 commits since 2.0.0; it is now grouped by theme (breaking, correctness, data safety, performance, kernel/helper, tooling and proofs, documentation) and records the measured before/after numbers rather than adjectives. README's install snippet and release note point at 3.0.0 instead of promising that 2.0.0 is still unpublished.
…ssertions The nine real-helper suites resolved `.venv/bin/python`, which exists only in this checkout: macOS failed with ENOENT and the Linux job only passed by luck. They now use the `python` on PATH through describeIf( realHelperEnabled), which is the pattern the integration suites already use, so they run where the dependencies are installed and skip where they are not instead of erroring. Validated with act first, which exposed three more problems the local suite hid. Six permission tests failed because act runs containers as root and chmod-based refusal cannot fail there; they now carry the root guard the suite already uses elsewhere. Two kill tests asserted liveness with signal 0, which still succeeds for an unreaped zombie, so they read /proc and require the process to be running. The cold-runner descendant test gave the whole run a 1 s budget while the kernel alone needs ~1.2 s to start in a container, so the cell never wrote its pid and the test proved nothing; the budget now covers startup and the cell. The write bench's 900 ms ceiling was calibrated on this host (421-585 ms) and failed at 682-799 ms in a container for identical code. It is an absolute gross-regression budget at 2 s now; complexity is pinned by compactPatchRatio, which still fails the previous isMultiline at 12.8x. act: 830 pass / 2 skip / 0 fail, bench green 3/3.
… documents realpath only resolves what exists, and a virtual document can name a notebook that is not on disk yet. The fallback returned the lexical spelling, so when an ancestor was a symlink (macOS: /tmp -> /private/tmp) the root-containment check compared two spellings of one directory and the sidecar fell back outside the session root. Resolve the deepest existing ancestor and keep the missing tail lexical, which restores the mapping under a symlinked session root. Reproduced with a symlinked TMPDIR on Linux: "maps an absolute real notebook path back under a symlinked session root" failed before and passes after, and the full suite is green in both modes (830 pass).
The kernel state is keyed by canonicalPathForKernel (fsp.realpath, which expands Windows 8.3 short names and follows symlinks), but isRunning resolved its lookup with realpathSync, which on bun 1.4.4 preserves the RUNNER~1 spelling, so the lookup missed a live kernel; and list() reported the canonical key, so a symlinked session dir listed paths the caller never typed. isRunning now consults the alias recorded at registration before falling back to a fresh resolution, and list() reports the spelling the caller last used. Reproduced on real Windows with TMP pointed at an 8.3 alias under bun 1.4.4: "counts the timeout per cell, not across the whole batch" failed before and passes after; the kernel list test fails under a symlinked TMPDIR before and passes after.
macOS spells the temp dir through a symlink (/tmp -> /private/tmp) and Windows through 8.3 short names (RUNNER~1), and the implementations resolve paths through realpath, so comparisons of lexical strings against resolved ones failed on runners where the two spellings differ while passing on Linux where they coincide. Assertions now compare the resolved form where the intent is the same physical file, and the rename/rm/readdir spy hooks match on stat identity (ino and dev) so the injected failures fire on every platform. Nine of the macOS failures were reproduced on Linux with a symlinked TMPDIR and are green in both modes; the sidecar and concurrent tests were re-run on real Windows under an 8.3 TMP and pass.
killPidTree(2) reports EPERM on Linux because PID 2 is kthreadd; on macOS no such process exists, both kills report ESRCH, and the tree correctly stays silent, so the test failed with zero failures recorded. The refusal path is now exercised by mocking process.kill, which tests the reporting logic on every platform instead of whichever privileged PIDs the operating system happens to run.
The resolved path was compared as a string against fs.realpathSync's answer, and on Windows the two resolution APIs disagree for the same file (8.3 short names: RUNNER~1 vs the long spelling). Compare what the path denotes (stat identity) instead. The miss-path budget was a wall-clock 1 s pin; a loaded single-process suite run measured 1198 ms for identical code, so it was a runner lottery. It is now a 5 s hang guard, and prompt termination stays structural: three setImmediate-spaced attempts in the helper.
The fake pyright is a python script; where no python is usable the spawn throws and the diagnostics test failed before exercising any behavior. Guard with a probe like the real-helper suites, so the test runs wherever an interpreter exists and skips elsewhere.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #2.
Byte-stable writes, a hardened tool boundary, and measured performance: 150 commits on top of
v2.0.0.Breaking (one)
ipynb_exportrefuses anoutputPaththat does not end in.md,.markdown,.py,.txtor.rst. Previously any path that was not a.ipynbwas written, which let a mistaken prompt overwrite.env,package.jsonor a key file. This is why the release is a major.The issue this branch is named for
Writes no longer reformat a notebook. The schemas validate only;
applyNotebookDefaultsis pure and returns a clone, so the rawJSON.parseobject is what gets written, andsrc/utils/json-patch.tssplices only the changed values into the stored text. Untouched bytes keep key order, layout, escapes, number literals and line endings — verified against 18 fixtures (LF/CRLF, tabs, 1/2/4/12-space indent, inline vs expanded,\uXXXX, duplicate keys, unsorted keys, trailing newline) where only the edited characters change. A fallback to a full rewrite is loud:writeMode/writeModeReasonin the result plus ajson-patchwarning.Correctness and data safety
save=truegives every cell its own share ofmaxOutputChars(later cells were persisted with emptystdoutover real output) and persists raw MIME bundles verbatim..tmp.invalid_unionmessages, andadditionalProperties: falseso a misspelled argument cannot wipe outputs.Performance (measured, with guards)
isMultilineon a 256k-key compact objectsanitizeTerminal, 40 MB ofESC ]noiseformatOutputs, 1000 × 100k-key JSONensureAscii, 10 MBscripts/bench-alloc.tspins per-patch allocation with a fixed workload (42–44 MB against a 60 MB ceiling; the previous tree measured 161–171 MB) andscripts/bench-writes.tsasserts time and RSS budgets for compaction, large outputs, non-ASCII, object-heavy patches and the 17 MB edit. Every guard was verified to fail when its property regresses.Kernel and Python helper
os.write(1, …).shutdownpreempts a running cell.pipis missing, refuses a request naming another notebook, and exits when its parent dies instead of orphaning a helper and kernel.Verification
tscclean forsrcand tests; Lean 16 jobs with nosorry; 8 TLA+ specs plus 17 shipped non-vacuity probes.prepackverifies the packed file set and grepsdistfor current strings.Release
Version is bumped to
3.0.0with a changelog grouped by theme. The release itself is intentionally not cut here; publishing to npm happens from the release workflow after this merges.