Repository navigation
perf(sidebar): throttle immediate observation publisher to coalesce agent title bursts #6807
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
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
3b24768
perf(sidebar): leading-edge throttle on immediate observation publisher
lawrencecchen 36df8c1
test(sidebar): assert the immediate publisher's synchronous leading-e…
lawrencecchen e68322b
perf(sidebar): synchronous-leading coalesce for immediate observation…
lawrencecchen 8e1a2b6
Merge remote-tracking branch 'origin/main' into feat-sidebar-throttle
lawrencecchen 00ae6fd
sidebar: move merged immediate aggregate into WorkspaceSidebarObserva…
lawrencecchen cee98e4
coalesceLatest: drop stale pending value when an overdue leading emis…
lawrencecchen 0046754
Move coalesceLatest operator into Sources/CoalesceLatestPublisher.swift
lawrencecchen 8dac5f4
Document why CoalesceLatestPublisher and its Inner share one file
lawrencecchen 9de6d4a
Make the overdue-trailing regression test deterministic with a virtua…
lawrencecchen 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,158 @@ | ||
| import Combine | ||
| import Foundation | ||
|
|
||
| // CoalesceLatestPublisher and CoalesceLatestInner are one operator: the | ||
| // Inner is the publisher's subscription and shares its file-private access | ||
| // boundary. Splitting the Inner into its own file would force widening | ||
| // `private` to `internal` for an implementation detail, so the pair | ||
| // intentionally lives in this single file. | ||
|
|
||
| // MARK: - Leading-edge coalescing | ||
|
|
||
| extension Publisher where Failure == Never { | ||
| /// Coalesces bursts while keeping the leading edge synchronous. | ||
| /// | ||
| /// Combine's `throttle` schedules every emission, including the first, | ||
| /// onto the scheduler, so even an isolated value is deferred to the next | ||
| /// run-loop turn and a subscriber never observes a synchronous emission. | ||
| /// The sidebar's immediate observation contract requires the opposite: | ||
| /// the current-state replay a subscriber receives from `@Published` | ||
| /// upstreams, and the first change after an idle period, must both arrive | ||
| /// in the same run-loop turn; only the tail of a burst may be deferred. | ||
| /// | ||
| /// Semantics per subscription: | ||
| /// - The first value (the `@Published` replay of current state) is | ||
| /// forwarded synchronously and does not open a coalesce window, so a | ||
| /// change made right after subscribing is still synchronous. | ||
| /// - A value arriving when no window is open is forwarded synchronously | ||
| /// and opens a window of `interval`. | ||
| /// - Values arriving inside an open window are coalesced: the latest one | ||
| /// is emitted when the window closes (on `scheduler`), which opens the | ||
| /// next window. | ||
| /// | ||
| /// Not thread-safe: intended for main-thread streams with `RunLoop.main`. | ||
| /// Downstream demand is ignored (sink-style subscribers only). | ||
| func coalesceLatest<Context: Scheduler>( | ||
| for interval: Context.SchedulerTimeType.Stride, | ||
| scheduler: Context | ||
| ) -> AnyPublisher<Output, Never> { | ||
| CoalesceLatestPublisher(upstream: self, interval: interval, scheduler: scheduler) | ||
| .eraseToAnyPublisher() | ||
| } | ||
| } | ||
|
|
||
| private struct CoalesceLatestPublisher<Upstream: Publisher, Context: Scheduler>: Publisher | ||
| where Upstream.Failure == Never { | ||
| typealias Output = Upstream.Output | ||
| typealias Failure = Never | ||
|
|
||
| let upstream: Upstream | ||
| let interval: Context.SchedulerTimeType.Stride | ||
| let scheduler: Context | ||
|
|
||
| func receive<S: Subscriber>(subscriber: S) where S.Input == Output, S.Failure == Never { | ||
| upstream.subscribe(CoalesceLatestInner( | ||
| downstream: subscriber, | ||
| interval: interval, | ||
| scheduler: scheduler | ||
| )) | ||
| } | ||
| } | ||
|
|
||
| private final class CoalesceLatestInner<Downstream: Subscriber, Context: Scheduler>: Subscriber, Subscription | ||
| where Downstream.Failure == Never { | ||
| typealias Input = Downstream.Input | ||
| typealias Failure = Never | ||
|
|
||
| private let downstream: Downstream | ||
| private let interval: Context.SchedulerTimeType.Stride | ||
| private let scheduler: Context | ||
| private var upstreamSubscription: Subscription? | ||
| private var hasReceivedReplay = false | ||
| private var windowStart: Context.SchedulerTimeType? | ||
| private var pendingValue: Input? | ||
| private var trailingScheduled = false | ||
| private var isCancelled = false | ||
|
|
||
| init(downstream: Downstream, interval: Context.SchedulerTimeType.Stride, scheduler: Context) { | ||
| self.downstream = downstream | ||
| self.interval = interval | ||
| self.scheduler = scheduler | ||
| } | ||
|
|
||
| func receive(subscription: Subscription) { | ||
| upstreamSubscription = subscription | ||
| downstream.receive(subscription: self) | ||
| subscription.request(.unlimited) | ||
| } | ||
|
|
||
| func receive(_ input: Input) -> Subscribers.Demand { | ||
| guard !isCancelled else { return .none } | ||
| if !hasReceivedReplay { | ||
| hasReceivedReplay = true | ||
| _ = downstream.receive(input) | ||
| return .none | ||
| } | ||
| let now = scheduler.now | ||
| if let start = windowStart, now < start.advanced(by: interval) { | ||
| pendingValue = input | ||
| scheduleTrailingEmission(at: start.advanced(by: interval)) | ||
| } else { | ||
| // If a trailing emission was scheduled but its callback is | ||
| // overdue (main run loop stalled past the deadline), this newer | ||
| // value supersedes the stale pending one; drop it so the late | ||
| // callback cannot emit it out of order after this value. | ||
| pendingValue = nil | ||
| windowStart = now | ||
| _ = downstream.receive(input) | ||
| } | ||
| return .none | ||
| } | ||
|
|
||
| func receive(completion: Subscribers.Completion<Never>) { | ||
| guard !isCancelled else { return } | ||
| if let value = pendingValue { | ||
| pendingValue = nil | ||
| _ = downstream.receive(value) | ||
| } | ||
| downstream.receive(completion: completion) | ||
| } | ||
|
|
||
| private func scheduleTrailingEmission(at deadline: Context.SchedulerTimeType) { | ||
| guard !trailingScheduled else { return } | ||
| trailingScheduled = true | ||
| scheduler.schedule(after: deadline) { [weak self] in | ||
| self?.emitTrailing() | ||
| } | ||
| } | ||
|
|
||
| private func emitTrailing() { | ||
| trailingScheduled = false | ||
| guard !isCancelled, let value = pendingValue else { return } | ||
| // An overdue callback may fire inside a window that a newer leading | ||
| // value opened; hold the pending value until that window's own | ||
| // deadline instead of emitting early. | ||
| if let start = windowStart { | ||
| let deadline = start.advanced(by: interval) | ||
| if scheduler.now < deadline { | ||
| scheduleTrailingEmission(at: deadline) | ||
| return | ||
| } | ||
| } | ||
| pendingValue = nil | ||
| windowStart = scheduler.now | ||
| _ = downstream.receive(value) | ||
| } | ||
|
|
||
| func request(_ demand: Subscribers.Demand) { | ||
| // Downstream demand is intentionally ignored; this operator backs | ||
| // sink-style Void observation streams with unlimited demand. | ||
| } | ||
|
|
||
| func cancel() { | ||
| isCancelled = true | ||
| pendingValue = nil | ||
| upstreamSubscription?.cancel() | ||
| upstreamSubscription = nil | ||
| } | ||
| } | ||
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
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.
P2:
receive(subscription:)unconditionally requests.unlimitedfrom upstream after callingdownstream.receive(subscription:). If the downstream synchronously cancels during that call, the upstream subscription is cancelled andisCancelledis set, yet the method still requests demand on the now-cancelled subscription. Adding aguard !isCancelled else { return }beforesubscription.request(.unlimited)respects the cancellation and avoids driving unnecessary upstream work.Prompt for AI agents