-
-
Notifications
You must be signed in to change notification settings - Fork 17
Add single-producer concurrency mode and global panic-capture toggle for high-throughput observables #182
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kosiew
wants to merge
49
commits into
samber:main
Choose a base branch
from
kosiew:performance-benchmark-8
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,997
−56
Open
Add single-producer concurrency mode and global panic-capture toggle for high-throughput observables #182
Changes from all commits
Commits
Show all changes
49 commits
Select commit
Hold shift + click to select a range
554a30a
Add observer panic handling enhancements
kosiew 8222cc6
Add shared panicCaptureGuard for observer tests
kosiew 964fc95
Updated the panic-capture opt-out example to construct the pipeline w…
kosiew 8873a69
Add guardObserverPanicCapture to manage observer state
kosiew 1c49abe
Disable observer panic capture for benchmark setup
kosiew 058ddb2
Refactor panic capture with RWMutex for testing
kosiew 6abd2b2
Add single-producer mode and optimize benchmarks
kosiew 72fd487
Document global panic capture toggle and its impact on performance modes
kosiew 9202bd4
Refactor range logic and add new unit tests
kosiew ce46665
Added three tests:
kosiew 8acff62
Improve comments in observer_test.go for clarity
kosiew ea8774c
Add comment to explain observerPanicCaptureEnabled
kosiew cc14a3a
Add godoc warning to SetCaptureObserverPanics()
kosiew 5280835
Add example for SetCaptureObserverPanics
kosiew 3f51535
Enhance ConcurrencyMode comment clarity
kosiew 5f6a45f
Add test for single-producer with multi-producer operator to demonstr…
kosiew c650a1a
Add test for single-producer context cancellation to verify observer …
kosiew ccb08cc
Add race detection support for operator creation tests
kosiew 02d3592
Refactor observer panic capture to use atomic operations for compatib…
kosiew 59bbc50
Enhance comments for concurrency modes in subscriber implementation t…
kosiew 45ec665
Implement benchmarks for subscriber concurrency modes and panic captu…
kosiew 7780620
Refactor error handling in observer methods to use lo.TryCatchWithErr…
kosiew 8c2d374
Remove BenchmarkSubscriberPanicCapture and unused import for cleaner …
kosiew a707227
Add context-based opt-out for observer panic capture to improve perfo…
kosiew ace0826
Add unsafe observer constructors to improve performance in high-throu…
kosiew c0640ca
Add billion-rows benchmark example with CSV source and fixture expans…
kosiew 42f0c59
perf: per-subscription panic-capture opt-out; add NewObserverUnsafe; …
kosiew 8ce76bd
refactor: remove global panic capture toggle; update tests to use per…
kosiew 3124b04
refactor: remove global panic capture toggle; update documentation to…
kosiew 4c7fae5
docs: update panic capture documentation to emphasize per-subscriptio…
kosiew 72515d3
docs: clarify per-subscription opt-out for panic capture in Observer …
kosiew 1532650
docs: remove reference to global toggle in SubscribeWithContext comments
kosiew d17e7a4
refactor: rename NewObserverUnsafe to NewUnsafeObserver for consistency
kosiew 9af8b11
refactor: optimize panic capture handling and direct call paths in su…
kosiew 3f6db02
Optimize benchmark CSV reading with memory mapping
kosiew b431ef6
lint fix
kosiew 1cabfba
test: add comprehensive tests for observer and subscriber implementat…
kosiew 4211efb
feat: enhance context handling in connectable observable implementation
kosiew f3c1731
refactor: replace lo.TryCatchWithErrorValue with defer-recover patter…
kosiew 23ced5a
refactor: add WithDroppedNotification helper to manage global hook sa…
kosiew 09abdab
test: add note to avoid parallel execution in TestLocklessDroppedNoti…
kosiew 055ae57
lint fix
kosiew d6405ab
refactor: revert panic handling with lo.TryCatchWithErrorValue for im…
kosiew 9a7bbc8
Implement per-subscription wrapper change
kosiew e06ffa7
refactor: optimize panic handling by removing inline defer/recover wr…
kosiew 6992320
lint fix
kosiew 12e3c79
test: add test for subscriber panic propagation with capture=false
kosiew b1cc37a
refactor: replace global error handlers with atomic storage for concu…
kosiew 2aeed5f
refactor: update WithDroppedNotification to use getter/setter for OnD…
kosiew File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| // Copyright 2025 samber. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // https://github.com/samber/ro/blob/main/licenses/LICENSE.apache.md | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| package ro | ||
|
|
||
| import ( | ||
| "context" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| ) | ||
|
|
||
| func TestNewConnectableObservableWithContext(t *testing.T) { | ||
| t.Parallel() | ||
| is := assert.New(t) | ||
|
|
||
| var ctxReceived context.Context | ||
| connectable := NewConnectableObservableWithContext(func(ctx context.Context, destination Observer[int]) Teardown { | ||
| ctxReceived = ctx | ||
| destination.NextWithContext(ctx, 1) | ||
| destination.NextWithContext(ctx, 2) | ||
| destination.NextWithContext(ctx, 3) | ||
| destination.CompleteWithContext(ctx) | ||
| return nil | ||
| }) | ||
|
|
||
| var values []int | ||
| ctx := context.WithValue(context.Background(), testCtxKey, "value") | ||
| sub := connectable.SubscribeWithContext(ctx, NewObserver( | ||
| func(value int) { values = append(values, value) }, | ||
| func(err error) { t.Fatalf("unexpected error: %v", err) }, | ||
| func() {}, | ||
| )) | ||
|
|
||
| // Connect the connectable observable | ||
| connectSub := connectable.Connect() | ||
| connectSub.Wait() | ||
| sub.Wait() | ||
|
|
||
| is.Equal([]int{1, 2, 3}, values) | ||
| is.NotNil(ctxReceived) | ||
| is.Equal("value", ctxReceived.Value(testCtxKey)) | ||
| } | ||
|
|
||
| func TestNewConnectableObservableWithConfigAndContext(t *testing.T) { | ||
| t.Parallel() | ||
| is := assert.New(t) | ||
|
|
||
| var ctxReceived context.Context | ||
| config := ConnectableConfig[int]{ | ||
| Connector: defaultConnector[int], | ||
| ResetOnDisconnect: false, | ||
| } | ||
|
|
||
| connectable := NewConnectableObservableWithConfigAndContext( | ||
| func(ctx context.Context, destination Observer[int]) Teardown { | ||
| ctxReceived = ctx | ||
| destination.NextWithContext(ctx, 1) | ||
| destination.NextWithContext(ctx, 2) | ||
| destination.NextWithContext(ctx, 3) | ||
| destination.CompleteWithContext(ctx) | ||
| return nil | ||
| }, | ||
| config, | ||
| ) | ||
|
|
||
| var values []int | ||
| ctx := context.WithValue(context.Background(), testCtxKey, "value") | ||
| sub := connectable.SubscribeWithContext(ctx, NewObserver( | ||
| func(value int) { values = append(values, value) }, | ||
| func(err error) { t.Fatalf("unexpected error: %v", err) }, | ||
| func() {}, | ||
| )) | ||
|
|
||
| // Connect the connectable observable | ||
| connectSub := connectable.Connect() | ||
| connectSub.Wait() | ||
| sub.Wait() | ||
|
|
||
| is.Equal([]int{1, 2, 3}, values) | ||
| is.NotNil(ctxReceived) | ||
| is.Equal("value", ctxReceived.Value(testCtxKey)) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| # Billion-rows benchmark (example) | ||
|
|
||
| This example contains a benchmark harness that runs a pipeline against a static | ||
| CSV file (one integer per line). It's intended as a reproducible example for | ||
| large-file benchmarks such as the "billion rows" challenge. | ||
|
|
||
| Files | ||
| - `benchmark_test.go`: the benchmark. It expects a static fixture file with | ||
| one integer per line and emits those values through a simple CSV source. | ||
| - `fixtures/sample.csv`: a tiny sample fixture included for CI and quick runs. | ||
| - `scripts/expand_fixture.sh`: simple shell script to expand the small sample | ||
| into a larger fixture by repeating lines. | ||
|
|
||
| How to run | ||
| 1. Use the small sample (fast / CI): | ||
|
|
||
| ```bash | ||
| # from repo root | ||
| go test -run=^$ -bench BenchmarkMillionRowChallenge ./examples/billion-rows-benchmark -benchmem | ||
| ``` | ||
|
|
||
| 2. Use a larger static fixture (recommended for real measurements): | ||
|
|
||
| - Obtain or generate a static CSV where each line is an integer (the 1B | ||
| challenge provides generators). Place it at `examples/billion-rows-benchmark/fixtures/1brc.csv` or set `FIXTURE_PATH`. | ||
|
|
||
| Example to expand the included sample to 1_000_000 lines (quick, not realistic): | ||
|
|
||
| ```bash | ||
| cd examples/billion-rows-benchmark | ||
| mkdir -p fixtures | ||
| ./scripts/expand_fixture.sh fixtures/sample.csv fixtures/1m.csv 1000000 | ||
| export FIXTURE_PATH=$(pwd)/fixtures/1m.csv | ||
| # run the bench (this will still run the benchmark harness, which runs the pipeline once per iteration) | ||
| go test -run=^$ -bench BenchmarkMillionRowChallenge -benchmem | ||
| ``` | ||
|
|
||
| Notes | ||
| - The benchmark accepts `FIXTURE_PATH` environment variable to point to the CSV fixture. If not set, it falls back to `fixtures/sample.csv` included in the example. | ||
| - For the official 1B challenge, follow the instructions in the challenge repository to generate the required static file and set `FIXTURE_PATH` to that file. | ||
| - The benchmark uses the per-subscription helper `ro.WithObserverPanicCaptureDisabled(ctx)` to avoid mutating global state when measuring hot-path performance. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| package benchmark | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "os" | ||
| "path/filepath" | ||
| "strconv" | ||
| "testing" | ||
|
|
||
| "github.com/samber/ro" | ||
| "golang.org/x/exp/mmap" | ||
| ) | ||
|
|
||
| // csvSource creates an Observable that reads int64 values (one per line) | ||
| // from the provided file path. It emits each parsed value and completes. | ||
| // This is intentionally simple: the observable reads the file synchronously | ||
| // on subscribe and emits values to the destination observer. | ||
| func csvSource(path string) ro.Observable[int64] { | ||
| return ro.NewObservableWithContext(func(ctx context.Context, dest ro.Observer[int64]) ro.Teardown { | ||
| reader, err := mmap.Open(path) | ||
| if err != nil { | ||
| dest.Error(err) | ||
| return nil | ||
| } | ||
| defer func() { _ = reader.Close() }() | ||
|
|
||
| size := reader.Len() | ||
| if size == 0 { | ||
| dest.CompleteWithContext(ctx) | ||
| return nil | ||
| } | ||
|
|
||
| data := make([]byte, size) | ||
| if _, err := reader.ReadAt(data, 0); err != nil { | ||
| dest.Error(err) | ||
| return nil | ||
| } | ||
|
|
||
| offset := 0 | ||
| for offset < len(data) { | ||
| next := bytes.IndexByte(data[offset:], '\n') | ||
| var line []byte | ||
| if next == -1 { | ||
| line = data[offset:] | ||
| offset = len(data) | ||
| } else { | ||
| line = data[offset : offset+next] | ||
| offset += next + 1 | ||
| } | ||
|
|
||
| if len(line) > 0 && line[len(line)-1] == '\r' { | ||
| line = line[:len(line)-1] | ||
| } | ||
|
|
||
| v, err := strconv.ParseInt(string(line), 10, 64) | ||
| if err != nil { | ||
| dest.Error(err) | ||
| return nil | ||
| } | ||
|
|
||
| // propagate context-aware notifications | ||
| dest.NextWithContext(ctx, v) | ||
| } | ||
|
|
||
| dest.CompleteWithContext(ctx) | ||
| return nil | ||
| }) | ||
| } | ||
|
|
||
| // Benchmark that runs the "million row" pipeline using a static CSV fixture. | ||
| // The benchmark expects a file with one integer per line. By default it will | ||
| // use the small sample in the fixtures directory. To benchmark a large static | ||
| // dataset, set the FIXTURE_PATH environment variable or place the file at | ||
| // `examples/billion-rows-benchmark/fixtures/1brc.csv`. | ||
| func BenchmarkMillionRowChallenge(b *testing.B) { | ||
| b.ReportAllocs() | ||
|
|
||
| fixture := os.Getenv("FIXTURE_PATH") | ||
| if fixture == "" { | ||
| fixture = filepath.Join("fixtures", "sample.csv") | ||
| } | ||
|
|
||
| // Use per-subscription opt-out of panic capture so the benchmark measures | ||
| // hot-path throughput without mutating global state. | ||
| ctx := ro.WithObserverPanicCaptureDisabled(context.Background()) | ||
|
|
||
| benchmarkCases := []struct { | ||
| name string | ||
| src ro.Observable[int64] | ||
| }{ | ||
| {name: "file-source", src: csvSource(fixture)}, | ||
| } | ||
|
|
||
| for _, tc := range benchmarkCases { | ||
| b.Run(tc.name, func(b *testing.B) { | ||
| pipeline := ro.Pipe3( | ||
| tc.src, | ||
| ro.Map(func(value int64) int64 { return value + 1 }), | ||
| ro.Filter(func(value int64) bool { return value%2 == 0 }), | ||
| ro.Map(func(value int64) int64 { return value * 3 }), | ||
| ) | ||
|
|
||
| b.ResetTimer() | ||
| for i := 0; i < b.N; i++ { | ||
| var sum int64 | ||
|
|
||
| subscription := pipeline.SubscribeWithContext(ctx, ro.NewObserver( | ||
| func(value int64) { sum += value }, | ||
| func(err error) { b.Fatalf("unexpected error: %v", err) }, | ||
| func() {}, | ||
| )) | ||
|
|
||
| subscription.Wait() | ||
|
|
||
| // keep the correctness guard | ||
| _ = sum | ||
| } | ||
| }) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| 1 | ||
| 2 | ||
| 3 | ||
| 4 | ||
| 5 | ||
| 6 | ||
| 7 | ||
| 8 | ||
| 9 | ||
| 10 |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For max speed, the
syscall.Mmapsyscall is recommended 😅There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good call.
direct syscall.Mmap requires OS-specific code and careful unmapping.
Shall I go with x/exp/mmap which provides a simpler ReaderAt wrapper and is cross-platform?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Wow, definitely!
I did not know there was an experimental implementation!