Generated .ino.cpp invalidates the checksum; background pio commands wipe .pio/build and .pio/libdeps
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>
returnThis 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 = arduinosrc/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
waitThe resulting build failure
pio run -e uno -t cleanpio run -e unoin one shell (takes ~6 s with the file above)- About 2 s in,
pio run -e nanoin 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 : e960e7285f53a010cfd40461f3c3d74047495a4bOne 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.cppThe 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.pyinject.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 removedThe 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_dirfor the duration of that build. pio run -e nanoshould not delete another environment's build output.- Concurrent
pioinvocations on one project should not destroy each other's output. - Dependency resolution should not delete installed libraries merely because
lib_depsis empty in the static config, given thatextra_scriptsis 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 deletedBoth fatal wipes land inside the window where the generated .ino.cpp exists.
Notes:
pio run --disable-auto-cleandoes not help. It guards the victim's call toclean_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
.inoso no transient file is generated (defect 1), and pointingPLATFORMIO_BUILD_DIRandPLATFORMIO_LIBDEPS_DIRoutside the project.PLATFORMIO_BUILD_DIRalone is not enough once defect 3 is in play, becauselibdepsis a separate tree.
Suggested fixes, either of which would break the interaction:
- Exclude PlatformIO's own generated
*.ino.cppfromcompute_project_checksum(). This is the one that matters for ordinary users. - Scope the removal to the environment actually being processed, and/or take a lock
around
clean_build_dir(). - Do not treat an empty static
lib_depsas "no dependencies" for the purpose of uninstalling.extra_scriptsis a supported way to populate it, and those hooks have not run at that point. Skipping the removal when the project declaresextra_scriptswould 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.
Source: platformio/platformio-core