Repository navigation
fix(ci): stream build output during long compiles - #3702
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughThe build workflow enables unbuffered Python output. ChangesCI output streaming
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
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
tests/test_locked_print.py (1)
30-32: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider 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 nametest_locked_print_flushes_each_line(at line 24) is slightly misleading. Consider renaming it to something liketest_locked_print_flushes_batchesto 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
📒 Files selected for processing (2)
ci/util/locked_print.pytests/test_locked_print.py
| _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 |
There was a problem hiding this comment.
🩺 Stability & Availability | 🔴 Critical | 🏗️ Heavy lift
Fix premature task_done() and support atomic batching.
There are two critical concurrency issues here:
_PRINT_QUEUE.task_done()is called before the output is written and flushed. This breaks the semantics ofQueue.join()used during shutdown, potentially allowing the interpreter to exit before the final batch finishes printing.- If
sys.stdout.writeraises 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.
| 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() | ||
|
|
There was a problem hiding this comment.
🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win
Fix shutdown race condition and prevent unstarted thread join() errors.
There are two hazards in the lifecycle management:
- Shutdown Race: In
_shutdown_writer, returning early if_WRITERisNonefails to set_SHUTTING_DOWN = True. If a concurrentlocked_printcall initializes the writer immediately after this check, it will enqueue output but bypass theatexitjoin sequence entirely, resulting in truncated logs._SHUTTING_DOWNmust be set unconditionally. - Unstarted Thread Join: In
_ensure_writer, assigning_WRITERbefore the thread starts creates a small window. If_shutdown_writeraccesses the unstarted thread and attempts tojoin()it, Python will raise aRuntimeError("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.
| 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.
| 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) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Ensure atomic batches and add missing return type annotation.
Two changes are required here:
- 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.
- 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.
| 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
|
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. |
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
Tests