Skip to content

vulkan-shaders-gen: retry an empty shader compile instead of failing at link (potential fix for CI failures) - #540

Merged
0xShug0 merged 3 commits into
0xShug0:mainfrom
christopherthompson81:fix/vulkan-shader-gen-retry
Sep 20, 2026
Merged

0xShug0 merged 3 commits into
0xShug0:mainfrom
christopherthompson81:fix/vulkan-shader-gen-retry

Conversation

@christopherthompson81

Copy link
Copy Markdown
Contributor

Problem

A shader whose compile produces no SPIR-V becomes an undefined reference at link, ~20 minutes into the build, naming a symbol in vendored code with nothing earlier in the log to explain it. The Nix (vulkan) job on #539 failed this way:

ld.bfd: ggml-vulkan.cpp:3964: undefined reference to
  `matmul_id_subgroup_nvfp4_f32_aligned_f16acc_cm1_len'

write_output_files() writes the declaration before it reads the artefact, then skips the definition if the file is empty, with no diagnostic:

hdr << "extern const uint64_t " << name << "_len;\n";      // always declared
...
std::string data = read_binary_file(path);
if (data.empty()) {
    continue;                                               // definition skipped
}

Compile success was judged by stderr alone, with no exit code, so a shader that merely warns is discarded while one that reports nothing and writes nothing is accepted.

Fix

Success is judged by the artefact — the SPIR-V must exist and be non-empty. An empty result is retried up to three times with short backoff; after the last attempt the shader is named and generation fails. Diagnostics alongside a usable artefact are treated as warnings and the shader is kept.

Why retry rather than just fail

The trigger does not reproduce locally. Investigating the #539 failure I built shaderc 2026.1 — the version this repo's Nix build uses, per the job log — and compiled the exact failing shader with the exact 17 defines: exit 0, no stderr, 27,700 bytes of valid SPIR-V. 120 repeat compiles under parallel load produced no anomalies. A full Vulkan build with that compiler and all four shader extensions enabled links cleanly: 2320 symbols declared, 2320 defined.

So the shader is fine and the compiler is fine; something environmental produced an empty file while reporting success. Retrying absorbs that. Failing loudly covers the case where it is not transient.

Verification

Against an injected failure, both directions:

  • transient (first attempt empty, later attempts normal) — recovers, build links, exit 0:
shader matmul_id_subgroup_nvfp4_f32_aligned_f16acc_cm1 produced no SPIR-V; retrying (2/3)
[333/333] Linking CXX executable bin/audiocpp_cli
  • permanent (always empty) — stops at generation naming the shader, exit 1, no link error:
shader matmul_id_subgroup_nvfp4_f32_aligned_f16acc_cm1 produced no SPIR-V; retrying (2/3)
shader matmul_id_subgroup_nvfp4_f32_aligned_f16acc_cm1 produced no SPIR-V; retrying (3/3)
cannot compile matmul_id_subgroup_nvfp4_f32_aligned_f16acc_cm1 after 3 attempts
shader generation failed; see errors above

Note on upstream

The same declaration-before-definition path exists in ggml-org/llama.cpp master. Upstream does already check the exit code from execute_command, which this tree's copy does not — worth a look when these files are next synced.

🤖 Generated with Claude Code

https://claude.ai/code/session_01EkxqpYvUbjCpRDnFiNiVfx

… not defined

A shader whose compile produces no SPIR-V becomes an undefined reference
at link, twenty minutes later, naming a symbol in vendored code with
nothing earlier in the log to explain it:

    ld.bfd: ggml-vulkan.cpp:3964: undefined reference to
      `matmul_id_subgroup_nvfp4_f32_aligned_f16acc_cm1_len'

write_output_files() emits the declaration before reading the artefact,
then skips the definition if the file is empty, silently. The symbol is
left declared and never defined.

Compile success was also judged by stderr alone, with no exit code, so a
shader that merely warns is discarded while one that reports nothing and
writes nothing is accepted. Success is now judged by the artefact: the
SPIR-V must exist and be non-empty.

An empty result is retried up to three times with short backoff before
giving up. This has been seen in CI with no accompanying diagnostic and
does not reproduce locally, so it appears environmental and rare;
retrying costs milliseconds on a genuinely broken shader and saves a
build that would otherwise fail at link for no visible reason. After the
last attempt the shader is named and generation fails.

Verified both ways against an injected failure. A transient -- first
attempt empty, later attempts normal -- recovers and the build links.
A permanent one reports:

    shader matmul_id_subgroup_nvfp4_f32_aligned_f16acc_cm1 produced no SPIR-V; retrying (2/3)
    shader matmul_id_subgroup_nvfp4_f32_aligned_f16acc_cm1 produced no SPIR-V; retrying (3/3)
    cannot compile matmul_id_subgroup_nvfp4_f32_aligned_f16acc_cm1 after 3 attempts
    shader generation failed; see errors above

and stops at generation instead of at link.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01EkxqpYvUbjCpRDnFiNiVfx
@0xShug0 0xShug0 changed the title vulkan-shaders-gen: retry an empty shader compile instead of failing at link vulkan-shaders-gen: retry an empty shader compile instead of failing at link (potential fix for CI failures) Sep 13, 2026
@0xShug0

0xShug0 commented Sep 13, 2026

Copy link
Copy Markdown
Owner

@christopherthompson81 Thanks! I’ll keep it open for now until I get some feedback from the nix sub.

@christopherthompson81

Copy link
Copy Markdown
Contributor Author

Moving this to draft so it isn't sitting in your review queue while you wait on feedback from the nix sub — no pressure either way, just ping me and I'll mark it ready again.

@christopherthompson81
christopherthompson81 marked this pull request as draft September 15, 2026 00:06
@0xShug0 0xShug0 added the ggml label Sep 15, 2026
@0xShug0
0xShug0 marked this pull request as ready for review September 20, 2026 16:27
@0xShug0

0xShug0 commented Sep 20, 2026

Copy link
Copy Markdown
Owner

Got nothing from nix sub. I'm going to merge this PR.

@0xShug0

0xShug0 commented Sep 20, 2026

Copy link
Copy Markdown
Owner

@christopherthompson81 I don’t know much about CI, so I left the review entirely to Codex. Does that make sense?

Two issues

  • It can accept a failed compile. The PR treats any non-empty .spv file as success without checking the compiler exit code. A failed compile could leave a non-empty stale file from an earlier build.
  • Its failure flag has a data race. Shader jobs run concurrently, but generation_failed is a plain bool written by those jobs. llama.cpp uses an atomic flag.

Current llama.cpp checks the subprocess exit status and fails shader generation on an error; it does not implement the PR empty-file retry. The retry may be useful, but it should be added on top of reliable subprocess failure handling, with the old output removed before each attempt

christopherthompson81 added a commit to christopherthompson81/audio.cpp that referenced this pull request Sep 20, 2026
…atomic

Review feedback on 0xShug0#540. Two holes in the previous commit:

Judging success by the artefact alone means a compile that fails and
leaves an earlier build's .spv in place is credited with that stale
file. Reproduced against a fake glslc that exits 0, prints nothing and
writes nothing, with a 26-byte stale artefact already present: the
generator exited 0 and embedded the stale bytes as the shader.

execute_command discarded the exit status at the syscall -- waitpid
with a null status, and no GetExitCodeProcess on Win32 -- so no caller
could have checked it. It now returns the status, and a non-zero exit
or any stderr fails the shader immediately, without retrying; a
compiler that reports failure is believed the first time. Only a silent
empty result is retried, and out_path is removed before each attempt so
no stale file can stand in for a missing one.

generation_failed was a plain bool written from the compile threads.
It is std::atomic<bool> now, and the catch handler sets it too: an
exception there leaves the shader out of shader_fnames, which is the
same undefined reference by another route.

Verified standalone against fake compilers over add.comp's 16 variants:
healthy exits 0 clean; a non-zero exit fails at once naming the code; a
transient first-attempt-empty recovers with all 16 definitions emitted;
a permanent empty and the stale-file case both stop at generation.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01TMmMgd5xNGnjsQgybuUiK3
@christopherthompson81

Copy link
Copy Markdown
Contributor Author

It makes sense — both points were right, and I've pushed a fix for each in ae72096.

Exit code. Worse than it looked: execute_command in this tree discards the status at the syscall (waitpid(pid, nullptr, 0), and no GetExitCodeProcess on the Win32 side), so no caller could have checked it. It returns the status now. A non-zero exit or any stderr fails the shader immediately, with no retry — a compiler that reports failure gets believed the first time. Only a silent empty result is retried, and out_path is removed before each attempt so a stale artefact can't stand in for a missing one.

The stale-file case wasn't hypothetical. Against a fake glslc that exits 0, prints nothing and writes nothing, with a 26-byte leftover .spv already in the output directory, the old binary exited 0 and embedded the stale bytes as the shader. New one stops at generation and names it.

Data race. Correct — generation_failed is std::atomic<bool> now. I also set it in the catch handler, which was a third way to the same undefined reference: an exception there leaves the shader out of shader_fnames entirely.

On the ordering point — "the retry should be added on top of reliable subprocess failure handling" — that's exactly the shape now: exit code first, artefact second, retry only on the silent-empty case.

Verified standalone over add.comp's 16 variants: healthy exits 0 clean; non-zero exit fails at once naming the exit code; transient first-attempt-empty recovers with all 16 definitions emitted; permanent-empty and stale-file both stop at generation with exit 1.

And yes — llama.cpp master has the exit-code check but not the empty-file retry. I have the retry on a local branch there; I'll send it upstream once this one settles, so the two trees don't drift further.

…atomic

Review feedback on 0xShug0#540. Two holes in the previous commit:

Judging success by the artefact alone means a compile that fails and
leaves an earlier build's .spv in place is credited with that stale
file. Reproduced against a fake glslc that exits 0, prints nothing and
writes nothing, with a 26-byte stale artefact already present: the
generator exited 0 and embedded the stale bytes as the shader.

execute_command discarded the exit status at the syscall -- waitpid
with a null status, and no GetExitCodeProcess on Win32 -- so no caller
could have checked it. It now returns the status, and a non-zero exit
or any stderr fails the shader immediately, without retrying; a
compiler that reports failure is believed the first time. Only a silent
empty result is retried, and out_path is removed before each attempt so
no stale file can stand in for a missing one.

generation_failed was a plain bool written from the compile threads.
It is std::atomic<bool> now, and the catch handler sets it too: an
exception there leaves the shader out of shader_fnames, which is the
same undefined reference by another route.

Verified standalone against fake compilers over add.comp's 16 variants:
healthy exits 0 clean; a non-zero exit fails at once naming the code; a
transient first-attempt-empty recovers with all 16 definitions emitted;
a permanent empty and the stale-file case both stop at generation.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01TMmMgd5xNGnjsQgybuUiK3
Backported from the shape llama.cpp master already has: the failure
check belongs before write_output_files(), not after it. A partial
header and source carry fresh timestamps, so a second build finds them
newer than their inputs, skips regeneration and links the gap instead.

The check after write_output_files() stays, because the embed step has
its own way to fail -- a shader that compiled but whose artefact is
unreadable by the time it is read back. llama.cpp sets its flag there
and then returns EXIT_SUCCESS without re-reading it, so that one is
detected and dropped upstream; keeping both checks here closes it.

execute_command is now byte-identical to llama.cpp master, which should
make the next ggml sync of this file a clean one.

Verified with ci/run-local.sh linux-vulkan on a real glslc: 1932 shader
symbols declared, every one defined, binary links with no undefined
generated symbols. Against the fake-compiler matrix, no output file is
written on any failure path.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01TMmMgd5xNGnjsQgybuUiK3
@christopherthompson81

Copy link
Copy Markdown
Contributor Author

Two follow-ups — the branch has been force-pushed, so the ae72096 in my last comment is now f031d28. Same content, rebuilt; see the second point for why.

One more backport from llama.cpp master. The failure check belongs before write_output_files(), not after it. Writing a partial header and source gives them fresh timestamps, so a second build finds them newer than their inputs, skips regeneration and links the gap — the original failure mode, one build later. Upstream returns early there; this branch now does too.

I kept the check after write_output_files() as well, because the embed step has its own way to fail. Worth flagging upstream: llama.cpp master sets compile_failed inside write_output_files() and then returns EXIT_SUCCESS without re-reading it, so that one is detected and dropped. Backporting the early return alone would have imported that.

execute_command is now byte-identical to llama.cpp master, which should make the next ggml sync of this file a clean one.

Line endings. My first push normalized the whole file CRLF→LF and showed up as a 2496-line diff. external/ggml/** blobs in this repo really are CRLF, and text=auto in .gitattributes skips renormalizing a file whose indexed blob is already CRLF — which is how the original commit added 50 CRLF lines cleanly, and why every commit after the first LF one normalized. Both commits are rebuilt on the original with endings preserved. Cumulative diff is 48 insertions / 24 deletions now, and the content is byte-identical to what I tested.

On testing CI locally — you mentioned not knowing much about CI, so: I added ci/run-local.sh, which replays the workflow steps in the same base image via docker. ci/run-local.sh linux-vulkan runs the Vulkan job end to end in about 7 minutes against a real glslc, which is the check this fix never had. I'll send that as its own PR rather than bury it here — say the word if you'd rather not carry it.

Running it against this branch: 1932 shader symbols declared, every one defined, binary links with no undefined generated symbols.

One unrelated thing it turned up: the "Build and run unit tests" step ends in No tests were found!!! and ctest exits 0, so the job is green while running nothing. The suites are gated behind ENGINE_BUILD_TESTS / ENGINE_BUILD_EXTENDED_TESTS / ENGINE_BUILD_MODEL_TESTS, and linux-build.yml sets none of them. Separate issue; I can open one if it's useful.

@0xShug0
0xShug0 merged commit 5785167 into 0xShug0:main Sep 20, 2026
6 checks passed
@0xShug0

0xShug0 commented Sep 20, 2026

Copy link
Copy Markdown
Owner

Thanks! Merged and let's see how it goes.

0xShug0 pushed a commit that referenced this pull request Sep 22, 2026
… off under memory pressure (#634)

* vulkan-shaders-gen: retry a compiler that cannot be started, and back off under memory pressure

#540 made an empty SPIR-V artefact retryable, which turned a link-time
undefined reference into a named generation failure. The Nix (vulkan) job now
reports the real cause, and it is one that fix does not cover:

    Error executing command for matmul_id_subgroup_nvfp4_f16_aligned_f16acc_cm1:
      Failed to fork process
    Cannot allocate memory

`execute_command` throws when fork() fails, and #540 opened its try block
OUTSIDE the retry loop -- so a spawn failure skipped every attempt and went
straight to the outer catch. An empty artefact was retried; not being able to
start the compiler at all, which is the more obviously transient of the two,
was fatal on the first occurrence.

The generator runs as one ninja target among many, so the C++ compiles of this
same build are what exhaust the memory. Two changes:

- A spawn failure is an attempt like any other, with backoff that grows
  (250ms, 500ms, 1s, 2s) rather than the flat 100ms an empty artefact needed:
  the wait has to be able to outlast a neighbouring translation unit.
- Failing to start a process is a statement about the machine, not about one
  shader, so it now halves the whole generator's concurrency cap. Repeated
  pressure converges on serial compilation instead of every remaining shader
  hitting the same wall in turn, which is what the CI log shows happening.

Also: both error paths leaked pipe descriptors before throwing, which only
mattered once they became retryable -- leaking under EMFILE would turn a
transient shortage into the permanent one it was mistaken for. errno now
travels in the exception rather than to stderr, and the messages are composed
before being written, since compile threads report concurrently and chained
<< from each interleaves into unreadable lines.

Verified with a real glslc and an injected ENOMEM at the fork site: clean run
16/16 SPIR-V and silent; transient recovers with the cap stepping 16->8->4->2->1
and exits 0; permanent still names the shader and exits 1 at generation.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01TMmMgd5xNGnjsQgybuUiK3

* vulkan-shaders-gen: hold no permit while waiting, and retry only a resource shortage

Both review points were right, and the first one was not theoretical.

1. The lowered cap did not reach the retries.

The compile permit is acquired once per shader in string_to_spv and held for
the whole of string_to_spv_func, so it spanned every attempt and every backoff.
A reduced cap therefore governed only shaders that had not started yet: the
tasks already running -- the ones that had just exhausted the machine -- kept
their permits and retried in lockstep into the same wall.

The permit is now released before the wait and re-acquired after it, so a task
resumes only when the generator is back under its limit. Measured with 40
injected ENOMEMs, probing held-permits against the cap at each launch:

    without the release: 48 attempts, 26 over cap, worst held=6 vs cap=1
                         -> generation FAILED, 8/16 shaders
    with the release:    56 attempts,  2 over cap, worst held=4 vs cap=1
                         -> generation succeeded, 16/16

Reproducible 3/3 each way. The two remaining over-cap attempts are a benign
race: the cap can fall between a permit being granted and the attempt starting.
The permit was valid when taken, so this costs one in-flight compile, not a
pile-up.

2. Every launch failure was treated as memory pressure.

"Cannot start the compiler" covered both a shortage that clears on its own and
a missing or malformed compiler that never will, and the second was retried
five times with four concurrency halvings before failing. On Windows a missing
glslc lands exactly there, because CreateProcess reports it to the caller
rather than to a child that has already forked; on POSIX execvp fails in the
child and arrives as an exit code, so only pipe() and fork() throw.

Launch failures now raise spawn_resource_error only for ENOMEM, EAGAIN, EMFILE
and ENFILE -- or their Win32 equivalents -- and the retry catches that type
alone. Anything else reaches the outer handler and fails at once. Verified by
injecting EACCES: 0 retries, 0 concurrency reductions, exit 1 naming the
shader, against ENOMEM in the same harness recovering with 12 retries and 4
reductions.

Clean run against a real glslc is unchanged: 16/16 SPIR-V, no stderr, exit 0.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants