Skip to content

Make save raise on failure; let save move file-backed data into the output instead of copying it - #25099

Open
shoumikhin wants to merge 2 commits into
pytorch:mainfrom
shoumikhin:file-backed-consume-on-write
Open

shoumikhin wants to merge 2 commits into
pytorch:mainfrom
shoumikhin:file-backed-consume-on-write

Conversation

@shoumikhin

@shoumikhin shoumikhin commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

1. Make save and save_pte_program raise when a write fails

ExecutorchProgramManager.save and both save_pte_program helpers logged a failed write and returned. Now they raise. Both helpers write the .pte through save. The deprecated ExecutorchProgram has no save, so it is still written with its own write_to_file.

2. Let save move file-backed data into the output instead of copying it

FileBackedData keeps a large blob, such as a delegate's engine, in a file until the program is written. Writing copies it into the .pte or .ptd, so the blob is on disk twice.

This adds a keyword-only consume flag, off by default, to save, write_tensor_data_to_file and both save_pte_program helpers:

save_pte_program(et_program, "model", output_dir, consume=True)

Data that owns its file (as from FileBackedData.move_from) then moves. The output is opened like in a plain save, so an existing file keeps its owner, permissions and links. Everything else is written first, so a disk without room for it fails before any data moves. Each buffer is copied end to start in 64 MiB chunks, and each synced chunk is cut off the source. On file systems with sparse files, the data is on disk once plus one chunk. The first 16 bytes of the output are written last, so a save that stops partway leaves a file that does not load.

Data that can't move safely, for example data on another file system or any data on Windows (where a move saves no space), is copied with a warning.

The moved data is gone from every program that shares it, such as the EdgeProgramManager it came from. If a save fails after data moved, a note on the error says so; unless the output loads, the program must be exported again. A deprecated ExecutorchProgram with consume=True raises TypeError.

For all callers, reading a FileBackedData whose file changed size raises instead of returning short data, saving onto the data's own file raises ValueError instead of emptying it, and copy.deepcopy of a FileBackedData returns the same object.

Test plan

test_cord.py, test_program.py and the Cadence test_utils.py on Linux x86_64. New tests cover a real lowering that moves backend data, several buffers in one output, a full disk, what is on disk at each sync, the failure note, a rerun into an existing output, each copy case, and the Windows and macOS paths (mocked). Each fails when the code it covers is removed.

@shoumikhin shoumikhin added the release notes: exir Changes to any dialects and passes on these dialects, such as memory planning label Nov 14, 2026
Copilot AI balanced review requested due to automatic review settings November 14, 2026 22:41
@pytorch-bot

pytorch-bot Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/25099

Note: Links to docs will display an error until the docs builds have been completed.

⏳ No Failures, 1 Pending

As of commit 9077adc with merge base a4df8b7 (image):
💚 Looks good so far! There are no failures yet. 💚

This comment was automatically generated by Dr. CI and updates every 15 minutes.

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review effort=max

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Nov 14, 2026
@claude

claude Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 28m 14s —— View job


Request changes: the first write to reach a shared FileBackedData consumes it, and save() hides the error this causes. The move can also lose data with several kinds of output, and whenever it fails partway through.

PR Review: #25099

Summary

The PR adds a consume_on_write option to FileBackedData. With it on, the data is moved into a seekable output from the end back to the start, and the source is truncated as it goes.

The main problem is the design: buffer, ETRecord and repeated saves all share this object, and it now has a destructive, single-use mode. The move itself can also lose data:

  • it accepts outputs where writes don't land at the offset it seeks to;
  • it truncates the source before the output has the chunk;
  • a failure can't be retried or recovered.

How this was checked: by reading the code and the CPython stdlib sources. The job wasn't allowed to run Python, so nothing was executed. pytorch/TensorRT#5045 was not reviewed.

Backward Compatibility

  • The mode is set on a shared object, and the first write triggers it (exir/_serialize/_cord.py:33, :95-101).
    • Why the object is shared: the backend sets consume_on_write when it creates the object.
      • NamedDataStore stores the object itself (exir/_serialize/_named_data_store.py:174).
      • LoweredBackendModule.__deepcopy__ passes named_data_store_output by reference (exir/lowered_backend_module.py:122).
      • ExecutorchProgramManager builds _pte_data once (exir/program/_program.py:1939) and reuses it.
    • What breaks: once a backend such as Torch-TensorRT turns the flag on, these user flows break after the first write into a seekable file:
      • et.buffer raises (_program.py:2022 → Cord.__bytes__ → to_bytes()).
      • generate_etrecord(...) with the lowered edge program raises in serde (exir/serde/serialize.py:55-56, :308).
      • A second write_to_file() raises partway through, after the header and earlier segments are already written.
      • save() catches Exception and only logs it (_program.py:2067-2072). Calling et.save(p) twice reopens p with "wb", which truncates the good .pte. The call writes the header, hits the RuntimeError, and returns normally. The result is a corrupt .pte, the engine is gone from both files, and nothing is raised.
    • Ownership is inverted: move_from (_cord.py:51-64) creates the files the program owns, such as the CUDA backend's blobs (backends/cuda/cuda_backend.py:1136, backends/cuda/cuda_weight_collector.py:125). It can't set the flag. Meanwhile, a cleanup=False file that the object doesn't own can be consumed.
    • Fix: this answers the API question in the description. Take the alternative you proposed:
      • put the opt-in on the write (Cord.write_to_file, ExecutorchProgramManager.write_to_file, save);
      • apply it only to buffers that own their file (cleanup=True);
      • say in those docstrings that the program can't be written or read again afterwards;
      • make save() re-raise.
    • Timing: decide this before fix(executorch): move compile_and_save's engines into the program instead of copying them TensorRT#5045 lands, because that PR makes another repo depend on this keyword.
    • Fix this →

Code Quality

  • The output check lets through outputs where writes don't land at the seeked offset (_cord.py:95-99). seekable() plus the mode string doesn't prove the output is a regular file that accepts writes at any offset.
    • O_APPEND descriptor opened with mode "wb" (for example os.fdopen(os.open(p, O_WRONLY | O_CREAT | O_APPEND), "wb"), or sys.stdout.buffer under >> out.pte):

      • FileIO.mode comes from the mode string, so the check passes, but every chunk lands at the end of the file.
      • Blobs over 8 MiB end up with their chunks in reverse order. The total size is right and nothing is raised, but the data is corrupt and the source is gone.
    • gzip.GzipFile (an io.BufferedIOBase): seekable() always returns True.

      • On 3.11/3.12, mode is the int 2, so "a" not in ... raises TypeError. A copy would have worked.
      • On 3.13+, mode is "wb". The first seek pushes size - chunk zeros through the compressor. The tail chunk is written and cut from the source. Then the next seek raises OSError("Negative seek in write mode"), and the tail chunk is lost.
    • io.BytesIO and open(os.devnull, "wb"): both pass (BytesIO has no mode), so writing into memory or doing a dry run destroys the source.

    • Writers that only implement write(): they now fail with AttributeError on seekable().

    • Fix: move only when all of these hold, and copy otherwise:

      • the output is an io.BufferedWriter, io.BufferedRandom or io.FileIO;
      • os.fstat(fileno()) reports a regular file (S_ISREG);
      • on POSIX, fcntl(F_GETFL) has no O_APPEND.

      This also replaces the getattr(outfile, "mode", "") probe (CLAUDE.md: no dynamic getattr patterns). Fix this →

  • The source is truncated before the code knows the chunk reached the output (_cord.py:119-121). The return value of outfile.write(chunk) is not checked, and nothing flushes before source.truncate(begin).
    • Buffered output: io.BufferedWriter holds a write that fits in its buffer. It only reaches the kernel at the next seek(), which runs after the truncate.
      • This always applies to the data's first chunk (size % 8 MiB bytes, written last) when it fits in the buffer.
      • On 3.14+, open() sizes the buffer as max(min(st_blksize, 8 MiB), 128 KiB). On filesystems that report a large st_blksize, full chunks can be held too.
      • If the delayed flush fails, or the process dies in between, those bytes are in neither file. A flush can fail with ENOSPC, EDQUOT or EIO, for example when the output is on another filesystem and the truncate freed nothing there.
    • Unbuffered output (open(p, "wb", buffering=0), a seekable FileIO): a partial write on a full disk returns a short count instead of raising.
      • The source is truncated anyway.
      • The next write succeeds in the space the truncate just freed, so the output silently contains zeros.
    • Fix: before each truncate, check that write() returned len(chunk) and call outfile.flush(). Fix this →
  • A failed move can't be retried or recovered (_cord.py:107-122, with the message at :72).
    • Before any truncation: self._moved = True is set before the first read or write.

      • Any error at this stage leaves the source intact, but this object can never read it again. An example is ENOSPC on the first outfile.write, which is the low-disk case this PR targets.
      • The error message says the data "was moved", which is false.
      • The user can't free space and call save() again.
    • After the first truncation: an exception or Ctrl-C leaves [0, end) in path and [end, size) in an output the caller will delete.

      • Nothing records end.
      • With cleanup=True, the finalizer deletes the part left in path.
      • save() hides the failure (see above).
      • The copy path left the source intact in every one of these cases.
    • Fix:

      • mark the data consumed only right before the first truncate;
      • after a truncate, raise an error that says how many bytes are left in path and where the rest is in the output;
      • document in the class docstring what a failed consuming write leaves behind.

      Fix this →

  • The "consumed" state is stored on the object, not on the file (_cord.py:39, :69-74, :102-103).
    • Trigger: another FileBackedData on the same path, such as a second construction or a copy.copy taken before the move, sees an empty file:
      • to_bytes() and prefix() return b"", and sha256() hashes nothing.
      • Its copy path writes 0 bytes while __len__ still reports the original size. Every later offset in the .pte shifts, silently.
    • Coverage: the length check at :115-118 only guards the move path, and that is all test_cord.py:150-160 tests.
    • Fix: check os.fstat(f.fileno()).st_size == self._size in _open. That covers every object on the path and replaces _moved, which also fixes the early-flag problem above. Fix this →
  • Truncating a file is not the same as deleting it (_cord.py:107). The docstring describes the option as being for "a caller that deletes path", but open(path, "r+b") behaves differently from a delete:
    • Links: it follows symlinks, and truncation affects every hard link to the file. If the engine is a link into a cache, the cached copy is destroyed. os.remove would only drop one name.
    • Permissions: it needs write permission. A read-only source (mode 0444, or a read-only mount) could still be copied, but now the write fails, and inside save() that failure is only logged.
    • Fix: copy instead when os.lstat(path) isn't a regular file with st_nlink == 1, or when the r+b open fails. Limiting the move to files created by move_from, as suggested above, also rules out both cases. Fix this →

Testing

  • The main move test doesn't measure what it claims (test_cord.py:96-118):
    • Disk use: on_disk adds the bytes passed to write() to the source's apparent size. It doesn't count allocated blocks. So the test can't show that the unwritten part stays a hole, and it would pass unchanged on NTFS (see Performance).
    • Write order: chunk = 1000 is smaller than io.BufferedWriter's buffer (8 KiB, or 128 KiB on 3.14+).
      • Every chunk reaches Recording.write at the next seek, after its source range has already been truncated.
      • The + chunk slack in the bound is never used.
      • The test passes without the missing flush, and it would still pass if the code truncated before writing.
    • Fix: measure st_blocks * 512 for both files, and have Recording.write assert that the source still holds the range being written.
  • Missing tests:
    • a writer that fails partway through a move, checking the source, the output and the object afterwards, and a retry;
    • writing the same Cord twice, or calling bytes(cord) after a move;
    • ExecutorchProgramManager.save() followed by .buffer or a second save().
  • Append test: test_cord.py:135-148 doesn't check that the source is still intact after the copy, unlike the pipe test at :133.

Fix this →

Performance

  • No disk saving, plus an extra full-size write, where the output can't be sparse (_cord.py:119-120, docstring :19-22).
    • Why: the first write lands at start + size - chunk. These filesystems allocate the whole gap at once, before any source byte is freed:

      • NTFS, unless the file is marked sparse, which Python never does;
      • FAT/exFAT;
      • HFS+.

      NTFS and exFAT also fill the gap with zeros.

    • Result: peak disk use is twice the data size, the same as a copy. On top of that, size bytes of zeros are written, and the source is still destroyed.

    • Who is affected: Windows is a supported CUDA export target (.ci/scripts/wheel/test_cuda_windows.py), and Torch-TensorRT supports Windows.

    • Fix: copy instead when os.name == "nt", and limit the docstring's "never on disk twice" to filesystems with sparse files. Fix this →

Specific Comments

  • exir/_serialize/_cord.py:17: the summary line "stays on disk until explicitly closed" is no longer true when consume_on_write is on.
  • exir/_serialize/_cord.py:100,105,109: "move" now means two different things in one class. move_from renames the file, while _move_to_file and _moved copy and truncate. The public flag says "consume", so _consume_into and _consumed would avoid the clash.
  • exir/_serialize/test/test_cord.py:94: the written = [0] list used as a counter would read more clearly as a nonlocal variable or an attribute on Recording.

Recommendation

Request Changes

What blocks approval:

  • With the constructor flag, the first write can destroy data that buffer, ETRecord and later saves still need, and save() turns that into a silently corrupt .pte.
  • Moving the opt-in to the write call, as the description already proposes, fixes that.
  • Before the move is safe to turn on for multi-gigabyte engines, it also needs a strict output check, a flush before each truncate, and defined behavior when it fails.

@shoumikhin
shoumikhin force-pushed the file-backed-consume-on-write branch from 9fab878 to fcfc152 Compare November 15, 2026 01:40
@shoumikhin shoumikhin changed the title Move file-backed data into the output file instead of copying it Let a write move file-backed data into the output instead of copying it Nov 15, 2026
Copilot AI balanced review requested due to automatic review settings November 15, 2026 01:40

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review effort=max

@claude

claude Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Review of PR #25099

Request changes: after a consuming save, a second or retried save truncates its output before it notices the data is gone, which destroys the only copy, and a failure partway through a program with several owned buffers leaves no record of where the moved ones went.

PR Review: #25099

Summary

The PR adds an opt-in consume=True to FileBackedData.write_to_file, Cord.write_to_file and ExecutorchProgramManager.write_to_file/write_tensor_data_to_file/save. With it, owned file-backed data is moved into the output instead of copied: chunks go back to front, and the source is truncated behind each one. The PR also makes save re-raise write errors.

The main problems:

  • a second or retried write destroys data;
  • the failure guarantees hold per buffer, not per program;
  • the move has a symlink hole and a signal race;
  • the docstrings don't state what callers are left with, or when the move saves no space.

Python commands aren't permitted in this job, so the tests weren't run. Everything below comes from reading the code.

Code Quality

  • A second or retried write after a consuming one wipes the moved data. Major.
    • save (_program.py:2090) and write_tensor_data_to_file (:2065) open the output with "wb", which truncates it, before any FileBackedData checks its size in _open (_cord.py:76-83).
    • Trigger: et.save("model.pte", consume=True) succeeds, then et.save("model.pte") runs again, for example in a script that saves twice. The second call empties model.pte, writes the leading bytes, and then _open raises. The delegate data is now in neither file.
    • The natural response to a failed consuming save does the same thing. Retrying it to the same path wipes the bytes the note says are "at offset N of the output".
    • Fix: before opening the output, check that every file-backed buffer in the cords being written still holds all its bytes. The second call then raises without touching the file.
    • Fix this →
  • The eligibility check misses symlinks. Major impact, uncommon trigger.
    • os.lstat (_cord.py:117) describes the link, not its target, so a link passes the st_nlink != 1 guard whatever its target's link count.
    • _open("r+b") then follows the link and truncates the target. The object never owned the target; cleanup only ever deletes the link.
    • Trigger: FileBackedData.move_from(path) where path is a symlink, because os.replace moves the link itself. For example, a file in a Hugging Face hub snapshots/ directory links into the shared blobs/ store, and the consuming save empties the shared blob.
    • Fix: also require stat.S_ISREG(source.st_mode). Comparing the opened descriptor's st_dev/st_ino with the lstat result also closes the gap between the check and the open.
    • Fix this →
  • A Ctrl-C during truncate leaves the bookkeeping one chunk behind (_cord.py:148-149).
    • CPython runs pending signal handlers as soon as a call returns. A KeyboardInterrupt that arrives during source.truncate(begin) is therefore raised before end = begin runs.
    • The note then reports [begin, end) as still in the source, but those bytes are only in the output.
    • On the first chunk it is worse. end == self._size, so the handler adds no note and leaves the finalizer alive. The source still holds everything except the last chunk, and it is deleted when the object is collected.
    • Fix: assign end = begin before the truncate. The note is then true whether or not the truncate happened.
    • Fix this →
  • A write error reported late can lose a chunk without a note. Suspected.
    • flush() (_cord.py:147) only hands the chunk to the kernel.
    • NFS, common for home and scratch directories on clusters, and many FUSE filesystems report ENOSPC/EDQUOT late: on a later write, on fsync, or on close(). By then truncate has already dropped the source's copy.
    • If the error comes at close() (the with in save), _consume_into has already returned, so there is no note at all. If it comes on a later chunk, the note lists bytes as being in the output that never got there.
    • A crash between the truncate and writeback has the same effect on a local disk.
    • Fix: call os.fsync(outfile.fileno()) before each truncate, which is one call per 8 MiB chunk. Otherwise, document that the move isn't safe on such filesystems or across crashes.
    • Fix this →
  • Some outputs make the check raise instead of falling back to a copy. Minor.
    • outfile.fileno() (_cord.py:122) raises io.UnsupportedOperation for a BufferedWriter over a raw stream with no descriptor, such as io.BufferedWriter(io.BytesIO()).
    • _open("r+b") (:133) can still fail after os.access has passed.
    • Both errors propagate, although the docstring promises that "any other output … gets a copy".
    • Fix: copy when these raise OSError before anything has been moved. UnsupportedOperation is a subclass of OSError.
    • Fix this →
  • A buffer that appears twice in one cord is moved at its first occurrence. Minor, latent.
    • set(cord.file_backed()) (_program.py:2077) drops repeats within a cord, so they never reach keep. Cord.write_to_file doesn't handle repeats either, so the second occurrence raises in _open after the first one emptied the file.
    • The in-tree serializer doesn't produce repeats today: delegate segments are deduplicated at exir/_serialize/_program.py:298-302, and named data is deduplicated by hash. The comment at _program.py:2072-2073 gives the reason repeats would matter.
    • Fix: drop the set(), and document in Cord.write_to_file that a repeated buffer must be in keep.
    • Fix this →

API Design

  • The failure guarantees hold for one buffer, not for a program (_cord.py:29-31, :234-238, _program.py:2048-2050).
    • Both the note and the promise that the data "can be written again" describe a single FileBackedData.
    • Take a cord with two owned buffers where the first is fully moved. If the second then fails, the error carries at most the second buffer's note, and no note at all if it fails before its own first truncation.
    • Nothing says that the first buffer's bytes now exist only at some offset in the partial output, or that the program can't be written again.
    • Deleting the broken .pte or retrying the save (the first Code Quality finding) then loses those bytes. For the tens-of-gigabytes engines that motivate this PR, that means rebuilding them.
    • Fix: have Cord.write_to_file add a note that lists the buffers already moved and their offsets in the output, state this program-level contract in the ExecutorchProgramManager.write_to_file docstring, and test two owned buffers where the second fails.
    • Fix this →
  • The post-condition at _program.py:2048-2050 claims less, and more firmly, than what happens. Minor.
    • The buffers belong to the lowered modules, not to this manager. et gets them through the edge manager's NamedDataStore (:1864), and LoweredBackendModule.__deepcopy__ shares them (exir/lowered_backend_module.py:122).
    • So after et.save(path, consume=True), the lowered EdgeProgramManager can't be serialized either. A second to_executorch() from it can't be saved, and generate_etrecord given the lowered manager fails in _NamedDataEncoder (exir/serde/serialize.py:56). _data_in_several_files only looks at this manager.
    • In the other direction, nothing is moved on Windows or for any output that _can_consume_into rejects, and the program stays usable. Code that works on one machine can therefore break on another.
    • Fix: document both, and consider logging when the move falls back to a copy.
    • Fix this →

Backward Compatibility

  • save now raises for every caller, not only for callers that pass consume (_program.py:2095).
    • Before this PR, a failed write was logged and swallowed. Raising is the right behavior, but it changes a public API. The PR's title, which is also its release notes: exir entry, only describes the opt-in move.
    • save now always passes consume= to self.write_to_file. An out-of-tree subclass that overrides write_to_file(self, open_file) therefore gets a TypeError from every save().
    • Fix: mention the save change in the title or the release note (Release notes: api, CONTRIBUTING.md:418), or move it to its own PR.

Testing

  • Six of the new tests fail on Windows, and a seventh likely does, yet the Windows unit-test job runs them.
    • pytest-windows.ini:26 collects exir/_serialize/test. The unittest / windows job runs on every PR and is still running on this one.
    • On Windows the move always falls back to a copy, so:
      • test_consume_moves_owned_data_without_a_second_copy fails: there is no st_blocks, and the source isn't emptied.
      • test_only_a_consuming_write_consumes and test_another_buffer_on_a_consumed_file_refuses_to_copy_it fail because no RuntimeError is raised.
      • test_a_consuming_write_that_fails_first_keeps_the_data fails because shutil.copyfileobj ignores the short write.
      • test_a_consuming_write_that_fails_later_says_where_the_bytes_are fails because there is no note, and del data deletes the file.
      • test_consume_copies_data_it_cannot_write_to fails because there is no os.geteuid.
      • The O_APPEND case in test_consume_copies_into_outputs_it_cannot_move_into likely fails too. Without os.O_BINARY, os.open opens the file in text mode, so every \n in the payload is written as \r\n.
    • Fix: skipIf(os.name == "nt") on the tests that need the move, and O_BINARY on Windows.
    • Fix this →
  • The late-failure test can't catch a wrong offset in the note (test_cord.py:245-269).
    • The output starts at offset 0, so start + end == end, and a note that dropped start would still pass.
    • The test also only matches the note's text. It never reads the output at the offset the note gives.
    • Fix: write a prefix first. Then check that the output holds _PAYLOAD[left:] at the offset in the note, and that the source holds _PAYLOAD[:left].
    • Fix this →
  • No program-level test checks that a consuming save actually moves anything (test_program.py:1215-1269).
    • Two of the tests mock Cord.write_to_file on programs that have no file-backed data, so keep=set() is trivially true. The third uses a buffer that has to be copied anyway.
    • If _data_in_several_files returned every buffer, which turns the feature off, all three would still pass.
    • Fix: add a test where _pte_data holds an owned buffer that no .ptd shares, and check that save(consume=True) empties the source and writes a correct .pte. Ideally add a second one that goes through real lowering, since every program test sets _pte_data by hand.
    • Fix this →

Performance

  • Across filesystems, or onto one without sparse files, the move saves no space but still consumes the program (_cord.py:21-26, :112-128).
    • When st_dev differs, each filesystem peaks just as it would with a copy: the source's at the start, the output's at the end. A typical case is engines written to a local /tmp or a tmpfs and the .pte saved to a home or NFS directory.
    • On exFAT, FAT or HFS+, the first write lands at the far end of the output and allocates the whole output, and some of these filesystems also zero-fill it. The peak is then a copy's, plus an extra pass of writes.
    • Only Windows is excluded today.
    • Fix: copy when os.fstat(fd).st_dev != source.st_dev (the fstat call is already there), and qualify "never on disk twice" (_cord.py:22).
    • Fix this →

Specific Comments

  • _cord.py:80-83: the message is wrong when the file grew or was replaced, e.g. "holds 200 of its 100 bytes; … taken the rest". "Expected N bytes, found M" fits every case.
  • _cord.py:157-160: the note doesn't name the output, which matters for write_tensor_data_to_file because it writes several files. "are still in it" would be clearer as "are still in {path}".
  • _program.py:2067-2069: _data_in_several_files() is recomputed for every .ptd. Compute it once before the loop.
  • _program.py:2071: _data_in_several_files reads as "data split across files". _shared_file_backed_data says what it returns.
  • _program.py:2078: (shared if data in seen else seen).add(data) is clever. A plain if/else is simpler.

Recommendation

Request Changes. Four findings can each lose data that only a full re-export brings back, and each has a small fix:

  • the destructive second write (check before opening the output);
  • the symlink hole (reject symlinks);
  • the signal race (set end before truncating);
  • the program-level failure contract (add a note at the cord level).

The Windows test failures will also block CI.

  • Load the /pr-review skill and the PR context (base origin/main, one commit, fcfc152)
  • Three independent reviewers each go through the full diff (_cord.py, _program.py, test_cord.py, test_program.py)
  • Run the tests: not possible here, because Python commands need approval in this job. The findings come from reading the code.
  • Check which points from the previous review were addressed
  • Merge duplicate findings and check each one against the code
  • Post the review

View job run

@shoumikhin
shoumikhin force-pushed the file-backed-consume-on-write branch from fcfc152 to a97f7bf Compare November 15, 2026 04:19
@shoumikhin shoumikhin changed the title Let a write move file-backed data into the output instead of copying it Let a write move file-backed data into the output instead of copying it; make save raise on failure Nov 15, 2026
Copilot AI balanced review requested due to automatic review settings November 15, 2026 04:19

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review effort=max

@claude

claude Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 40m 34s —— View job


PR Review: #25099

  • Load the /pr-review skill and the PR context (base origin/main, one commit, 4 files)
  • Three independent reviewers go through the full diff
  • Merge duplicate findings and check each one against the code (by reading it: running Python, and so the tests, needed approval in this job)
  • Check which points from the earlier reviews were addressed
  • Post the review

Request Changes: a write after a consuming write is only caught after the output has been opened with "wb", so a second write to the same path (a re-run cell, a retry, save_pte_program) erases the only copy of the moved data, and there is still no test that goes through real lowering.

Detailed review

Summary

The PR adds consume=True to FileBackedData, Cord and ExecutorchProgramManager (write_to_file, write_tensor_data_to_file, save). With it, an owned file is moved into the output instead of copied: the file is written from the end back to the start and truncated after each synced chunk, so a large delegate payload is on disk only once.

  • Main problem: write_to_file can't protect an output its caller reopens. A comment says every output is checked before it's opened, which isn't true for this method.
  • Still open from an earlier review: a copy made under consume is silent, and no test goes through real lowering.
  • Smaller problems:
    • A killed process leaves no record of where the moved bytes are.
    • Cord documents a precondition it could enforce.
    • The output check accepts wrappers.
    • There's an fsync per 8 MiB chunk.

Code Quality

  • A killed process leaves no record of where the bytes are (minor), exir/_serialize/_cord.py:189-198.
    • The note on the error is the only record of a move that stopped partway, and it's only added when an exception reaches the except.
    • A SIGTERM (timeout, a cancelled CI job, a scheduler), a SIGKILL or the OOM killer during a long move gives no exception. The first bytes stay in a hidden .executorch_*.data file and the rest are in the output, and nothing records this.
    • Separately, save logs {e} (exir/program/_program.py:2126), and that leaves out __notes__.
    • Fix: log the source path, size and output offset once before the first truncation. In save, use logging.exception or drop the line, since the error is re-raised. Fix this →
  • Cord.write_to_file documents a precondition it could enforce (minor), exir/_serialize/_cord.py:271-272.
    • If a caller leaves a repeated buffer out of keep, the first occurrence is moved and the second raises RuntimeError partway through the write. The partial output is then the only copy.
    • The Cord knows its own buffers. Counting self.file_backed() and copying any buffer that appears twice takes about two lines. _shared_file_backed_data would then only need to handle sharing across files. Fix this →
  • The output check accepts wrappers that don't write where they seek (minor, low confidence), exir/_serialize/_cord.py:136.
    • isinstance accepts any BufferedWriter or BufferedRandom, whatever its raw is.
    • A buffered wrapper over a stream that transforms the data but reports the underlying file's fileno(), such as io.BufferedWriter(gzip.GzipFile(...)), passes every later check. The source is truncated after the first chunk, and then the backward seek raises.
    • A subclass that hashes what it writes receives the chunks from the end back to the start.
    • Fix: for the buffered types, also require isinstance(outfile.raw, io.FileIO). The Recording and FailsThird tests still pass with this. Fix this →

Testing

  • No test goes through real lowering (raised in an earlier review, still open).
    • Every manager-level test in exir/program/test/test_program.py sets et._pte_data/et._tensor_data by hand.
    • So nothing checks that a backend's FileBackedData reaches the .pte/.ptd Cords intact through to_backend → to_executorch (the named data store, AlignedData(Cord(...)), segments), or that the consumed output still deserializes.
    • The only producers in the repo outside tests are in the CUDA backend (backends/cuda/cuda_weight_collector.py:125, backends/cuda/cuda_backend.py:1136), which needs CUDA.
    • A variant of BackendWithNamedDataMap (exir/backend/test/backend_with_named_data_map.py) whose preprocess stores FileBackedData.move_from(...) covers this on CPU, since add_named_data accepts a FileBackedData. The test would save with consume=True, then assert that the backing file is empty and that the deserialized .pte holds the payload. Fix this →
  • exir/_serialize/test/test_cord.py:272-275: the retry after the early failure checks only the output bytes. It still passes if the retry silently copies, for example if the first failure had detached the finalizer. Assert that the retry returns 0 and leaves data._path empty. Fix this →
  • exir/_serialize/test/test_cord.py:138 (low confidence): the peak is 25 blocks of 4 KiB and the bound is about 26. The test would fail on file systems that allocate in bigger units, such as tmpfs on 64 KiB-page kernels. Taking the slack from os.statvfs(directory).f_frsize avoids that.

API Design

  • Reopening a consumed output erases the only copy (major), exir/program/_program.py:2067 and 2088-2090.
    • The comment says every buffer is checked "before its output is opened". That holds for save and write_tensor_data_to_file. It doesn't hold for write_to_file, whose caller has already opened open_file with "wb" before line 2067 runs.
    • Say a notebook cell or a retry loop runs this a second time:
      with open("model.pte", "wb") as f:
          et.write_to_file(f, consume=True)
      It truncates model.pte, which now holds the only copy of the moved payloads, and only then raises.
    • save_pte_program (extension/export_util/utils.py:146-152) does the same when it runs after a consuming save. It also swallows the RuntimeError and returns the path of an empty .pte; the only trace is a log line.
    • 67 files in the repo write programs with open(..., "wb") + write_to_file, so that is the code people will add consume=True to.
    • Fix:
      • Correct the comment.
      • Say in the write_to_file docstring that after a consuming write the output is the only copy and must not be reopened for writing. Point to save, which checks before opening.
      • Have save_pte_program call prog.save(filename) instead of opening the file itself. Fix this →
  • A copy under consume is silent (raised in an earlier review, still open), exir/_serialize/_cord.py:121-125 and exir/program/_program.py:2063-2064.
    • Even when the data and the output are on the same file system, an owned buffer is copied instead of moved when:
      • the file has a second hard link;
      • the output is opened for append;
      • the output is a tempfile.NamedTemporaryFile (its wrapper isn't a BufferedWriter);
      • the file isn't writable;
      • the buffer is shared with another output;
      • the platform is Windows.
    • The data is then on disk twice, which is what consume is meant to avoid. Whether the program can still be written depends on which path each buffer took.
    • write_to_file and save return None either way, so the caller can't tell why the disk filled up or whether a second save is safe.
    • Fix: log a warning with the path and size when an owned buffer is copied under consume, or have the manager methods report whether anything was moved. Fix this →
  • consume can be passed positionally (minor): exir/program/_program.py:2052, 2072 and 2108, and exir/_serialize/_cord.py:116 and 264.
    • et.save(path, True) moves data out of its file, but nothing in the call says so.
    • The flag is new, so making it keyword-only (*, consume: bool = False) breaks no callers. Fix this →

Performance

  • One flush and fsync per 8 MiB chunk (magnitude not measured), exir/_serialize/_cord.py:167-188.
    • A 40 GiB payload means about 5,000 fsync calls, each waiting on the device (and a round trip on NFS or Lustre).
    • Reads and writes also run one after the other, where a copy overlaps them. So the move may be much slower than the copy it replaces.
    • Each truncation needs a sync before it, but there's no need to truncate after every chunk. Writing 256 MiB in 8 MiB pieces and then syncing and truncating once:
      • keeps memory at one chunk;
      • caps the extra disk use at 256 MiB;
      • cuts the number of syncs by a factor of 32.
    • Please benchmark a multi-GiB move against a copy. Fix this →

Specific Comments

  • exir/_serialize/_cord.py:85: check() doesn't say what it checks. A name like check_not_consumed() would read better at its call site, exir/program/_program.py:2093.

  • exir/_serialize/_cord.py:182: the comment says the chunk "has to be on the output's disk". On macOS, os.fsync doesn't flush the drive's write cache (fcntl.F_FULLFSYNC does), so after a power loss the truncation can survive while the chunk doesn't.

  • exir/program/_program.py:2061-2062: the docstring says buffer can't be read after a consuming write. It still can if it was read before, because it's cached at lines 2032-2034.

  • exir/program/_program.py:2096-2097: the comment covers only a buffer shared by the .pte and a .ptd. The loop also catches a buffer repeated within one file, which test_consume_copies_a_buffer_repeated_in_one_file relies on.

  • exir/_serialize/test/test_cord.py:203-207: the seekable() override has no effect.

    • _open_to_consume never calls seekable().
    • On POSIX the pipe already fails the S_ISREG and st_dev checks.
    • On Windows the function returns before it looks at the output.

    The test name and comment describe a check the code doesn't have.

Recommendation

Request Changes

Two things block this PR:

  • write_to_file can erase a consumed .pte, while a comment says that case is handled. The fix is small: the comment, the docstring, and sending save_pte_program through save.
  • There's still no end-to-end test through real lowering.

The silent copy and the sync per chunk are open to discussion. But on a large model they decide whether consume actually keeps the data on disk once.

@shoumikhin
shoumikhin force-pushed the file-backed-consume-on-write branch from a97f7bf to 4c8247d Compare November 15, 2026 06:25
Copilot AI balanced review requested due to automatic review settings November 15, 2026 06:25
@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review effort=max

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@claude

claude Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 37m 13s —— View job


Review of PR #25099

Request Changes: if a consuming save is killed partway through, it leaves a full-length .pte that the runtime loads with zeros where data hadn't been moved yet, and consume still copies silently in cases the caller can't see, now including programs built from a deep copy of a lowered edge manager.

Detailed review

PR Review: #25099

Summary

The PR adds consume=True to FileBackedData.write_to_file and Cord.write_to_file. It moves file-backed data the program owns into the output from back to front, truncating the source after each synced chunk. consume is passed through ExecutorchProgramManager.write_to_file, write_tensor_data_to_file and save, and save and save_pte_program now raise on failure.

Request Changes, for two reasons:

  • A consuming save that is killed leaves path at its full length, and it loads with zeroed data.
  • consume still copies silently in cases the caller can't detect.

Points the previous review raised that are still open are marked (still open). I couldn't run the tests because running Python in this job needs approval, so every finding comes from reading the code.

Code Quality

  • A killed consuming save leaves a .pte that the runtime loads, with zeros for the data not yet moved (major).

    • How it happens. _cord.py:167-188 writes each chunk straight to its final offset, starting with the buffer's last chunk, so the output has its full length after the first write. If the process dies before the move finishes, no handler runs. That covers SIGKILL, SIGTERM, the OOM killer, a CI timeout and a power cut. path keeps its full length, and the unwritten start of the buffer is a hole that reads as zeros. Those bytes now exist only in a hidden .executorch_*.data file that nothing points to.
    • Why the runtime accepts it. serialize_pte_binary adds no padding after the last segment (exir/_serialize/_program.py:480-496). So when the buffer being moved is the last segment, the file passes the runtime's only size check (expected <= actual, runtime/executor/program.cpp:110-119). The flatbuffer is written before the segments, so it verifies too.
    • What the user sees. A zeroed delegate header usually fails when the method loads. Zeroed named data, such as weights, gives wrong outputs with no error.
    • Compared with a copy. A killed copy leaves a short file that the runtime rejects, and the source is intact, so the save can be re-run. A killed move leaves neither.
    • .ptd files. Each .ptd from write_tensor_data_to_file (_program.py:2083-2088) has the same problem. When one fails, the notes don't say which .ptd holds the moved bytes.
    • Fix.
      • With consume, have save and write_tensor_data_to_file write to a temporary file in the destination directory.
      • os.replace it onto the final name only after the write succeeds.
      • Create the file with open(name, "xb") rather than mkstemp, so it gets the usual permissions instead of 0600.
      • On failure, name the temporary file in a note.
      • Before the move starts, log the sources and the temporary file, so a killed run leaves a trail.

    Fix this →

Testing

  • test_program.py:1349-1368. The .ptd branch checks assertIn(payload, f.read()), which passes wherever the payload lands in the file. A move to the wrong offset in a .ptd would not be caught. Also, the 16 KiB payload moves as a single 8 MiB chunk, so this end-to-end test never runs the multi-chunk path. Fix: patch _COPY_CHUNK_SIZE down to a few KiB, save the same program without consume into a second directory first, and compare the .pte and .ptd byte for byte. Fix this →
  • test_cord.py:213-231 (still open). _open_to_consume never calls seekable(), and an anonymous pipe already fails both the S_ISREG check and the st_dev check. So the ReportsSeekable override can't change the outcome, and the test can't fail for the reason its name gives. Fix: move the override to the output of the named-pipe test (test_cord.py:247), where S_ISREG is the only check that rejects it. Fix this →

API Design

  • consume=True still falls back to a copy without telling the caller (still open).

    • Where. _open_to_consume (_cord.py:131-161) returns None on Windows and in these cases:

      • the object doesn't own the data;
      • the output isn't a regular file opened without O_APPEND;
      • the source has another name or is on another file system.

      Nothing above it reports the fallback: Cord.write_to_file, ExecutorchProgramManager.write_to_file and save all return None. A caller who passed consume because the disk can't hold two copies finds out when the disk fills.

    • A trigger the previous review didn't name.

      • EdgeProgramManager and NamedDataStore don't define __deepcopy__, so copy.deepcopy(edge_manager) deep-copies NamedDataStore.buffers.
      • Each copied FileBackedData gets a weakref.finalize that was never registered, so _finalizer.alive is False (_cord.py:133).
      • to_executorch() serializes from that store (_program.py:1871-1876).
      • So with a manager lowered by to_edge_transform_and_lower, calling to_executorch() on a deep copy, as docs/source/etrecord.rst:126-139 does, gives a program where save(consume=True) copies every buffer.
    • Fix. Log a warning once for each buffer that falls back, with the reason. Give FileBackedData a __deepcopy__ that returns self (the data on disk doesn't change, as with bytes), so deep copies keep ownership.

    Fix this →

  • generate_etrecord() fails after a consuming save of a lowered program.

    • Why. generate_etrecord() reads every FileBackedData in the lowered modules of the edge manager it is given (exir/serde/serialize.py:52-55), and LoweredBackendModule.__deepcopy__ keeps the same objects (exir/lowered_backend_module.py:122).
    • Which flows.
      • docs/source/llm/export-custom-llm.md:521-535 deep-copies the lowered manager, calls to_executorch() on the original, then calls generate_etrecord() with the copy. If a consuming save runs before generate_etrecord(), it raises the RuntimeError from _check_size.
      • With the __deepcopy__ fix above, the etrecord.rst flow fails the same way.
      • The generate_etrecord=True flow isn't affected, because it records the programs from before lowering.
    • Fix. The write_to_file docstring (_program.py:2059-2068) should say to generate the ETRecord first.

    Fix this →

  • Repeated buffers (still open).

    • Problem. _cord.py:272-273 requires callers to put every repeated buffer in keep, but Cord.write_to_file could find the repeats in self._buffers itself. A direct caller who forgets to do this hits the following:
      1. The first occurrence is moved.
      2. The second occurrence fails with the RuntimeError from _check_size.
      3. The only copy of the data is left in a half-written output.
    • Why ExecutorchProgramManager is safe. Only because _shared_file_backed_data (_program.py:2099-2110) also catches repeats within one file, which its comment doesn't mention.

    Fix this →

Performance

  • One sync per 8 MiB chunk (still open). _cord.py:183-184 syncs the output after every _COPY_CHUNK_SIZE chunk. Moving a 4 GiB payload therefore waits on 512 device flushes in a row, and each one can take tens of milliseconds on network or cloud disks. I haven't measured this. Fix: give the move its own, larger chunk size, such as 64–256 MiB. That costs that much extra disk and a pread buffer of the same size. Then time a multi-GB move against the copy path. Fix this →

Specific Comments

  • exir/program/_program.py:2061-2062 (still open): the docstring says the data can't be "read through buffer again", but that's wrong if buffer was read before the consuming write. It is cached at _program.py:2032-2033 and keeps returning those bytes.
  • exir/program/_program.py:2129-2131 (still open): the except now only logs and re-raises. The log uses str(e), which drops the notes that say where the moved bytes are, and the error is reported twice. Drop the try/except.
  • exir/_serialize/_cord.py:257: file_backed() reads like a predicate; file_backed_buffers() would say what it returns.

Fix this → (all three)

Recommendation

Request Changes. The killed-save problem under Code Quality blocks approval. Because the move writes in place, an interrupted consuming save becomes a .pte that loads with zeroed data, and the source has already given up those bytes. The silent fallback under API Design should be fixed in the same pass, or callers can't rely on consume to save disk space. Everything else is minor.

Review steps
  • Load the /pr-review skill
  • Read the diff against origin/main
  • Run the three independent reviewers
  • Try to run the tests. I couldn't: running Python here needs approval, so every finding comes from reading the code.
  • Merge duplicate findings
  • Check each finding against the code
  • Check which points from the earlier reviews were addressed
  • Post the review

shoumikhin added a commit to shoumikhin/TensorRT that referenced this pull request Nov 15, 2026
…tead of copying them

`compile_and_save` writes each engine to a temporary file as soon as it is built. The ExecuTorch
save then copies that file into the `.pte` (or the `.ptd`), and the file is deleted only when the
call returns. So while the program is written, every engine is on disk twice. For a model whose
engine is tens of gigabytes, the copy needs that much more free disk, and an export can fail on a
device that has room for the result.

The backend now hands each of these engine files to ExecuTorch as data that owns the file
(`FileBackedData(path, cleanup=True)`); it is deleted after the save anyway. Inside
`compile_and_save`, the save then writes the program and the `.ptd` with `consume=True`, so
ExecuTorch moves each engine into the program: it copies it back to front and truncates the file as
it goes, and each engine is on disk once. ExecuTorch does this only when the temporary directory,
where the engine files are, is on the same file system as the program; otherwise it copies.

With `generate_etrecord`, the save copies the engines instead. The ETRecord reads the engines after
the program is written, so the save order stays the same as before, and the program is kept when
the ETRecord can't be written.

Every ExecuTorch save now passes `consume` (as `False` outside `compile_and_save`), so this needs
the `consume` argument from pytorch/executorch#25099. It lands after that change, together with an
ExecuTorch pin that has it, which also raises the minimum ExecuTorch version.

Test plan:

- `tests/py/dynamo/executorch/test_api.py`, CPU, with the lowering stubbed:
  - New `test_compile_and_save_moves_the_engines`: inside `compile_and_save`'s offload block, the
    program and the `.ptd` are written with `consume=True`. It fails without this change.
  - New `test_compile_and_save_keeps_the_program_when_the_etrecord_fails`: in the same block with
    an ETRecord, the program and the `.ptd` are written first, without `consume`, and the `.pte`
    is kept when the ETRecord save raises.
  - New `test_save_executorch_keeps_the_program_when_the_etrecord_fails`: the same for a plain
    save.
  - New `test_save_executorch_does_not_consume`: a plain save writes without `consume`.
- `tests/py/dynamo/executorch/test_compile_and_save.py` on an A100:
  - The streaming test now also checks that each engine reaches ExecuTorch as data that owns its
    file.
  - New `test_engines_move_into_the_program_without_a_second_copy` checks that each engine file
    is empty after the program is written.
  - New `test_an_etrecord_makes_the_save_copy_the_engines`: with an ETRecord, the engine files
    keep their bytes, and both the `.pte` and the ETRecord are written.
Copilot AI balanced review requested due to automatic review settings November 20, 2026 01:12
@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 4m 53s —— View job


Needs Discussion: I found no data-loss bug in the move at 905c4bc+2 (HEAD), but the save docstring's ETRecord advice is wrong (generating first isn't enough, it has to be saved first), a consuming save replaces the output's inode where a plain save writes into it, and the per-chunk sync cost is still undocumented; everything else is minor.

PR Review: #25099

Summary

The PR makes save and both save_pte_program helpers raise on failure. It also adds a keyword-only consume (default False) that moves owned FileBackedData into a .partial file from the end back to the start and then hard-links it onto path. The remaining problems are in the documented contract and in output-file handling, not in the move bookkeeping. I didn't run the tests (running Python needs approval in this job), so every finding comes from reading the code.

API Design

  • "Generate any ETRecord first" doesn't prevent the failure (exir/program/_program.py, save docstring).

    • ETRecord reads file-backed data when it is saved, not when it is generated: _NamedDataEncoder calls obj.to_bytes() (exir/serde/serialize.py:55-56).
    • With the new FileBackedData.__deepcopy__ returning self (exir/_serialize/_cord.py:73-76), the ETRecord's deep copy of the edge programs holds the same objects that save(consume=True) empties.
    • Trigger: to_edge_transform_and_lower(..., generate_etrecord=True) → to_executorch() → et.save(p, consume=True) → et.get_etrecord().save(...). The user did what the docstring says, and the ETRecord save raises the _check_size RuntimeError.
    • The same holds for anything else that shares the buffers: the lowered EdgeProgramManager, a second to_executorch() from it, or copy.deepcopy(et). _move_into counts uses only inside this manager, so the docstring's "the program can't be saved again" understates what breaks.
    • Fix: say "save any ETRecord first", and say that every program sharing this program's lowered modules can't be serialized afterwards.

    Fix this →

  • The PR description reads as if consume defaults to True ("This adds a keyword-only consume=True to save, …"). All four signatures default to False. All three reviewers read it that way. The description is also the release note, so it should say "a keyword-only consume flag (off by default)".

Backward Compatibility

  • save_pte_program breaks legacy ExecutorchProgram when it doesn't have to (extension/export_util/utils.py, backends/cadence/aot/utils.py:299).
    • ExecutorchProgram has both write_to_file and write_tensor_data_to_file (exir/program/_program.py:625, :633), so the old helper worked fully for it. It now gets an AttributeError from prog.save.
    • Making the helper raise only needed removing the try/except. I found no in-repo caller passing the legacy type, but the type hint on the extension helper has accepted it, so out-of-tree callers may.
    • Fix: keep open(..., "wb") + prog.write_to_file(f) when consume is false, or label the PR as a BC break.

Code Quality

  • A consuming save replaces the output file instead of writing into it (exir/program/_program.py, _write_moving: os.remove(path) then os.link(temp, path)).
    • A plain save opens path with "wb", so it keeps the inode: the mode, owner, group, ACLs and every other hard link. A consuming save drops all of them. The new file's mode comes from the umask, and another hard link to the old model.pte (for example in a deploy directory) silently keeps the old model.
    • _move_into already falls back to a plain save for links and non-regular files (S_ISREG(os.lstat(path))). It doesn't for a regular file with st_nlink > 1, and the warning doesn't mention this case.
    • Fix: treat st_nlink > 1 at path like a link (copy), and document that a consuming save creates a new file.
  • The old output is removed before anything is written (_write_moving, os.remove(path) before cord._write_to_file). If writing the non-moved parts hits ENOSPC, the temporary file is cleaned up and path is gone. A plain "wb" save loses it too, so this isn't a regression, but it undercuts "a full disk shows up before any source changes". Removing path right before the first _move_to would keep the disk saving and the old output on an early failure.
  • The "no overwrite" guarantee falls back to overwriting (_write_moving, except OSError: os.replace(temp, path)). Any os.link error other than FileExistsError (FAT/exFAT, some SMB/FUSE mounts) goes through os.replace, which silently replaces a file created at path during the move. The comment and the PR description promise more than the code does. Either say so or, on that path, check os.path.lexists(path) right before os.replace.
  • A cached sha256() survives a move (exir/_serialize/_cord.py, sha256). It returns self._sha256 without _check_size, while every other reader now raises. The CUDA weight collector passes sha256= to move_from, so after a consuming save a NamedDataStore dedupe can match against data that no longer exists. Check the size before returning the cached value.
  • The same-file guard covers only the cord being written (save passes [self._pte_data], write_tensor_data_to_file passes only the tensor-data cords). If path is the file behind a .ptd buffer, save truncates or removes it, and the next write_tensor_data_to_file raises with the data gone. Pass all of _pte_data and _tensor_data in both places. test_writing_over_the_data_file_raises uses the same object in both cords, so it can't catch this.
  • save_bpte_program still swallows write errors (backends/cadence/aot/utils.py:311-316). It sits next to the helper this PR fixes, and its message names output_dir instead of filename.

Fix this →

Testing

  • exir/_serialize/test/test_cord.py, test_a_full_disk_before_the_move_changes_nothing: with space = 8 + 255, the failure happens on the first chunk inside _move_to, after _finalizer.detach(), so it actually tests the finalizer restore, not "before the move". Nothing covers a real ENOSPC while writing the non-moved data; the other ordering test mocks write_to_file.
  • No test checks that an existing output at path survives a consuming save that fails early, or what happens to another hard link at path.

Performance

  • One flush and sync per 8 MiB chunk (_cord.py, _move_to; still open from earlier reviews). A 20 GB engine means about 2,500 syncs, each F_FULLFSYNC on macOS. The docstring says only that "the sync per chunk makes the save slower". The guarantee needs a sync before each truncate, not after each 8 MiB read, so syncing and truncating every 256 MiB would keep the bound (plus 256 MiB) with ~32× fewer syncs. Please benchmark a multi-GB move against a copy.

Recommendation

Needs Discussion. Nothing blocks on correctness of the move itself. Fix the ETRecord docstring before merge, since it tells users to do something that still fails. Decide whether replacing the output's inode (and dropping its other hard links) is acceptable for consume. Decide whether save_pte_program should keep working for legacy ExecutorchProgram.

  • Load the /pr-review skill and the PR context
  • Read the diff (HEAD~2..HEAD, 7 files, +668/−38)
  • Run three independent reviewers (all 7 files covered)
  • Merge duplicate findings and check each one against the code
  • Run the tests: not done, because running Python needs approval in this job

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review effort=max

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 53m 28s —— View job


Request Changes: a consuming save that fails after some data has moved leaves a program that can't be saved again and data that can't be fully recovered, and nothing stops a move across file systems (the CUDA backend's default wherever /tmp is tmpfs), where it saves no space but makes that failure reachable.

PR Review: #25099

Summary

This PR makes save and both save_pte_program helpers raise when a write fails, and adds a consume option to save, write_tensor_data_to_file and the helpers, which moves data the program owns into the output from its end back to its start instead of copying it. The first two Code Quality points block approval. I didn't run the tests, because running Python needs approval in this job.

Code Quality

  • Blocker: a consuming save that fails after data moved can't be retried or recovered (partly still open). exir/program/_program.py:1967-1974, exir/_serialize/_cord.py:160-170

    • Every later save or write_tensor_data_to_file raises RuntimeError at _check_file_backed_data (_program.py:1916), so the only way forward is a re-export. Re-running save_pte_program after its .ptd write fails raises the same way, because the .pte already moved its data.
    • The .partial has holes where the buffers that hadn't moved yet go. Their files keep live finalizers, so they're deleted when the program is collected or at exit, and no note names them: only the split buffer gets a byte range (_cord.py:166-169), and the note at _program.py:1973 says only that the .partial "holds the only copy of the data moved so far".
    • The .partial and the split buffer's head, a hidden .executorch_*.data file whose finalizer stays detached, are left on disk.
    • Triggers: Ctrl-C or EIO during the move, or a full output disk when the move crosses file systems (next point).
    • Fix: on failure, move the data back with the same end-to-start protocol, source and output swapped, starting from the last buffer that moved, so the program is intact and the save can be retried. At a minimum, detach the finalizer of every buffer in move, name each buffer's file and output offset in the note, and say in the docstring that a failed consuming save needs a re-export.

    Fix this →

  • Blocker: nothing stops a move across file systems, where it saves no space (still open). exir/program/_program.py:2213

    • FileBackedData.move_from keeps the file in the directory it came from (_cord.py:58-68), so the CUDA backend's weights stay next to the AOTI output (backends/cuda/cuda_backend.py:1371-1375, backends/cuda/cuda_weight_collector.py:181-188), in the inductor cache, which defaults to /tmp/torchinductor_$USER.
    • Where /tmp is tmpfs (Fedora, Arch, Debian 13), or the output goes to another mount such as a container volume, the move saves nothing on the output's file system but still empties the program. "A full disk shows before any data moves" (_cord.py:242-243) then no longer holds: a full output disk fails partway through the move, which is the case above.
    • File systems without sparse files gain nothing either. That includes every save on Windows: NTFS makes a file sparse only when its sparse flag is set, and this code never sets it.
    • Fix: copy when os.stat(data.path).st_dev differs from the st_dev of the output's directory, and either skip the move on Windows or say in the docstring that NTFS doesn't count.

    Fix this →

  • _move_into doesn't check _can_move() (still open). exir/program/_program.py:2213. When every owned buffer is hard-linked or read-only, move is non-empty, so the save still goes through the temp file and unlinks the old output (see API Design), and _move_into returns True, contradicting "Return False, having written nothing, if no data can move" (:2203-2204). Fix: add data._can_move() to the filter.

    Fix this →

  • save_bpte_program still swallows write errors (still open), in the file whose save_pte_program this PR made raise (backends/cadence/aot/utils.py:311-316), and it logs output_dir rather than the file it failed to write. The nxp save_pte_program does the same (backends/nxp/tests/utils.py:38-43).

    Fix this →

Testing

  • Nothing tests the crash-safety ordering. Deleting the _sync before the truncate (exir/_serialize/_cord.py:157), either _sync_directory call (exir/program/_program.py:1954, :1975), or the _sync before the link (:1959) fails no test. No program-level test fails a save after one buffer moved and before the next, the case in the first Code Quality point. Fix: patch _sync and os.remove with side effects that record the order and the source file's size, and add a two-buffer program test that fails between the buffers.

    Fix this →

API Design

  • "The program can't be saved again" understates what a consuming save breaks (still open). exir/program/_program.py:2183-2184. The move empties the data for everything that shares it: the EdgeProgramManager the program was lowered from and its deep copies (FileBackedData.__deepcopy__ returns self), other to_executorch() results, buffer unless it was already read (:2131-2132), and serde serialize() of the lowered program (exir/serde/serialize.py:55-56). with open(path, "wb") as f: et.write_to_file(f) over the consumed output truncates the only copy of the moved data before it raises. Fix: document all of this on consume and on write_to_file (:2150-2156).

    Fix this →

  • A consuming save replaces the output instead of writing into it (still open). exir/program/_program.py:1949-1956. Unlike a plain save:

    • the new file's mode comes from the umask, and the old owner, ACLs and xattrs are lost;
    • other hard links to the old output keep the old content;
    • on POSIX, a read-only output is replaced without a word, where a plain save raises;
    • a writable output in a directory the user can't write fails at open(temp, "xb") (:1950) instead of being copied, contradicting "Data that can't move is copied".

    The comment "as a plain save does" (:2215) holds only for links and devices. Fix: in _move_into, also copy when the existing output has st_nlink > 1 or isn't writable, or its directory isn't writable, and copy the old mode onto the temp file before linking it.

    Fix this →

Thread Safety

  • The os.replace fallback can overwrite another save's output (still open). exir/program/_program.py:1965-1966. Any OSError from os.link other than FileExistsError falls through to os.replace. On file systems without hard links (FAT, exFAT), the consuming save that finishes second replaces the first one's output, which holds the only copy of that save's moved data; an unrelated error such as EIO takes the same path. Fix: fall back only for the errnos that mean "no hard links" (EPERM, EOPNOTSUPP), and say in the comment at :1961 that the guarantee needs them.

    Fix this →

Performance

  • A consuming save syncs once per 8 MiB chunk, and at least once per buffer (still open). exir/_serialize/_cord.py:33, :157. The CUDA backend makes one buffer per weight storage (backends/cuda/cuda_weight_collector.py:181-188), so a 16 GB model takes about 2,000 syncs, where a plain save takes none. Fix: give _move_to its own, larger chunk size (for example 256 MiB, which still bounds the extra space), and mention the cost in the docstring.

    Fix this →

Specific Comments

  • exir/program/_program.py:2183-2184 - "generate any ETRecord first" should be "save any ETRecord built from the lowered program first". This corrects the previous review: generate_etrecord=True isn't affected, since it copies the edge program before lowering (:1286, :1416) and add_executorch_program keeps no file-backed data, and generate_etrecord() saves as it generates (devtools/etrecord/_etrecord.py:759). Line 2183 is also longer than the lines around it.
  • exir/program/_program.py:2188-2191 - Raises omits the FileExistsError from :1963-1964.
  • exir/program/_program.py:2220-2225 - the warning lists every condition, not the one each copied buffer failed.
  • exir/program/_program.py:2202 - consume is passed only so _move_into can return early; the two callers could test it.
  • exir/_serialize/_cord.py:238-263 - _write_to_file differs from write_to_file only by the underscore, though it moves data, needs a regular file and returns a count; a name like _write_and_move would say so. skip (:252, :259) means "moves".
  • exir/_serialize/_cord.py:74-75, exir/program/test/test_program.py:1338 - the ETRecord rationale doesn't match the code: what needs __deepcopy__ to return self is to_executorch() on a deep copy of a lowered EdgeProgramManager, whose _named_data_store gets deep-copied because the class has no __deepcopy__.

Fix this →

Recommendation

Request Changes

The partial-failure state is the blocker. The missing st_dev check is what makes it reachable with the CUDA backend's defaults, and it's the cheaper fix.

shoumikhin added a commit to shoumikhin/TensorRT that referenced this pull request Nov 20, 2026
…tead of copying them

`compile_and_save` writes each engine to a temporary file as soon as it is built. The ExecuTorch
save then copies that file into the `.pte` (or the `.ptd`), and the file is deleted only when the
call returns. So while the program is written, every engine is on disk twice. For a model whose
engine is tens of gigabytes, the copy needs that much more free disk, and an export can fail on a
device that has room for the result.

The backend now hands each of these engine files to ExecuTorch as data that owns the file
(`FileBackedData(path, cleanup=True)`); it is deleted after the save anyway. Inside
`compile_and_save`, when the outputs would not fit in the free space of their file system (with a
tenth to spare, and an output already there counted as free, since both a copy and a move replace
it), the program is then written with ExecuTorch's `save(file_path, consume=True)` and
the `.ptd` with `write_tensor_data_to_file(..., consume=True)`, so ExecuTorch moves each engine into
the program: it copies it back to front and truncates the file as it goes, so the engines are on
disk once (plus one chunk) instead of twice, on a file system with sparse files. ExecuTorch moves
other data that owns its file the same way, such as the CUDA backend's weights, and copies data it
can't move, with a warning. Its `save` takes only a `.pte` path, so a program saved under another
name is written as before, with a copy; the `.ptd` still moves.

ExecuTorch is an optional extra, and releases before pytorch/executorch#25099, such as 1.6.0, have
no `consume` argument. Both writes check whether ExecuTorch's method takes it, through one small
helper, and copy as before when it doesn't. That fallback writes the program through `open` and
`write_to_file`, as before this change, so a failed write still raises.

The move is slower than a copy, because ExecuTorch syncs each chunk to disk before the engine file
gives it up. Measured on btrfs, engines of 0.5, 2 and 8 GiB took 1.3, 8 and 37 seconds to move and
0.5, 1.9 and 6.7 seconds to copy. So `compile_and_save` moves only when a copy would not fit, where
the save failed before, and otherwise copies exactly as before. The docstring says so.

If a move fails after some data left its engine file, ExecuTorch keeps its partial output,
`<name>.<random>.partial`, which holds that data. The engine files are temporary and are deleted
when `compile_and_save` returns, so that output can never be finished, and it can be as large as the
engines on a disk that just ran out. So the consuming writes now run inside `moving_engines_into`:
when the save fails, it deletes each partial output this save left, and a note on the error says to
export again. A partial output that was there before the save is never touched. ExecuTorch can also
leave other data it moved in part, such as a file of CUDA weights whose rest is in the partial
output; that file is deleted too, since nothing can finish it either. Afterwards it empties the plan
of each engine the save moved, in part or in full: that plan maps an emptied file, so a later read
of it through its module, such as a second save in the block, killed the process with a bus error.
Now the plan is empty and that read raises. An engine file the cleanup can't delete is logged as a
warning, so it can't hide the error that ended the block, and a save that succeeded doesn't fail
over it. The program path goes through `os.fspath` first, so a `pathlib.Path` still works.

With `generate_etrecord`, the save copies the engines instead. The ETRecord is written after the
program and reads the engines, so a move would leave it nothing to read. The program is still
written first, as before. The docs now say why `compile_and_save` can write an ETRecord when a
plain save of a program with TensorRT engines can't: it keeps each engine as a byte buffer read
from its file. The record then holds copies of every engine, and writing it reads them into
memory, which the docs also say: for a 4 GiB engine the record took 8 GiB, and the save 3 GiB more
host memory.

The move needs the `consume` argument of `save` and `write_tensor_data_to_file` from
pytorch/executorch#25099; with an ExecuTorch without it, `compile_and_save` copies as before. Only
the move passes `consume`, so every other save calls ExecuTorch exactly as before.

Test plan:

- `tests/py/dynamo/executorch/test_api.py`, CPU, with the lowering stubbed:
  - New `test_save_in_the_offload_block_moves_the_engines_when_a_copy_does_not_fit`: inside
    `compile_and_save`'s offload block, the program and the `.ptd` are written with
    `consume=True` when the disk has no room for a copy, and without it when it has, counting an
    old output it replaces as free. The path is a `pathlib.Path`.
  - New `test_save_in_the_offload_block_moves_only_the_ptd_into_a_path_without_pte`: the same
    block with a `.bin` path writes the program without `consume` and the `.ptd` with it.
  - New `test_save_in_the_offload_block_copies_with_an_executorch_without_consume`: with an
    ExecuTorch whose writes take no `consume`, the program goes through `write_to_file` and the
    `.ptd` is written without `consume`.
  - New `test_a_failed_move_in_the_offload_block_deletes_its_partial_output`: a consuming `.pte`
    or `.ptd` write that stops inside an engine leaves no partial file, and the error says to
    export again.
  - New `test_a_failed_move_deletes_what_it_moved_in_part`: a failed save deletes the partial output
    it left and a data file it moved in part, and says to export again; an untouched data file and a
    partial output from before the save are kept; the engine files are deleted in every case.
  - New `test_a_save_empties_the_plans_of_the_engines_it_moved`: after a save, a moved engine's
    plan is empty and no longer found as an engine file, the other one is untouched, and a second
    save passes over the moved one.
  - New tests for engine files the cleanup can't check or delete: a warning, not an error.
  - New `test_save_in_the_offload_block_keeps_the_program_when_the_etrecord_fails` and
    `test_save_executorch_does_not_consume`.
- `tests/py/dynamo/executorch/test_compile_and_save.py` on an A100 with TensorRT 11.4, with
  ExecuTorch 1.6 and with ExecuTorch from pytorch/executorch#25099:
  - The streaming test also checks that each engine reaches ExecuTorch as data that owns its file.
  - New `test_engines_move_into_the_program_without_a_second_copy`, new
    `test_an_etrecord_makes_the_save_copy_the_engines`, and new
    `test_a_failed_move_leaves_no_partial_output` (the disk fills after the first engine moved;
    no partial file is left). They make the disk
    look full, so the save moves, and they need an ExecuTorch that moves data. The skip checks
    for `Cord.file_backed_buffers` as well as `consume`, so an ExecuTorch that renames `consume`
    fails them instead of skipping them.

Signed-off-by: Anthony Shoumikhin <[email protected]>
@shoumikhin
shoumikhin force-pushed the file-backed-consume-on-write branch from e689a97 to 9fca900 Compare November 21, 2026 07:30
Copilot AI balanced review requested due to automatic review settings November 21, 2026 07:30

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review effort=max

@claude

claude Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 47m 29s —— View job


Request Changes: on Windows, save(consume=True) empties the program's data without saving disk space, and a save that fails after its output is complete reports that output as partial and says to export again. Both are small fixes; the other findings are minor.

PR Review: #25099

Summary

The PR makes save, save_pte_program and the Cadence save_pte_program raise when a write fails. It also adds consume=True, which moves owned FileBackedData into the output, working from the end back and syncing each chunk before cutting it off the source.

  • Two problems block approval. On Windows (NTFS) a consuming save gives up the program's data and saves no space. A failure after the output is complete is reported as partial.
  • The rest are minor: fallbacks that raise instead of copying, docs that overstate guarantees, and gaps in the tests.

I could not run the tests, because running Python needs approval in this job, so everything below comes from reading the code at 9fca900. All 7 changed files were covered. "(n/3)" says how many of the three independent reviewers reported a finding. "Still open" marks a point an earlier review raised that this head doesn't address.

Code Quality

  • [major] Windows: the move empties the data and saves no space (3/3, partly still open). exir/program/_program.py:2236-2266, exir/_serialize/_cord.py:138-171

    • Why no space is saved: the move writes each buffer's last chunk first, at the far end of the output. NTFS only leaves gaps unallocated in files marked sparse (FSCTL_SET_SPARSE), which nothing here does, so that first write allocates and zero-fills the whole gap. FAT/exFAT and HFS+ do the same.
    • The cost: the peak is output plus source, about 2N, the same as a copy. It adds N bytes of zero writes and a sync per chunk. The source is still consumed, so neither this program nor the programs sharing its data can be saved again.
    • The docs: save (2208-2209) says "On file systems with sparse files", and a Windows user will count NTFS as one. _move_to (139-141) promises "on disk once plus one chunk" without that condition.
    • Context: _sync_directory already special-cases win32, and Windows CI collects both test directories (pytest-windows.ini:26,32).
    • Fix: copy on win32 and qualify both docstrings. Optionally, extend the output with truncate and compare st_blocks before the first chunk moves, to detect file systems without sparse files elsewhere. Fix this →
  • [major] A complete output is reported as partial, and the docs say to export again (3/3). exir/program/_program.py:1987-2002

    • What happens: once _sync(output.fileno()) (1986) returns, the temp file is complete and synced. Any later failure still gets the note "<where> holds the only copy of the data moved so far", and the save docstring (2217-2219) says the program "has to be exported again". Later failures include:
      • os.link failing with an errno outside _NO_HARD_LINKS, for example ENOSPC/EDQUOT for the new directory entry on the nearly full disk this feature targets, or ENOSYS on some FUSE mounts;
      • the final _sync_directory failing;
      • a Ctrl-C after the link.
    • The test expects it: test_a_note_names_the_output_once_it_is_in_place (test_program.py:1412-1426) expects exactly that note for a path it checks is complete.
    • Why it matters: for a large model, the user may delete a complete file named *.partial and spend hours exporting again.
    • Fix: track completion and word the note to match, for example "<temp> is complete; rename it to <path>". Fix this →
  • _can_replace accepts outputs that a consuming save then fails on (3/3, partly still open). exir/program/_program.py:1946-1960, 1976-1983

    • These fail before any data moves, so the save raises where a plain save succeeds. That contradicts the docstring's "Data that can't move … is copied, with a warning". The cases:
      • another user's writable file in a sticky directory: os.remove gives EPERM;
      • a bind-mounted output, common in containers: EBUSY;
      • a writable but unreadable directory: _sync_directory's os.open gives EACCES;
      • a file name within 17 characters of NAME_MAX: open(temp, "xb") fails.
    • Nothing is lost, because nothing has moved yet.
    • Replacing the file also drops the old file's owner, ACLs and xattrs, which a plain save keeps.
    • Fix: if _write_moving raises while all data is still intact, fall back to the plain write. Fix this →
  • A cached sha256() keeps answering after a move (3/3, still open). exir/_serialize/_cord.py:110-117

    • This contradicts the class docstring ("after which reading it raises").
    • Both CUDA producers always cache the digest (backends/cuda/cuda_weight_collector.py:188, backends/cuda/cuda_backend.py:1362-1363). NamedDataStore deduplicates by that digest (exir/_serialize/_named_data_store.py:99-102), so consumed data gets past dedup and only fails later, at write time.
    • Fix: check the size before returning the cached digest. Fix this →
  • _move_to doesn't enforce its precondition (1/3). exir/_serialize/_cord.py:145-164

    • The bug: called on a FileBackedData that never owned its file (_finalizer is None), self._finalizer.detach() raises AttributeError inside the try. The handler then registers a finalizer (164), so the object later deletes a file it never owned. Only the private API can reach this.
    • The test it hides: test_a_deep_copy_can_move_the_data (test_cord.py:151-154) passes even without __deepcopy__, because it calls _write_and_move directly and a deep-copied weakref.finalize is dead (detach() returns None).
    • Fix: raise unless _can_move(), and assert _can_move() on the copy in the test. Fix this →
  • The "Copied N of M" warning is logged before the copy happens (3/3, partly still open). exir/program/_program.py:2258-2265

    • With a read-only output, the user sees "Copied 1 of 1 …" and then a PermissionError (test_consume_does_not_replace_a_read_only_output).
    • The warning lists every condition rather than the one each buffer failed, so the user can't tell what to change. Fix this →
  • A failed or killed move leaves files that nothing removes or documents (2/3, partly still open). exir/program/_program.py:2214-2219, exir/_serialize/_cord.py:147

    • It leaves <path>.<hex>.partial, plus the head of each moved buffer in its hidden .executorch_*.data file. The finalizer is detached, so nothing removes them.
    • After a SIGKILL, an OOM kill or a power loss, no note or log names them.
    • On the nearly full disk that motivates consume, exporting again needs that space back. Fix this →
  • The file-system transaction code lives in _program.py (3/3). exir/program/_program.py:1928-2004

    • These ~80 lines (_sync_directory, _can_replace, _intact, _write_moving and the errno tuples) import the private _cord._sync and call the private Cord._write_and_move and FileBackedData._can_move.
    • Moving them next to Cord keeps those privates inside their module and leaves _program.py to decide what moves. Fix this →
  • save_bpte_program still swallows errors (1/3, still open). backends/cadence/aot/utils.py:320-325

    • It sits right below the save_pte_program this PR makes raise, but still logs and swallows the error.
    • It also logs output_dir instead of filename. Fix this →
  • The same-file guard checks only the cord being written (2/3, still open, contrived). exir/program/_program.py:2194, 2230

    • For example, if a .pte buffer wraps an existing outdir/model.ptd (cleanup=False), write_tensor_data_to_file(outdir) truncates that file before the .pte is saved.
    • Fix: pass every cord to _check_file_backed_data. Fix this →
  • On macOS, _sync falls back to fsync after any OSError from F_FULLFSYNC, including EIO (1/3, low confidence). exir/_serialize/_cord.py:23-26

    • On macOS, fsync doesn't flush the drive cache. A chunk can therefore be cut from the source after a sync that never reached stable storage.
    • _sync_directory filters errnos (_NO_DIRECTORY_SYNC); _sync could do the same. Fix this →

Testing

Each of these was reported by one or two reviewers. Together they contradict the PR description's claim that each test fails when the code it covers is removed.

  • _move_to's error paths are untested: nothing exercises the size check (_cord.py:143) or the "shrank while it was moved" error (_cord.py:153).
  • The mode test can pass without the code it covers: test_consume_replaces_an_existing_output sets mode 0o600 (test_program.py:1383). A new file already gets 0o600 under umask 077, and Windows ignores modes, so the test passes without the chmod at _program.py:1982. Mode 0o640 differs from the default under common umasks.
  • Nothing tests the space claim, for example by checking st_blocks of the output plus the source during a move with a larger data size.
  • Weak coverage of the helpers: the Cadence save_pte_program change has no test, and the legacy-branch test (test_program.py:1256-1271) uses a duck type instead of ExecutorchProgram.

Fix this →

API Design

  • The public read paths don't document what consuming does (3/3, partly still open). exir/program/_program.py:2148, 2176, 2214-2216
    • After a consuming save, buffer (unless already cached) and write_to_file raise RuntimeError, and their docstrings don't say so.
    • with open(path, "wb") as f: et.write_to_file(f) over the consumed output truncates the only copy of the moved data before write_to_file raises. save guards against this with _check_file_backed_data; write_to_file can't, because the caller truncates the file first.
    • "None of them can be saved again" understates this: nothing can read the moved data again. Fix this →
  • Question for the author: which flow passes consume=True? (2/3)
    • No in-tree caller passes it.
    • The only non-test producers of owned FileBackedData are the two CUDA sites (cuda_backend.py:1362, cuda_weight_collector.py:188). Both keep their files next to AOTInductor's .wrapper.so (cuda_backend.py:1392-1395).
    • Nothing in backends/cuda or backends/aoti overrides AOTInductor's output location. As far as I can tell, that leaves the files in the inductor cache under the system temp directory. That is often a different file system from the output: a tmpfs, or a root disk separate from the data disk. In that case every buffer is copied, with a warning.
    • The Cadence helper has no producer, so its new consume does nothing.
    • If no flow uses this yet, consider landing the first commit (raise on failure) on its own.

Thread Safety

  • Without hard links, a file created during the move is overwritten (3/3, partly still open). exir/program/_program.py:1987-1993
    • On file systems without hard links (vfat, exFAT and some SMB mounts return EPERM or EOPNOTSUPP), the os.replace fallback overwrites a file that another process created at path during the move.
    • That contradicts the FileExistsError entry under Raises (2225) and the comment at 1988.
    • Fix: check os.path.lexists(path) before replacing, and qualify the docs. Fix this →

Performance

  • Syncs happen once per buffer, not "once per 64 MiB moved" (3/3, partly still open). exir/program/_program.py:2211-2212, exir/_serialize/_cord.py:148-159
    • Every moved buffer syncs at least once.
    • The CUDA weight collector makes one FileBackedData per weight storage (cuda_weight_collector.py:618), so an LLM moves hundreds of buffers with one fsync each.
    • Fix: correct the docstring, or batch syncs across buffers in _write_and_move so that small buffers share one sync before their sources are cut. Fix this →

Specific Comments

  • exir/program/_program.py:2211: "A consuming save writes a new file at path" is true only when something moves. Otherwise the save writes into the existing file.
  • exir/program/_program.py:2221-2225: Raises doesn't list OSError, although raising on a failed write is the point of the PR.
  • exir/program/_program.py:2245: drop the or {}. In ExecutorchProgramManager, _tensor_data is always a dict, because serialize_for_executorch returns Dict[str, Cord] (exir/_serialize/_serialize.py:49).
  • exir/_serialize/_cord.py:76-77: the __deepcopy__ comment doesn't say that copies now share ownership. Calling close() on a "copy", or using it in a with block, deletes the original's file.
  • exir/_serialize/_cord.py:128-129: "so cutting the file short loses nothing" is wrong, because every program that shares the buffer loses the data.
  • extension/export_util/utils.py:143: "and its data files" doesn't say that they go to output_dir, even when model_name is a path ending in .pte.
  • extension/export_util/utils.py:137, backends/cadence/aot/utils.py:286: the parameter is annotated prog: ExecutorchProgramManager, but the new else branch exists for the deprecated ExecutorchProgram.
  • _move_into, _move_to, _write_moving and _write_and_move are near-synonyms in one call chain. The public API says "consume" while the internals say "move".
  • The PR description lists the changes as bullets, which CLAUDE.md asks to avoid.

Recommendation

Request Changes

Two small changes block approval:

  • Windows: copy instead of moving on win32, and qualify the docstrings.
  • Failure notes: track completion in _write_moving, so a complete output is no longer reported as partial with advice to export again.

The consume=True caller question also needs an answer before this file-system machinery is worth carrying. The rest is minor and can land with those fixes.

Review progress
  • Load the /pr-review skill and the PR context
  • Read the diff (HEAD~2..HEAD at 9fca900, 7 files, +838/−33)
  • Run three independent reviewers (each covered all 7 files)
  • Merge duplicate findings and check each one against the code
  • Check which points from earlier reviews are still open
  • Post the review
  • Run the tests: not done, because running Python needs approval in this job

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review effort=max

@claude

claude Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 31m 24s —— View job


Request Changes: the default save path is fine, but save(consume=True) falls back to a full copy that can't fit after a full-disk error, fails after all data has moved when os.link returns an errno outside _NO_HARD_LINKS, and loses the old output's mode on its fallback.

Detailed review

PR Review: #25099

Summary

The PR makes save and both save_pte_program helpers raise when a write fails. It also adds an opt-in consume flag that moves owned FileBackedData into the output instead of copying it. I found no problems in the default path (consume=False). The consuming path has three small correctness gaps in its failure handling: a full disk, hard-link errnos, and the old output's mode. It also has structure and test-coverage issues. All 7 changed files were reviewed, by reading only: running Python needs approval in this job, so no tests were run.

Code Quality

1. A full disk before any data moves still triggers a full copy that cannot fit (exir/program/_program.py:2272-2276)

  • _move_into falls back on any OSError while the sources are intact. That includes ENOSPC and EDQUOT from writing the parts that don't move, or from the first chunk.
  • The move needed only the non-moved bytes plus one chunk. The copy needs those plus all of the data, so it fails too, but only after filling the free space with a new path.
  • _write_moving already removed the old output (line 1979). The user is left with a truncated .pte where a re-raise would leave nothing. The "Copying … Data moves only out of …" warning then blames move conditions that all held.
  • This is the nearly-full-disk case that consume exists for. test_a_consuming_save_that_fails_before_data_moves_copies_instead (test_program.py:1524-1535) uses OSError("disk full") as the case that should fall back.
  • Fix: re-raise ENOSPC, EDQUOT and EFBIG. Keep the fallback for errors that mean "can't move here", such as EACCES or EPERM from creating the temp file or removing the old output, or a failed directory sync.
  • Fix this →

2. A save can fail after all of its data has moved if os.link returns an unlisted errno (exir/program/_program.py:1984-1992, _NO_HARD_LINKS at line 1930)

  • The link runs after every chunk has left its source. Any errno outside EPERM, EINVAL, ENOTSUP and EOPNOTSUPP fails the save at that point.
  • The program has then lost the data, the complete file sits at path.<hex>.partial, and save_pte_program skips the .ptd.
  • A likely trigger is a FUSE file system without link (rclone mount, for example). On Linux kernels that don't yet map this to EPERM, it returns ENOSYS. I haven't checked this per file system, so treat it as low confidence.
  • test_consume_renames_only_where_there_are_no_hard_links (test_program.py:1468) makes EIO fatal.
  • Fix: re-raise only FileExistsError and treat every other link failure as "no hard links". The lexists check and os.replace still surface real I/O errors.
  • Simpler option: use a plain os.replace. A plain save has no guard against a concurrent writer either, and that guard is the only reason the errno list is needed.
  • Fix this →

3. Replacing the output loses its metadata (exir/program/_program.py:1977-1979, 2249-2250, 1944-1955)

  • _write_moving copies the mode bits and removes the old path before _write_and_move runs.
  • If the write then fails before data moves (for example the first chunk's write or sync), the fallback in save or write_tensor_data_to_file recreates path with open(path, "wb"). The new file gets the umask default, so a 0o640 output becomes 0o644. A plain save keeps the mode.
  • The _move_into docstring ("Return False, having written nothing") is wrong in that case, because the old file is already deleted.
  • On success, only the mode carries over. A group-writable output owned by another user gets a new owner and group, where a plain save would keep them. _can_replace is framed as parity with a plain save, so it could also require st_uid == os.geteuid().
  • Fix this →

4. The consuming save's file-system code is in the wrong module and uses private APIs across modules (exir/program/_program.py:22, 1928-2005, 2266)

  • About 80 lines of file-system code live in _program.py: _sync_directory, _can_replace, _intact, _write_moving and two errno tuples. _sync and the third errno tuple are in _cord.py.
  • _program.py imports the private _sync and calls FileBackedData._can_move and Cord._write_and_move.
  • _write_and_move requires that each moved buffer appears once (_cord.py:252-253). Only the Counter in _move_into enforces that.
  • Tests have to patch _sync in each module separately (test_program.py:1497 and 1517, and test_cord.py). That is why the sync-order test at test_program.py:1482 never sees the per-chunk syncs.
  • Fix: put the transaction behind one entry point in exir/_serialize, such as a Cord method that writes to a path and moves the given buffers. _move_into then only chooses what moves.
  • Fix this →

5. The copy warning doesn't say what stopped the move (exir/program/_program.py:2277-2285)

  • It lists every condition for a move but not which one failed for which buffer.
  • After the OSError fallback, it is logged right after "Could not move data into …", even though every condition it lists held.
  • Fix: name the copied buffers and the reason for each, and skip the list after a fallback.
  • Fix this →

6. Whether data moved is inferred from the file size instead of being tracked (exir/_serialize/_cord.py:93-98, 119-126, 182; exir/program/_program.py:1958-1963)

  • CLAUDE.md asks for explicit state. Because the state is only inferred:
    • the error can only guess at the cause ("for example because a consuming save moved it");
    • _intact treats any OSError or RuntimeError from stat() as moved data;
    • _can_move() is True again after a successful move (line 182);
    • sha256() raises after a move only when the digest wasn't cached.
  • Both CUDA producers cache the digest: cuda_weight_collector.py:188 passes sha256=, and cuda_backend.py:1363 calls sha256() right after move_from.
  • The sha256 check in test_moves_owned_data_and_keeps_owning_the_emptied_file (test_cord.py:145) passes only because owned() passes no digest.
  • Fix this →

7. save_bpte_program still swallows write errors (backends/cadence/aot/utils.py:311-325)

  • It sits in the same file as the save_pte_program this PR changes, and it still logs a failed write and returns. Its error message also names output_dir rather than filename.
  • Fix this →

8. Nothing in the repo passes consume=True

  • The only uses pass the flag through: extension/export_util/utils.py:151-152 and backends/cadence/aot/utils.py:300.
  • Owned data comes only from the CUDA backend (cuda_backend.py:1362, cuda_weight_collector.py:188). It moves only if that backend writes its files on the same file system as the output (_program.py:2267). I have not checked whether that holds in practice, for example when /tmp is a tmpfs.
  • Consider wiring up one real export path, or documenting where the backend should write its files, so this path has a user and an end-to-end test.

Testing

  • The copy branch of Cord._write_and_move for a FileBackedData that doesn't move has no test (exir/_serialize/_cord.py:266-267).
    • Every _write_and_move cord in test_cord.py (cord(), lines 125-129) holds exactly one FileBackedData.
    • In test_program.py, each cord that moves also holds only one.
    • If that branch or its seek broke, a .pte or .ptd with one moved and one copied blob would have a zero-filled hole, and no test would fail.
  • The change to Cadence's save_pte_program (backends/cadence/aot/utils.py:299-308) has no test.
  • Fix this →

Performance

  • The Windows check stands in for "the file system leaves holes unallocated" (exir/program/_program.py:2253-2254).
    • FAT, exFAT and HFS+ also allocate the hole, as NTFS does for a file that isn't sparse.
    • On them, a consuming save still holds the data on disk twice at its peak, syncs every 64 MiB, and empties the source.
    • Fix: check os.fstat(output.fileno()).st_blocks after the first chunk and before any truncate. That detects the case while the data is still intact, so the save can fall back to a copy.
    • This is low confidence: it rests on file-system behaviour that I haven't checked here.

Specific Comments

  • exir/program/_program.py:2226: "rename it to path" doesn't fit two of the notes. When the directory sync after the link fails, the note names path itself. After a FileExistsError, renaming the complete temp file would overwrite the file that appeared.
  • extension/export_util/utils.py:137, backends/cadence/aot/utils.py:286: prog is typed ExecutorchProgramManager, but both bodies now also branch on the deprecated ExecutorchProgram.
  • exir/program/_program.py:1991: raise FileExistsError(...) inside except OSError as e: makes the traceback read "During handling of the above exception…". Use from e.
  • PR description: it says "a read-only output" is copied with a warning. test_consume_does_not_replace_a_read_only_output (test_program.py:1645-1654) shows the save logs that warning and then raises PermissionError, as a plain save does.

Recommendation

Request Changes

  • Items 1–3 under Code Quality are small, local fixes to the new consuming path.
  • Item 1 matters most, because it hits exactly the case the flag exists for.
  • The rest can be done in this PR or a follow-up.

Review progress

  • Load the /pr-review skill and checklist
  • Read the diff (origin/main...HEAD at c6ec465, merge base 8c3f75d; 7 files, +963/−33)
  • Run three independent reviewers
  • Merge their findings and check each one against the code
  • Post the review

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review effort=max

@claude

claude Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 52m 48s —— View job


No blockers remain; the points worth fixing first are zero-length buffers that always "move", the missing test that moves two buffers into one output, and the open question of who will pass consume=True.

Detailed review

PR Review: #25099

Summary

The PR adds an opt-in consume flag that moves owned FileBackedData into the .pte/.ptd chunk by chunk instead of copying it, and makes save and both save_pte_program helpers raise when a write fails. Nothing found blocks it. The findings below are edge cases, one test gap and one design question.

All 7 changed files were reviewed. The tests could not be run, because running Python needs approval in this job, so everything below comes from reading the code at f1dab57. "(still open)" marks a point raised in an earlier review.

Code Quality

  • Replacing an existing output keeps only its mode (still open, in part). See exir/program/_program.py:1943-1954 and :1977-1980.
    • _can_replace checks that replacing the output keeps the link, other names and write protection that a plain save keeps. A plain save writes into the file, though, so the file also keeps its owner, group, ACLs, xattrs and SELinux label. The consuming save instead creates a new file that the caller owns.
    • Trigger: a teammate re-exports into a shared, group-writable directory. The owner's model.pte then belongs to the teammate, and its group becomes the teammate's primary group unless the directory is setgid, so the owner can lose access.
    • Fix: also require existing.st_uid == os.geteuid(), and copy otherwise. Fix this →
  • The copy warning lists every condition instead of the one that failed (still open). See exir/program/_program.py:2284-2292.
    • After the Could not move data into … fallback at :2282, the warning fires again and lists conditions that all held. The log then blames the setup for an error that happened during the write.
    • When _can_replace(path) is False, nothing says that the output was the reason.
    • Fix: give the reason for each buffer, or for the output, and skip the list after the fallback. Fix this →
  • A successful link can be reported as FileExistsError on NFS (low likelihood). See exir/program/_program.py:1985-1993.
    • link(2) warns that over NFS the call can fail even though the server made the link, for example when the reply to a retransmitted request is lost.
    • In that case lexists(path) is True, so a complete save raises, with a note that points the user at the temporary file.
    • Fix: before raising, treat os.path.samestat(os.stat(temp), os.lstat(path)) as success. Fix this →
  • The move runs across two modules through private names (still open). See exir/program/_program.py:22, :1928-2011 and :2272.
    • _program.py imports _sync and calls FileBackedData._can_move and Cord._write_and_move. The temporary file, the link, the directory sync and the fallback live in _program.py, while the chunked move lives in _cord.py.
    • Each module's tests patch only their own _sync (test_program.py:1441, :1488, test_cord.py:235). The sync-order test therefore expects ["sync dir", "move", "sync", "link", "sync dir"] without the per-chunk syncs, and no test sees the whole sequence.
    • Fix: move _write_moving, _sync_directory, _can_replace and _intact into exir/_serialize behind one entry point, so that _move_into only chooses what moves. Fix this →

Testing

  • No test moves more than one buffer into an output.
    • Every consuming test has a single owned buffer per cord:

      • exir/_serialize/test/test_cord.py:131-133;
      • _owned/_program in exir/program/test/test_program.py:1297-1312;
      • the lowering test at :1321-1348.
    • The CUDA collector, by contrast, makes one FileBackedData per weight storage (backends/cuda/cuda_weight_collector.py:618), so a real .ptd moves hundreds of buffers.

    • With one buffer, all(...) and any(...) give the same answer:

      • if all became any at exir/program/_program.py:2000, a failure while moving the second buffer would delete or empty the temporary file that holds the only copy of the first;
      • if it became any at :2280, that failure would turn into a copy that raises RuntimeError and loses the note.

      The suite would pass either way.

    • Fix: add a two-buffer save that succeeds, and one whose second _move_to fails after the first buffer moved. Fix this →

API Design

  • Who passes consume=True? (still open)
    • Nothing in the tree does. The only producer of owned data is the CUDA backend (backends/cuda/cuda_backend.py:1362, backends/cuda/cuda_weight_collector.py:188). It creates its files next to the AOTI .wrapper.so, in the inductor cache, which by default is under the system temp directory.
    • The st_dev check at exir/program/_program.py:2273 therefore makes the save copy whenever that cache and the output are on different file systems:
      • a tmpfs /tmp, the default on Fedora and Arch;
      • a separate /home;
      • an output bind-mounted into a container;
      • another btrfs subvolume or ZFS dataset of the same pool, since each has its own st_dev.
    • Is a follow-up planned that passes consume=True from examples/cuda/scripts/export.py:146 and puts TORCHINDUCTOR_CACHE_DIR next to the output? Or should the consume docstring say this?
    • Separately, the Cadence helper's consume (backends/cadence/aot/utils.py:290) can never move anything, because no Cadence code makes owned data. Dropping it keeps that API smaller.
  • The space saving is assumed, not checked (the first point is still open). See exir/program/_program.py:2259-2274.
    • Only Windows is excluded. FAT, exFAT, HFS+ and WSL's /mnt/c have no sparse files either, so they allocate the holes the move leaves. On those file systems the data is still consumed and synced every 64 MiB, and the peak disk use is the same as a copy.
    • Where a snapshot or clone (btrfs, ZFS, APFS) still holds the source's blocks, cutting the source frees nothing. The move then needs as much free space as a copy, and running out partway loses the export. A plain save that hits ENOSPC would leave the program intact, and a nearly full disk is exactly the case consume targets.
    • Fix: before moving, extend the output to its final length with os.ftruncate, and copy if st_blocks shows the holes were allocated. That also makes a full disk on a file system without sparse files fail before anything moves. Also name the snapshot case in the consume docstring. Fix this →
  • A consuming save that writes several files can't be retried once a later file fails (still open). See exir/program/_program.py:2206-2211 and extension/export_util/utils.py:151-152. Once one output has taken moved data, the upfront _check_file_backed_data in the next call raises RuntimeError for that data.
    • Take two .ptd files where the second fails before its data moves, for example with ENOSPC. Retrying write_tensor_data_to_file raises, even though the first file is complete and the second file's data is intact, and no public call writes only the second file.
    • If the .pte took moved data, a retried save_pte_program raises at the .pte, so the caller has to know to call write_tensor_data_to_file alone.
    • Fix: add a note to the error that names the outputs already complete, and say in both docstrings what a retry can and can't do. Fix this →

Thread Safety

  • Zero-length buffers always "move", which defeats the guard against a file that appears at path. See exir/program/_program.py:2268-2274 and :2000.
    • An empty owned buffer passes every check for move and stays _intact forever. A save that moves only empty buffers therefore takes the replace-and-sync path for nothing.
    • If the link then finds a file that appeared at path, _move_into swallows the FileExistsError and the copy fallback overwrites that file. When an old output existed, the restore at :2002-2004 has already replaced it. Preventing that overwrite is the reason for the link at :1987.
    • CUDA's empty weights placeholder is such a buffer (backends/cuda/cuda_backend.py:1362, stored at backends/aoti/aoti_backend.py:415), for example when the weights next to it are copied.
    • Fix: add and len(data) to the comprehension. Fix this →
  • Reads check the size only when the file is opened. See exir/_serialize/_cord.py:128-134.
    • to_bytes and write_to_file read to EOF, so a source that changes after _open gives short data without an error.
    • That is exactly the case the new check targets. A consuming save of one program cuts a shared buffer from the end, while another program made from the same EdgeProgramManager, or from a deep copy of it, copies the buffer on another thread. The plain save then writes a short .pte and returns normally, although the commit message says such reads now raise.
    • Fix: read exactly self._size bytes, and raise on a short read. Fix this →

Specific Comments

  • extension/export_util/utils.py:137, backends/cadence/aot/utils.py:286: the parameter is annotated prog: ExecutorchProgramManager, but both bodies now also handle the deprecated ExecutorchProgram. Annotate it as Union[ExecutorchProgram, ExecutorchProgramManager] (still open).
  • exir/_serialize/_cord.py:119-126: a digest passed to move_from is returned after a move without a size check (cuda_weight_collector.py:188 passes one). test_moves_owned_data_and_keeps_owning_the_emptied_file (test_cord.py:145-147) expects sha256 to raise, and it passes only because its data has no cached digest (still open).
  • exir/_serialize/_cord.py:171-180: the note and the finalizer go by the file's current size. In the "shrank" case of test_data_whose_file_changed_size_does_not_move (test_cord.py:198-203) nothing was cut, yet the error says bytes moved, and the source is left with no finalizer, so it is never removed. The test checks neither.
  • exir/program/_program.py:1989: "No hard links here, unless path exists." doesn't match the code. The branch handles any link failure, such as EIO or EMLINK, as the commit message says. "Any other failure, for example no hard links on this file system, falls back to a rename." would match.
  • exir/program/_program.py:2233-2235: .executorch_*.data files leak whenever the process dies before the finalizers run, whether or not the save consumes. Deleting them only frees space, but "before exporting again" reads like a precondition.
  • exir/program/_program.py:2279: full is built inline, while the other errno sets are module constants (_NO_FULL_SYNC, _NO_DIRECTORY_SYNC).

Fix these →

Recommendation

Approve. Nothing above blocks an opt-in flag whose default path only gains the intended errors. Worth doing before merging: the two-buffer test and skipping zero-length buffers. The caller question can be settled here or in a follow-up.

Review progress
  • Load the /pr-review skill and the PR context
  • Read the diff (origin/main...HEAD at f1dab57, merge base 8c3f75d; 7 files, +976/−33)
  • Run three independent reviewers (each covered all 7 files)
  • Try to run the tests: not possible, because running Python needs approval in this job
  • Merge duplicate findings and check each one against the code
  • Check which points from earlier reviews are still open
  • Post the review, then re-check every cited line and the commit messages against it

Done: three independent reviews, then every posted finding re-read against the code at f1dab57 and the two commit messages. Several reviewer claims were dropped because the code does not support them or the trigger was too contrived. One of them was that a consuming save breaks the program's own ETRecord. It doesn't: the ETRecord's edge programs are copied before to_backend (_program.py:1288, :1418, :1542), and add_executorch_program keeps only debug maps.

Not done: running the tests (needs approval in this job), and anything outside the diff.

`ExecutorchProgramManager.save` caught any error from the write, logged it and returned
normally. Both `save_pte_program` helpers (the shared one in `extension/export_util` and
the Cadence one) did the same, and the shared one then returned the path of a file that
might be empty or cut short. A caller had no way to notice, short of reading the log.

Now the error reaches the caller. `save` still logs the path when it succeeds. Both
`save_pte_program` helpers write the `.pte` of an `ExecutorchProgramManager` through
`save` instead of repeating its code, so `save` and both helpers behave the same way.
The legacy `ExecutorchProgram` from the deprecated
`exir.capture(...).to_edge().to_executorch()` path has no `save`, so the helpers still
write it with its own `write_to_file`, as before.

Behavior change for callers: `save` and `save_pte_program` raise on a failed write, where
they used to log and return.

Test plan: `exir/program/test/test_program.py` and the new
`backends/cadence/aot/tests/test_utils.py`. New tests check that `save` raises when the
write fails, that the shared `save_pte_program` writes the `.pte` and `.ptd` files,
returns the path, and raises when either write fails, and that the Cadence one saves
through `save` and raises when it fails. These fail on the code before this change. Both
files also check that the helpers still write a program that has no `save`; that behavior
did not change, so those tests guard it rather than fail before.
`FileBackedData` keeps a large blob, such as a delegate's compiled engine, in a file until
the program is written. Writing it copies that file into the `.pte` or `.ptd`, so the blob
is on disk twice until the caller deletes the file. For an engine of tens of gigabytes,
that copy alone can make an export run out of disk.

This adds a keyword-only `consume` flag, off by default, to
`ExecutorchProgramManager.save`, `write_tensor_data_to_file` and both `save_pte_program`
helpers. With it, data that owns its file (`cleanup=True`, as from `move_from`) moves into
the output.

The save opens `path` the same way a plain save does, so an existing output keeps its
owner, group, permissions, other names and links. The directory is synced first, so the
new file survives a crash. Everything except the moved data is written next, so a disk
without room for it fails before any data moves. Each moved buffer is then copied from its
end back to its start, 64 MiB at a time, and each chunk is cut off the source file after
it is synced. On file systems with sparse files, peak disk use is the data once plus one
chunk. On others, such as FAT32, the data still moves but saves no space. The cost is
time: one sync per chunk. Because the output fills out of order, its first 16 bytes stay
zero until everything else is synced, and are written and synced last. A save that stops
partway leaves a file that the runtime refuses to load, instead of one that loads with
holes in it. On macOS a sync uses `F_FULLFSYNC`, and falls back to `fsync` only where the
file system does not support it.

Data is copied instead, with a warning, when it does not own its file, the file is a link,
has another name, can't be written or is on another file system than the output, or the
program uses the file more than once. Everything is copied on Windows: NTFS fills the hole
that a move leaves in a file that is not sparse, so a move would save no space there.

The moved data is gone from every program that shares it, for example the
`EdgeProgramManager` it was lowered from and other programs made from it. If a save fails
after data moved, a note on the error says that `path` holds the only copy of the data
moved so far. Unless that file loads, the program has to be exported again. A save that
fails before any data moves raises like a plain save and leaves the data where it was.

Other behavior changes: reading a `FileBackedData` whose file changed size, before or
during the read, for example because it was moved, raises instead of returning short data,
and so does writing a program again after a consuming save. `save` and
`write_tensor_data_to_file` raise `ValueError` when the output is the file that holds the
data to write, instead of emptying it. `copy.deepcopy` of a `FileBackedData` returns the
same object, so a program made from a deep copy of a lowered `EdgeProgramManager` can
still move its data. Before, the copy could not be read once the original was collected.

`write_to_file`, which takes a file the caller opened, always copies, as before. The
deprecated `ExecutorchProgram` can't move data, so `save_pte_program` raises `TypeError`
when it gets one with `consume=True`.

Test plan: `exir/_serialize/test/test_cord.py`, `exir/program/test/test_program.py` and
`backends/cadence/aot/tests/test_utils.py` on Linux x86_64, including a save through
`to_edge_transform_and_lower` that moves backend data into a `.pte` and a `.ptd`, several
buffers in one output, a full disk before and during the move, the order of the syncs and
what is on disk at each of them, a failure after the first buffer moved, a rerun into an
existing output that is private, a link or has another name, each copy case, the copy on
Windows (by setting `sys.platform`), and the macOS sync fallback (by mocking `fcntl`).
Each new test fails when the code it covers is removed.
@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review effort=max

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@claude

claude Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Reviewing PR #25099

  • Read the PR and its diff against origin/main (2 commits, 9 files, +989/−34)
  • Have three independent reviewers go through every changed line
  • Merge their findings (about 15 distinct findings remain; three were reported by all three reviewers)
  • Check each finding against the code
  • Post the review (writing it now)

View job run

This branch was previously deployed

1 inactive deployment
cadence — 9077adc6 Deployed Nov 22, 2026 by shoumikhin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. release notes: exir Changes to any dialects and passes on these dialects, such as memory planning

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants