Skip to content

Generated .ino.cpp invalidates the checksum; background pio commands wipe .pio/build and .pio/libdeps #5519

Open

Description

@ellensp

Configuration

Operating system: Ubuntu 24.04.5 LTS, kernel 7.0.0-31-generic (x86_64)

PlatformIO Version (platformio --version): PlatformIO Core, version 6.2.0
(Python 3.12.3)

Description of problem

An ordinary single Arduino build can be destroyed mid-compile, with no concurrency
on the user's part, because PlatformIO generates a file into src_dir that
invalidates its own project checksum
- and any other pio invocation that then
runs will delete .pio/build.

1. A build invalidates its own checksum. compute_project_checksum()
(platformio/project/helpers.py:93) hashes the sorted list of every
.c .cc .cpp .h .hpp .s .S path under include_dir, src_dir and lib_dir.
The Arduino .ino conversion writes <name>.ino.cpp into src_dir at the start of
a build and removes it at the end. So for the entire duration of every .ino-based
build, the computed checksum differs from the stored project.checksum, and any
pio invocation during that window sees a mismatch and wipes the build tree.

This is what makes it hit ordinary users rather than only people running builds in
parallel. A single build, with the VS Code extension simply open, is enough: the
extension runs pio project init --ide vscode in the background - for example after
platformio.ini, or a file it includes via extra_configs, is modified - and that
lands inside the window.

The transient file is removed when the build ends, so by the time anyone looks the
project is back to a state whose checksum matches. That is why this presents as a
random, unreproducible build failure.

2. clean_build_dir() removes the shared build root, not the environment being
built.
platformio/run/cli.py:127 calls clean_build_dir(build_dir, config)
(platformio/run/helpers.py:26) with build_dir = the .pio/build root. When the
checksum does not match it runs fs.rmtree(build_dir), destroying every
environment's artifacts, not just the one being processed. So the damage is not
limited to whatever the background refresh was looking at - pio run -e nano will
delete .pio/build/uno.

3. An empty static lib_deps deletes the whole libdeps directory.
_install_project_env_libraries() (platformio/package/commands/install.py:240)
reads

lib_deps = config.get(f"env:{project_env}", "lib_deps")

straight from ProjectConfig - the static platformio.ini - and passes it to
_uninstall_project_unused_libdeps() (same file, 277-290), which begins:

lib_deps = set(lib_deps)
storage_dir = Path(lm.package_dir)
if not lib_deps:
    if storage_dir.exists():
        fs.rmtree(str(storage_dir))     # the entire .pio/libdeps/<env>
    return

This runs before any extra_scripts hook, so a project that populates lib_deps
from a script - a documented, supported pattern - presents an empty list here every
time, and its whole libdeps directory is removed.

pio project init --ide vscode is one such command, so the same background
invocation that triggers defects 1 and 2 also empties .pio/libdeps/<env>.

Whether this is noticed depends on whether something reinstalls afterwards, which
is why it can look inconsistent. If the same command later resolves dependencies
again the directory is repopulated and only unmanaged files are missing; where
nothing reinstalls, the libraries are simply gone and the next build fails with:

*** [.pio/build/<env>/src/src/MarlinCore.cpp.o] Implicit dependency
    `.pio/libdeps/<env>/TMCStepper/src/TMCStepper.h' not found, needed by target ...

This one does not need a race at all: the library is gone and stays gone, so the
next build fails outright rather than intermittently. It is also not addressed by
relocating the build directory, since libdeps is a separate tree.

Defect 1 is the one that affects ordinary Arduino users. Defect 3 affects any
project that injects lib_deps from a script. Defect 2 widens the blast radius of
defect 1. They are independent, and fixing any one of them breaks that particular
interaction.

Steps to Reproduce

Three files, no IDE involved:

platformio.ini

[env:uno]
platform = atmelavr
board = uno
framework = arduino

[env:nano]
platform = atmelavr
board = nanoatmega328
framework = arduino

src/main.ino

void setup() {}
void loop() {}

src/slow.cpp - any translation unit slow enough to give a race window. Generated
with:

src = 'volatile long sink;\n'
for i in range(40000): src += 'static long f%d(long x){return x*%d+1;}\n' % (i, i)
src += 'void slow(){' + ''.join('sink=f%d(sink);' % i for i in range(40000)) + '}\n'
open('src/slow.cpp','w').write(src)
Defect 1 on its own - no second process, no race

Show that the stored checksum is invalid for the whole duration of one ordinary
build:

pio run -e uno                                   # stores .pio/build/project.checksum
cat .pio/build/project.checksum                  # stored
python -c "from platformio.project.config import ProjectConfig
from platformio.project.helpers import compute_project_checksum
print(compute_project_checksum(ProjectConfig.get_instance()))"   # idle

pio run -e uno -t clean
pio run -e uno &                                 # start a build
sleep 3 && python -c "...same three lines..."    # sample while it compiles
wait
The resulting build failure
  1. pio run -e uno -t clean
  2. pio run -e uno in one shell (takes ~6 s with the file above)
  3. About 2 s in, pio run -e nano in another shell

Step 3 stands in for the VS Code extension's background
pio project init --ide vscode. In normal use nobody types it - it is enough to
have the project open in the editor.

Actual Results

Defect 1 - the checksum does not match the stored one while the build runs, and
matches again once it finishes:

stored   : e960e7285f53a010cfd40461f3c3d74047495a4b
idle     : e960e7285f53a010cfd40461f3c3d74047495a4b
mid-build: f1844bf0b92c4e402f6187fef93387b99c7db0fe   <-- src/ now contains main.ino.cpp
after    : e960e7285f53a010cfd40461f3c3d74047495a4b

One build, one process. Any pio command run during that window will see the
mismatch and delete .pio/build.

The resulting failure - the uno build dies mid-compile:

Fatal error: can't create .pio/build/uno/src/slow.cpp.o: No such file or directory
FileNotFoundError: [Errno 2] No such file or directory: '.../.pio/build/uno/.sconsign312.tmp'
========================== [FAILED] Took 6.21 seconds ==========================

.pio/build/uno/ no longer exists. No such file or directory refers to the
directory, not the source.

Polling src/ during the build shows where the differing checksum comes from:

SEEN during build: src/main.ino.cpp
after build:       main.ino  slow.cpp

The transient file is gone by the time anyone investigates, which is why this
normally looks random.

Defect 2, shown separately - shared-root wipe - build uno, then touch src/extra.cpp, then pio run -e nano.
.pio/build/uno is gone, despite nano being a different environment.

Defect 3, shown separately - libraries deleted. Add an extra_scripts hook that
injects a dependency, so nothing is visible in the static config:

platformio.ini

[env:uno]
platform = atmelavr
board = uno
framework = arduino
extra_scripts = pre:inject.py

inject.py

Import("env")
cfg = env.GetProjectConfig()
cfg.set("env:" + env["PIOENV"], "lib_deps", ["<any library>"])

pio project config -e uno shows no lib_deps. Build once so the library installs,
then drop a marker in the directory and run the command the editor runs:

echo marker > .pio/libdeps/uno/MARKER.txt
pio project init --ide vscode
ls .pio/libdeps/uno        # MARKER.txt is gone - the directory was removed

The marker matters: check the end state alone and this looks like it did not
happen, because the dependency is reinstalled later in the same command. The marker
is not, which proves the directory was deleted. On a project where nothing
reinstalls - Marlin, where lib_deps comes from a feature-driven script - the
libraries stay gone and the next build fails with the "Implicit dependency ... not
found" error above.

Expected Results

  • A build should not invalidate the project checksum through a file PlatformIO
    itself generates into src_dir for the duration of that build.
  • pio run -e nano should not delete another environment's build output.
  • Concurrent pio invocations on one project should not destroy each other's output.
  • Dependency resolution should not delete installed libraries merely because
    lib_deps is empty in the static config, given that extra_scripts is a supported
    way to populate it.

Additional info

Instrumenting clean_build_dir() to log argv, pid/ppid, parent command line, both
checksums and a stack trace before each rmtree gives, on a real project:

>>> RMTREE <<<
  build_dir : /home/user/project/.pio/build
  argv      : platformio/__main__.py -c vscode project init --ide vscode
  parent    : /usr/share/code/code --type=utility ... node.mojom.NodeService ...

with the timeline:

23:36:26.842  RMTREE  (a deliberate `pio run -t clean`)
23:36:28.407  KEEP    checksum matches - ino.cpp not created yet
23:36:29      <name>.ino.cpp CREATED by the build
23:36:35.505  RMTREE  <-- killed the running build
23:36:36      <name>.ino.cpp deleted

Both fatal wipes land inside the window where the generated .ino.cpp exists.

Notes:

  • pio run --disable-auto-clean does not help. It guards the victim's call to
    clean_build_dir(), not the other process's.
  • Longer builds are hit far more often, since the vulnerable window is exactly the
    build duration. On the project where this was found, ~60-70 s STM32 builds failed
    repeatedly while ~10 s AVR builds almost never did.
  • Workarounds that do work: removing the .ino so no transient file is generated
    (defect 1), and pointing PLATFORMIO_BUILD_DIR and PLATFORMIO_LIBDEPS_DIR
    outside the project. PLATFORMIO_BUILD_DIR alone is not enough once defect 3 is in
    play, because libdeps is a separate tree.

Suggested fixes, either of which would break the interaction:

  1. Exclude PlatformIO's own generated *.ino.cpp from compute_project_checksum().
    This is the one that matters for ordinary users.
  2. Scope the removal to the environment actually being processed, and/or take a lock
    around clean_build_dir().
  3. Do not treat an empty static lib_deps as "no dependencies" for the purpose of
    uninstalling. extra_scripts is a supported way to populate it, and those hooks
    have not run at that point. Skipping the removal when the project declares
    extra_scripts would be sufficient.

How this was investigated

This was diagnosed with AI assistance under human oversight, noted here so the
findings can be weighed accordingly.

The initial observation was mine: builds run from the command line never failed with
VS Code closed, but failed regularly with it open. I directed the investigation and
reviewed each step.

Claude (Anthropic), model Opus 5, running as Claude Code, did the legwork: reading
the PlatformIO Core sources to find clean_build_dir() and
compute_project_checksum(), temporarily instrumenting clean_build_dir() to log
argv, pid/ppid, parent command line, both checksums and a stack trace before each
rmtree, running the builds that produced the timeline above, sampling src_dir
during a build to catch the transient .ino.cpp, and reducing it all to the
standalone three-file reproduction in this report.

Every claim here rests on captured output rather than inference, and the standalone
reproduction is the part worth checking first - it needs no editor, no
instrumentation and no trust in how the conclusion was reached. Several intermediate
hypotheses along the way turned out to be wrong and were discarded on evidence.

Activity

  1. changed the title [-]Generated .ino.cpp invalidates the project checksum, so .pio/build gets wiped mid-build[/-] [+]Generated .ino.cpp invalidates the checksum; background pio commands wipe .pio/build and .pio/libdeps[/+] on Sep 23, 2026
  2. ivankravets commented on Sep 23, 2026

    @ivankravets
    Member

    Scam.

  3. ellensp commented on Sep 24, 2026

    @ellensp
    Author

    This is not a scam. I am a Marlin firmware developer and this is a real defect that
    has been destroying my builds. I appreciate the issue tracker gets a lot of noise,
    so here is the shortest possible version, with a video.

    Video (61s, no commentary needed):

    bug1-pio-checksum.mp4

    Reproduce in three files:

    platformio.ini

    [env:uno]
    platform = atmelavr
    board = uno
    framework = arduino
    
    [env:nano]
    platform = atmelavr
    board = nanoatmega328
    framework = arduino

    src/main.ino — void setup(){} void loop(){}

    src/slow.cpp — any file slow enough to give a ~6 s build.

    pio run -e uno -t clean
    pio run -e uno            # shell 1
    pio run -e nano           # shell 2, two seconds later

    Result: the uno build dies with
    Fatal error: can't create .pio/build/uno/src/slow.cpp.o: No such file or directory,
    and .pio/build/uno/ no longer exists.

    Why: compute_project_checksum() (platformio/project/helpers.py:93) hashes the
    sorted list of every source path under src_dir. The .ino conversion writes
    main.ino.cpp into src_dir at the start of a build and deletes it at the end, so
    for the whole duration of every .ino build the computed checksum differs from the
    stored project.checksum. Any pio command run in that window therefore takes the
    mismatch branch in clean_build_dir() (platformio/run/helpers.py:26) and deletes
    the build tree.

    Checksums from the video, same project, nothing else changed:

    stored    98662f3fe4234b558792d365ed2cd4489e00f531
    mid-build 49863ce2cff00b262aecac407f873843ea9da950
    

    Why this affects ordinary users, not just people building in parallel: nobody
    types that second command. The VS Code PlatformIO extension runs
    pio project init --ide vscode in the background when platformio.ini changes, and
    that lands inside the same window. With VS Code closed my builds never fail; with it
    open they fail regularly. The generated file is gone by the time anyone looks, which
    is why this normally presents as a random, unreproducible build failure.

    Suggested fix: exclude PlatformIO's own generated *.ino.cpp from
    compute_project_checksum().

    Please reopen. If you would prefer this split into separate issues, or want any
    further detail, I am happy to provide it.

  4. ellensp commented on Sep 24, 2026

    @ellensp
    Author

    A second, independent defect, shown in the same project. This one needs no race and
    no timing — it reproduces deterministically every time.

    Video (44s):

    bug2-pio-shared-root.mp4

    Reproduce:

    pio run -e uno            # build both environments
    pio run -e nano
    ls .pio/build/            # nano  project.checksum  uno
    
    touch src/extra.cpp       # add any new source file
    pio run -e nano           # build ONLY nano
    
    ls .pio/build/            # nano  project.checksum   -- 'uno' is gone

    Result: building nano deletes .pio/build/uno. Nothing referenced uno.

    Why: platformio/run/cli.py:127 passes the .pio/build root to
    clean_build_dir():

    build_dir = config.get("platformio", "build_dir")
    clean_build_dir(build_dir, config)

    and platformio/run/helpers.py:26 removes that whole tree on a checksum mismatch:

    if isdir(build_dir):
        if isfile(checksum_file):
            with open(checksum_file, encoding="utf8") as fp:
                if fp.read() == checksum:
                    return
        fs.rmtree(build_dir)        # the entire .pio/build

    project.checksum is a single file at that root, shared by every environment, so one
    environment's mismatch discards all of them.

    On its own this is wasted rebuild time. Combined with #5519's first defect it is why
    a lost build looks random: a build generates main.ino.cpp, the checksum no longer
    matches, and the next pio command — typically the VS Code extension's background
    pio project init --ide vscode — removes the build tree of whatever else happens to
    be compiling.

    Suggested fix: scope the removal to the environment being processed, and/or take
    a lock around clean_build_dir().

  5. ellensp commented on Sep 24, 2026

    @ellensp
    Author

    A third defect, in the package manager rather than the build system. No race, no
    build running — one command deletes your installed libraries.

    Video (52s):

    bug3-pio-libdeps.mp4

    Reproduce. A project whose lib_deps comes from a script, which is a documented,
    supported pattern:

    platformio.ini

    [env:uno]
    platform = atmelavr
    board = uno
    framework = arduino
    extra_scripts = pre:inject.py

    inject.py

    Import("env")
    cfg = env.GetProjectConfig()
    cfg.set("env:" + env["PIOENV"], "lib_deps", ["bblanchon/[email protected]"])
    pio run -e uno                                # ArduinoJson installs, build OK
    echo marker > .pio/libdeps/uno/MARKER.txt     # marker so we can see what happens
    pio project init --ide vscode                 # what the VS Code extension runs
    ls .pio/libdeps/uno                           # MARKER.txt is gone

    The marker matters. ArduinoJson is still listed afterwards, so looking at the
    end state alone suggests nothing happened. It does not survive — the whole directory
    is removed and the dependency is reinstalled later in the same command. The marker
    is not reinstalled, which is what shows the deletion.

    Why: _install_project_env_libraries()
    (platformio/package/commands/install.py:240) reads

    lib_deps = config.get(f"env:{project_env}", "lib_deps")

    from the static platformio.ini, then passes it to
    _uninstall_project_unused_libdeps() (same file, 277):

    lib_deps = set(lib_deps)
    storage_dir = Path(lm.package_dir)
    if not lib_deps:
        if storage_dir.exists():
            fs.rmtree(str(storage_dir))     # the entire .pio/libdeps/<env>
        return

    This runs before any extra_scripts hook, so a script-populated project always
    presents an empty list here and has its libdeps directory removed.

    Why it is not cosmetic. Where nothing reinstalls afterwards the libraries are
    simply gone and every later build fails. On Marlin, whose lib_deps are selected by
    a feature-driven script, opening the project in VS Code is enough to produce:

    *** [.pio/build/<env>/src/src/MarlinCore.cpp.o] Implicit dependency
        `.pio/libdeps/<env>/TMCStepper/src/TMCStepper.h' not found, needed by target ...
    

    Note this is not fixed by relocating PLATFORMIO_BUILD_DIR, since libdeps is a
    separate tree.

    Suggested fix: do not treat an empty static lib_deps as "no dependencies".
    Skipping the removal when the project declares extra_scripts would be sufficient.

  6. thinkyhead commented on Sep 24, 2026

    @thinkyhead
    Contributor

    My OCD brain wants to fix up all the text in these posts to remove the extra newlines that agents insert. But otherwise these appear to be sensible findings, and not specifically related to how Marlin "abuses" the PlatformIO script stack (j/k - we just make creative use of it).

    @ivankravets — I can vouch for @ellensp. He won't waste your time.

    If long detailed robot posts are a problem, we can clean them up some, but watch out! there may be more. We've both got 6 months of free Claude Max 20x to use however we want, and we're coming for your bugs.

  7. added this to the 6.2.1 milestone on Sep 24, 2026
  8. ivankravets commented on Sep 24, 2026

    @ivankravets
    Member

    Hi @thinkyhead, I reopened the issue. An interesting thing has happened. Once @ellensp filed the issue, 1 hour later, someone contacted us and asked for money to fix it. Here is a part of the email:

    Image

    How is that even possible?

  9. ellensp commented on Sep 25, 2026

    @ellensp
    Author

    An AI-powered bot would be my guess. Scrapes new issues and sends 'extortion' e-mails.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions