Skip to content

test: Measure performance of writing Singer stream to stdout#3673

Draft
edgarrmondragon wants to merge 2 commits into
mainfrom
test/measure-perf-singer-stream-write
Draft

test: Measure performance of writing Singer stream to stdout#3673
edgarrmondragon wants to merge 2 commits into
mainfrom
test/measure-perf-singer-stream-write

Conversation

@edgarrmondragon

@edgarrmondragon edgarrmondragon commented Jun 10, 2026

Copy link
Copy Markdown
Collaborator

We currently measure the performance of formatting a message for stdout, but we don't measure the cost of writing individual messages.

Summary by Sourcery

Add performance benchmarks for writing Singer messages to stdout using different writers and message patterns.

Tests:

  • Add benchmarks for SimpleSingerWriter writing repeated record messages to stdout.
  • Add benchmarks for MsgSpecWriter writing repeated record messages to stdout with real flush calls.
  • Add benchmark for SimpleSingerWriter writing a realistic sequence of schema, record, and state messages to stdout.

@edgarrmondragon edgarrmondragon self-assigned this Jun 10, 2026
@sourcery-ai

sourcery-ai Bot commented Jun 10, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Adds pytest benchmarks that measure the throughput of writing Singer messages to stdout for different writer implementations and message mixes, including setup fixtures for schema and state messages and realistic stdout redirection to /dev/null so flush syscalls are exercised.

File-Level Changes

Change Details Files
Introduce fixtures for reusable schema and state benchmark messages.
  • Add bench_schema_message fixture returning a SchemaMessage with representative user-like schema and key properties.
  • Add bench_state_message fixture returning a StateMessage with a bookmarks-style payload.
tests/benchmarks/test_io.py
Add benchmark for SimpleSingerWriter writing many record messages to stdout with real flush calls.
  • Instantiate SimpleSingerWriter and repeatedly write the same RecordMessage a fixed number of times.
  • Redirect sys.stdout to a text /dev/null handle within a context manager to ensure flush performs real syscalls.
  • Wrap the write loop in a nested run() function passed to pytest benchmark.
tests/benchmarks/test_io.py
Add benchmark for MsgSpecWriter writing many record messages to stdout using a binary stdout surrogate.
  • Instantiate MsgSpecWriter and repeatedly write the same RecordMessage a fixed number of times.
  • Create a binary /dev/null file object and a lightweight stdout surrogate exposing a buffer attribute and flush method.
  • Temporarily assign the surrogate to sys.stdout, execute the benchmarked write loop, then restore stdout and close the file.
tests/benchmarks/test_io.py
Add benchmark for SimpleSingerWriter writing a realistic schema→records→state message sequence to stdout.
  • Instantiate SimpleSingerWriter and benchmark a run that writes one schema message, many record messages, then one state message.
  • Use the new schema and state fixtures alongside the existing record fixture.
  • Redirect sys.stdout to /dev/null within a context manager during the benchmark and restore it afterward.
tests/benchmarks/test_io.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@edgarrmondragon edgarrmondragon marked this pull request as draft June 10, 2026 22:19

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hey - I've found 1 issue, and left some high level feedback:

  • The manual stdout monkeypatching is repeated across benchmarks; consider extracting a small helper/context manager to redirect stdout to /dev/null so the setup/teardown is less error-prone and easier to reuse.
  • In the MsgSpecWriter benchmark, _DevNullStdout only exposes buffer and flush; if any future code calls write on stdout this will break unexpectedly, so adding a no-op write method (or using contextlib.redirect_stdout around a binary wrapper) would make the fake stdout more robust.
  • For devnull_b, using a with statement instead of manually opening and closing the file would simplify resource management and avoid potential leaks if the benchmark body is modified in the future.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The manual stdout monkeypatching is repeated across benchmarks; consider extracting a small helper/context manager to redirect stdout to /dev/null so the setup/teardown is less error-prone and easier to reuse.
- In the MsgSpecWriter benchmark, `_DevNullStdout` only exposes `buffer` and `flush`; if any future code calls `write` on stdout this will break unexpectedly, so adding a no-op `write` method (or using `contextlib.redirect_stdout` around a binary wrapper) would make the fake stdout more robust.
- For `devnull_b`, using a `with` statement instead of manually opening and closing the file would simplify resource management and avoid potential leaks if the benchmark body is modified in the future.

## Individual Comments

### Comment 1
<location path="tests/benchmarks/test_io.py" line_range="136-158" />
<code_context>
+    writer = MsgSpecWriter()
+    number_of_runs = 1000
+
+    devnull_b = open(os.devnull, "wb")  # noqa: PTH123, SIM115
+
+    class _DevNullStdout:
+        buffer = devnull_b
+
+        def flush(self) -> None:
+            devnull_b.flush()
+
+    old_stdout = sys.stdout
+    sys.stdout = _DevNullStdout()  # type: ignore[assignment]
+    try:
+
+        def run():
+            for record in itertools.repeat(bench_record_message, number_of_runs):
+                writer.write_message(record)
+
+        benchmark(run)
+    finally:
+        sys.stdout = old_stdout
+        devnull_b.close()
+
+
</code_context>
<issue_to_address>
**suggestion (testing):** Make the MsgSpecWriter benchmark stdout stub more faithful to real sys.stdout by adding a write method.

`_DevNullStdout` currently only exposes `buffer` and `flush()`. If `MsgSpecWriter` ever starts calling `sys.stdout.write(...)`, this benchmark will fail even though real `sys.stdout` supports that. Please add a `write(self, data: str) -> int` method (e.g. forwarding to `devnull_b.write(data.encode(...))` or a no-op that returns `len(data)`) so the stub more accurately matches `sys.stdout` and avoids brittle failures.

```suggestion
    writer = MsgSpecWriter()
    number_of_runs = 1000

    devnull_b = open(os.devnull, "wb")  # noqa: PTH123, SIM115

    class _DevNullStdout:
        buffer = devnull_b

        def write(self, data: str) -> int:
            """Mimic TextIOBase.write, discarding data like /dev/null."""
            return len(data)

        def flush(self) -> None:
            devnull_b.flush()

    old_stdout = sys.stdout
    sys.stdout = _DevNullStdout()  # type: ignore[assignment]
    try:

        def run():
            for record in itertools.repeat(bench_record_message, number_of_runs):
                writer.write_message(record)

        benchmark(run)
    finally:
        sys.stdout = old_stdout
        devnull_b.close()
```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread tests/benchmarks/test_io.py
@codecov

codecov Bot commented Jun 10, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.12%. Comparing base (787800b) to head (f2b5a3e).
⚠️ Report is 17 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #3673   +/-   ##
=======================================
  Coverage   94.12%   94.12%           
=======================================
  Files          73       73           
  Lines        6200     6200           
  Branches      762      762           
=======================================
  Hits         5836     5836           
  Misses        270      270           
  Partials       94       94           
Flag Coverage Δ
core 82.95% <ø> (ø)
end-to-end 76.03% <ø> (ø)
optional-components 44.82% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@codspeed-hq

codspeed-hq Bot commented Jun 10, 2026

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 8 untouched benchmarks
🆕 3 new benchmarks

Performance Changes

Benchmark BASE HEAD Efficiency
🆕 test_bench_write_mixed_messages_simple N/A 5.6 ms N/A
🆕 test_bench_write_record_messages_msgspec N/A 7.2 ms N/A
🆕 test_bench_write_record_messages_simple N/A 52.7 ms N/A

Comparing test/measure-perf-singer-stream-write (f2b5a3e) with main (787800b)

Open in CodSpeed

@edgarrmondragon edgarrmondragon marked this pull request as ready for review June 10, 2026 22:26
@edgarrmondragon edgarrmondragon marked this pull request as draft June 11, 2026 05:18
edgarrmondragon and others added 2 commits June 15, 2026 19:28
We currently measure the performance of _formatting_ a message for
stdout, but we don't measure the cost of writing individual messages.

Signed-off-by: Edgar Ramírez Mondragón <edgarrm358@gmail.com>
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
@edgarrmondragon edgarrmondragon force-pushed the test/measure-perf-singer-stream-write branch from 358e96f to f2b5a3e Compare June 16, 2026 01:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant