Skip to content

fix(ci): stream build output during long compiles - #3702

Merged
zackees merged 4 commits into
masterfrom
fix/3697-unbuffered-build-output
Jul 16, 2026
Merged

zackees merged 4 commits into
masterfrom
fix/3697-unbuffered-build-output

Conversation

@zackees

@zackees zackees commented Jul 16, 2026 •

Copy link
Copy Markdown
Member

Closes #3697\n\n## Summary\n- Flush every line emitted by the shared CI logger so compiler progress reaches piped stdout immediately.\n- Set PYTHONUNBUFFERED=1 on the reusable build step as a second guard for direct Python output.\n- Add a regression test asserting locked_print flushes each emitted line.\n\n## Validation\n- uv run pytest tests/test_locked_print.py — 1 passed\n- �ash lint --no-rust ci/util/locked_print.py tests/test_locked_print.py — passed\n- uv run ruff check and format check — passed\n- Full �ash test --py was attempted; it stalled in the unrelated ci/tests/test_fbuild_qemu.py emulator test and was stopped after leaving toolchain processes. The focused change completed before that test and has no dependency on QEMU.

Summary by CodeRabbit

  • Bug Fixes

    • Improved CI build log responsiveness by enabling unbuffered Python output during FastLED example compilation.
    • Enhanced ordered, concurrent logging output to reduce interleaving and ensure more consistent stdout behavior.
  • Tests

    • Added coverage to confirm the logging utility writes a multi-line message as a single combined output and flushes exactly once.

@coderabbitai

coderabbitai Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d01cc38a-cf30-4697-8f09-423f897c312f

📥 Commits

Reviewing files that changed from the base of the PR and between 90cc958 and ed9b29e.

📒 Files selected for processing (1)
  • ci/util/locked_print.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • ci/util/locked_print.py

📝 Walkthrough

Walkthrough

The build workflow enables unbuffered Python output. locked_print now queues lines for asynchronous batched writing, drains output during shutdown, and tests verify combined writes and flushing.

Changes

CI output streaming

Layer / File(s) Summary
Queue-based writer lifecycle
ci/util/locked_print.py
locked_print enqueues split lines for a background writer, which batches writes and flushes stdout; shutdown drains queued output before interpreter exit.
Unbuffered build output and validation
.github/workflows/build_template.yml, tests/test_locked_print.py
The build step sets PYTHONUNBUFFERED=1, and tests verify a multiline call produces one combined write and one flush.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant locked_print
  participant PRINT_QUEUE
  participant _write_batches
  participant sys.stdout
  locked_print->>PRINT_QUEUE: enqueue split output lines
  PRINT_QUEUE->>_write_batches: provide queued lines
  _write_batches->>sys.stdout: write joined batch and flush
  _shutdown_writer->>PRINT_QUEUE: enqueue shutdown sentinel
  _write_batches->>sys.stdout: drain accepted output before exit
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: streaming CI build output during long compiles.
Linked Issues check ✅ Passed The changes address #3697 by unbuffering and flushing CI output so the ESP32-S3 build keeps emitting updates.
Out of Scope Changes check ✅ Passed All edits are directly tied to CI output streaming and its regression test, with no unrelated changes.
Docstring Coverage ✅ Passed Docstring coverage is 80.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/3697-unbuffered-build-output

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
tests/test_locked_print.py (1)

30-32: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider renaming the test to reflect batched flushing.

Since the assertions correctly enforce that the multiline string is consolidated into a single combined write and exactly one flush (stream.flush_count == 1), the legacy test name test_locked_print_flushes_each_line (at line 24) is slightly misleading. Consider renaming it to something like test_locked_print_flushes_batches to accurately reflect the batched behavior.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/test_locked_print.py` around lines 30 - 32, Rename the test function
test_locked_print_flushes_each_line to reflect batched flushing, such as
test_locked_print_flushes_batches, while leaving its assertions and behavior
unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@ci/util/locked_print.py`:
- Around line 74-81: Update locked_print to declare an explicit None return type
and enqueue the complete result of string.splitlines() as one queue item rather
than putting each line individually. Preserve the existing shutdown check and
lock-protected behavior.
- Around line 43-69: Update _shutdown_writer to set _SHUTTING_DOWN
unconditionally under PRINT_LOCK before checking whether _WRITER exists, so
concurrent locked_print calls cannot enqueue output after shutdown begins. In
_ensure_writer and shutdown coordination, prevent _shutdown_writer from joining
a Thread object before _WRITER.start() has completed, while preserving draining
and joining for a successfully started writer.
- Around line 9-40: Update _write_batches to treat each queue item as a
list[str] batch, accumulate consumed-task counts while draining, and move all
corresponding task_done() calls into a finally block that runs after the
write/flush attempt. Ensure the finally block marks every consumed item done
even when sys.stdout.write or flush raises, and preserve the stopping sentinel
behavior.

---

Nitpick comments:
In `@tests/test_locked_print.py`:
- Around line 30-32: Rename the test function
test_locked_print_flushes_each_line to reflect batched flushing, such as
test_locked_print_flushes_batches, while leaving its assertions and behavior
unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: fc2aabba-8eb1-4067-abd7-947096c6d23a

📥 Commits

Reviewing files that changed from the base of the PR and between 7e2a0d0 and a59a123.

📒 Files selected for processing (2)
  • ci/util/locked_print.py
  • tests/test_locked_print.py

Comment thread ci/util/locked_print.py Outdated
Comment on lines +9 to +40
_PRINT_QUEUE: Queue[str | None] = Queue(maxsize=_QUEUE_CAPACITY)
_WRITER: Thread | None = None
_WRITER_START_LOCK = Lock()
_SHUTTING_DOWN = False


def _write_batches() -> None:
"""Drain queued lines in batches and flush each batch to the pipe."""
while True:
line = _PRINT_QUEUE.get()
batch: list[str] = []
stopping = line is None
_PRINT_QUEUE.task_done()
if line is not None:
batch.append(line)
while not stopping:
try:
line = _PRINT_QUEUE.get_nowait()
except Empty:
break
try:
if line is None:
stopping = True
else:
batch.append(line)
finally:
_PRINT_QUEUE.task_done()
if batch:
sys.stdout.write("\n".join(batch) + "\n")
sys.stdout.flush()
if stopping:
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🔴 Critical | 🏗️ Heavy lift

Fix premature task_done() and support atomic batching.

There are two critical concurrency issues here:

  1. _PRINT_QUEUE.task_done() is called before the output is written and flushed. This breaks the semantics of Queue.join() used during shutdown, potentially allowing the interpreter to exit before the final batch finishes printing.
  2. If sys.stdout.write raises an exception (e.g., BrokenPipeError), the queue is not drained and _PRINT_QUEUE.join() will hang the shutdown sequence indefinitely.

To solve this (and to prevent flaky partial batches by accepting a full list[str] of lines per queue item—see the corresponding change below for locked_print), track the number of consumed tasks and mark them done inside a finally block after flushing.

🔒️ Proposed fix
-_PRINT_QUEUE: Queue[str | None] = Queue(maxsize=_QUEUE_CAPACITY)
+_PRINT_QUEUE: Queue[list[str] | None] = Queue(maxsize=_QUEUE_CAPACITY)
 _WRITER: Thread | None = None
 _WRITER_START_LOCK = Lock()
 _SHUTTING_DOWN = False
 
 
 def _write_batches() -> None:
     """Drain queued lines in batches and flush each batch to the pipe."""
     while True:
-        line = _PRINT_QUEUE.get()
+        item = _PRINT_QUEUE.get()
         batch: list[str] = []
-        stopping = line is None
-        _PRINT_QUEUE.task_done()
-        if line is not None:
-            batch.append(line)
+        stopping = item is None
+        tasks = 1
+        if item is not None:
+            batch.extend(item)
         while not stopping:
             try:
-                line = _PRINT_QUEUE.get_nowait()
+                item = _PRINT_QUEUE.get_nowait()
             except Empty:
                 break
-            try:
-                if line is None:
-                    stopping = True
-                else:
-                    batch.append(line)
-            finally:
-                _PRINT_QUEUE.task_done()
-        if batch:
-            sys.stdout.write("\n".join(batch) + "\n")
-            sys.stdout.flush()
+            tasks += 1
+            if item is None:
+                stopping = True
+            else:
+                batch.extend(item)
+        try:
+            if batch:
+                sys.stdout.write("\n".join(batch) + "\n")
+                sys.stdout.flush()
+        finally:
+            for _ in range(tasks):
+                _PRINT_QUEUE.task_done()
         if stopping:
             return
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ci/util/locked_print.py` around lines 9 - 40, Update _write_batches to treat
each queue item as a list[str] batch, accumulate consumed-task counts while
draining, and move all corresponding task_done() calls into a finally block that
runs after the write/flush attempt. Ensure the finally block marks every
consumed item done even when sys.stdout.write or flush raises, and preserve the
stopping sentinel behavior.

Comment thread ci/util/locked_print.py
Comment on lines +43 to +69
def _ensure_writer() -> None:
global _WRITER
if _WRITER is not None:
return
with _WRITER_START_LOCK:
if _WRITER is None:
_WRITER = Thread(
target=_write_batches,
name="fastled-build-output",
daemon=True,
)
_WRITER.start()


def _shutdown_writer() -> None:
"""Drain all accepted output before normal interpreter shutdown."""
global _SHUTTING_DOWN
if _WRITER is None:
return
with PRINT_LOCK:
if _SHUTTING_DOWN:
return
_SHUTTING_DOWN = True
_PRINT_QUEUE.put(None)
_PRINT_QUEUE.join()
_WRITER.join()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

Fix shutdown race condition and prevent unstarted thread join() errors.

There are two hazards in the lifecycle management:

  1. Shutdown Race: In _shutdown_writer, returning early if _WRITER is None fails to set _SHUTTING_DOWN = True. If a concurrent locked_print call initializes the writer immediately after this check, it will enqueue output but bypass the atexit join sequence entirely, resulting in truncated logs. _SHUTTING_DOWN must be set unconditionally.
  2. Unstarted Thread Join: In _ensure_writer, assigning _WRITER before the thread starts creates a small window. If _shutdown_writer accesses the unstarted thread and attempts to join() it, Python will raise a RuntimeError ("cannot join thread before it is started").
🛡️ Proposed fix
 def _ensure_writer() -> None:
     global _WRITER
     if _WRITER is not None:
         return
     with _WRITER_START_LOCK:
         if _WRITER is None:
-            _WRITER = Thread(
+            t = Thread(
                 target=_write_batches,
                 name="fastled-build-output",
                 daemon=True,
             )
-            _WRITER.start()
+            t.start()
+            _WRITER = t
 
 
 def _shutdown_writer() -> None:
     """Drain all accepted output before normal interpreter shutdown."""
     global _SHUTTING_DOWN
-    if _WRITER is None:
-        return
     with PRINT_LOCK:
         if _SHUTTING_DOWN:
             return
         _SHUTTING_DOWN = True
+        writer = _WRITER
+        if writer is None:
+            return
         _PRINT_QUEUE.put(None)
     _PRINT_QUEUE.join()
-    _WRITER.join()
+    writer.join()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def _ensure_writer() -> None:
global _WRITER
if _WRITER is not None:
return
with _WRITER_START_LOCK:
if _WRITER is None:
_WRITER = Thread(
target=_write_batches,
name="fastled-build-output",
daemon=True,
)
_WRITER.start()
def _shutdown_writer() -> None:
"""Drain all accepted output before normal interpreter shutdown."""
global _SHUTTING_DOWN
if _WRITER is None:
return
with PRINT_LOCK:
if _SHUTTING_DOWN:
return
_SHUTTING_DOWN = True
_PRINT_QUEUE.put(None)
_PRINT_QUEUE.join()
_WRITER.join()
def _ensure_writer() -> None:
global _WRITER
if _WRITER is not None:
return
with _WRITER_START_LOCK:
if _WRITER is None:
t = Thread(
target=_write_batches,
name="fastled-build-output",
daemon=True,
)
t.start()
_WRITER = t
def _shutdown_writer() -> None:
"""Drain all accepted output before normal interpreter shutdown."""
global _SHUTTING_DOWN
with PRINT_LOCK:
if _SHUTTING_DOWN:
return
_SHUTTING_DOWN = True
writer = _WRITER
if writer is None:
return
_PRINT_QUEUE.put(None)
_PRINT_QUEUE.join()
writer.join()
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ci/util/locked_print.py` around lines 43 - 69, Update _shutdown_writer to set
_SHUTTING_DOWN unconditionally under PRINT_LOCK before checking whether _WRITER
exists, so concurrent locked_print calls cannot enqueue output after shutdown
begins. In _ensure_writer and shutdown coordination, prevent _shutdown_writer
from joining a Thread object before _WRITER.start() has completed, while
preserving draining and joining for a successfully started writer.

Comment thread ci/util/locked_print.py
Comment on lines 74 to +81
def locked_print(string: str):
"""Print with a lock to prevent garbled output for multiple threads."""
"""Queue lines for ordered, flushed, batched output with backpressure."""
_ensure_writer()
with PRINT_LOCK:
# print only prints so much, break up the string into lines
if _SHUTTING_DOWN:
return
for line in string.splitlines():
print(line)
_PRINT_QUEUE.put(line)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Ensure atomic batches and add missing return type annotation.

Two changes are required here:

  1. Enqueuing lines individually inside a loop causes a race condition where the background writer may drain partial strings, breaking the "one flush per call" expectation and causing test flakiness. Push the full list of lines as a single atomic item instead.
  2. The function is missing an explicit return type, which violates coding guidelines. As per coding guidelines, all function return types must have explicit type annotations.
♻️ Proposed fix
-def locked_print(string: str):
+def locked_print(string: str) -> None:
     """Queue lines for ordered, flushed, batched output with backpressure."""
     _ensure_writer()
     with PRINT_LOCK:
         if _SHUTTING_DOWN:
             return
-        for line in string.splitlines():
-            _PRINT_QUEUE.put(line)
+        lines = string.splitlines()
+        if lines:
+            _PRINT_QUEUE.put(lines)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def locked_print(string: str):
"""Print with a lock to prevent garbled output for multiple threads."""
"""Queue lines for ordered, flushed, batched output with backpressure."""
_ensure_writer()
with PRINT_LOCK:
# print only prints so much, break up the string into lines
if _SHUTTING_DOWN:
return
for line in string.splitlines():
print(line)
_PRINT_QUEUE.put(line)
def locked_print(string: str) -> None:
"""Queue lines for ordered, flushed, batched output with backpressure."""
_ensure_writer()
with PRINT_LOCK:
if _SHUTTING_DOWN:
return
lines = string.splitlines()
if lines:
_PRINT_QUEUE.put(lines)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ci/util/locked_print.py` around lines 74 - 81, Update locked_print to declare
an explicit None return type and enqueue the complete result of
string.splitlines() as one queue item rather than putting each line
individually. Preserve the existing shutdown check and lock-protected behavior.

Source: Coding guidelines

@zackees

zackees commented Jul 16, 2026

Copy link
Copy Markdown
Member Author

Updated implementation per review: the bounded queue remains the backpressure boundary, while a semaphore now signals only the idle-to-active transition. The writer drains until the queue is empty, performs one concatenated write/flush per burst, then blocks on the semaphore; shutdown enqueues a sentinel and waits on queue.join(). Focused pytest and Ruff pass.

@zackees
zackees merged commit ce7108e into master Jul 16, 2026
10 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jul 16, 2026
@zackees
zackees deleted the fix/3697-unbuffered-build-output branch August 21, 2026 19:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

ci: ESP32-S3 build workflow can remain in-progress without runner updates

1 participant