Repository navigation
[core] Support actor level backpressure config - #63310
Conversation
Signed-off-by: sampan <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request implements actor-wide backpressure for streaming generators, enabling a shared cap on unconsumed objects across concurrent tasks. It introduces the _actor_generator_backpressure_num_objects option and the ActorWideGeneratorBackpressureWaiter class to manage the shared budget. Changes include updates to task specifications, core worker logic, and Cython bindings, along with new tests. Review feedback suggests making TeardownTask idempotent to prevent incorrect unconsumed counts if called multiple times.
| void ActorWideGeneratorBackpressureWaiter::TeardownTask( | ||
| ActorTaskBackpressureMetadata &metadata) { | ||
| absl::MutexLock lock(&mutex_); | ||
| metadata.task_alive = false; |
There was a problem hiding this comment.
The TeardownTask method is not idempotent. If it is called multiple times (for example, once manually and once during the destruction of the StreamingGeneratorExecutionContext object), it will decrement total_objects_generated_ multiple times. This would lead to an inconsistent state where the actor-wide unconsumed count is incorrect, potentially allowing more objects than the configured cap. A check for metadata.task_alive should be added to ensure the teardown logic only executes once.
void ActorWideGeneratorBackpressureWaiter::TeardownTask(
ActorTaskBackpressureMetadata &metadata) {
absl::MutexLock lock(&mutex_);
if (!metadata.task_alive) {
return;
}
metadata.task_alive = false;Signed-off-by: sampan <[email protected]>
Signed-off-by: sampan <[email protected]>
Signed-off-by: sampan <[email protected]>
Signed-off-by: sampan <[email protected]>
Signed-off-by: sampan <[email protected]>
Signed-off-by: sampan <[email protected]>
Signed-off-by: sampan <[email protected]>
Signed-off-by: sampan <[email protected]>
|
This pull request has been automatically marked as stale because it has not had You can always ask for help on our discussion forum or Ray's public slack channel. If you'd like to keep this open, just leave any comment, and the stale label will be removed. |
|
Hi @sampan-s-nayak, would you mind rebase this PR? |
| int64 total_num_object_consumed = 1; | ||
| } | ||
|
|
||
| message UpdateGeneratorBackpressureConsumedRequest { |
There was a problem hiding this comment.
Do we really need a new RPC for reporting consumption?
The implementation in this PR will send UpdateGeneratorBackpressureConsumedRequest once the caller reads a ref from the generator, while the old implementation could also send a ReportGeneratorItemReturnsReply at that time.
The difference is that ReportGeneratorItemReturnsReply can be sent right away in the HandleReportGeneratorItemReturns handler if there is no task-level backpressure, but I think we just need to always delay the response in case of actor-level backpressure.
There was a problem hiding this comment.
I was previously using just ReportGeneratorItemReturnsReply and delaying replies. the problem with this approach is that a generator is not marked as completed until all ReportGeneratorItemReturnsReply calls have been made. so with actor level bp it can lead to situations where there is enough slots but new tasks are blocked because current task has not been marked as executed.
look at test_actor_generator_backpressure_task_completes_before_consumed test for an example where things would fail to be optimal. until the first generator is fully consumed no new task would be allowed to run despite there being less than backpressure number of outputs
There was a problem hiding this comment.
I get your point, but to be honest, I am not sure if it is worth introducing a new PRC for this optimization. The existing per-stream backpressure has the same behavior that marks the generator as completed after it is drained. Is it a current bottleneck?
test_actor_generator_backpressure_task_completes_before_consumed looks a bit weird to me, actually. As a user, g2 being blocked under max_concurrency=1 is much more expected to me, given that g1 is not drained. If I want to guarantee that g2 is not blocked, I would just use max_concurrency=2.
There was a problem hiding this comment.
The existing per-stream backpressure has the same behavior that marks the generator as completed after it is drained.
not really, with _generator_backpressure_num_objects we dont really block completion on the backpressure.
Example 1
import ray
ray.init()
@ray.remote
class tracker:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
return self.count
def get_count(self):
return self.count
def wait_count(n):
while ray.get(t.get_count.remote()) < n:
time.sleep(0.01)
@ray.remote
class test:
def method(self):
for i in range(10):
yield i
print("done!")
a = test.remote()
t = tracker.remote()
g1 = a.method.options(_generator_backpressure_num_objects=11).remote(t)
g2 = a.method.options(_generator_backpressure_num_objects=11).remote(t)
wait_count(19)
output
2026-06-16 09:23:47,903 INFO worker.py:2024 -- Started a local Ray instance.
(test pid=1273626) done!
(test pid=1273626) done!Example 2:
import ray
import time
ray.init(include_dashboard=False)
@ray.remote
class tracker:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
return self.count
def get_count(self):
return self.count
@ray.remote
class test:
def method(self, tracker):
for i in range(6):
ray.get(tracker.increment.remote())
yield i
print("done!")
a = test.remote()
t = tracker.remote()
g1 = a.method.options(_generator_backpressure_num_objects=5).remote(t)
g2 = a.method.options(_generator_backpressure_num_objects=5).remote(t)
def wait_count(n):
while ray.get(t.get_count.remote()) < n:
time.sleep(0.01)
wait_count(4)
print(ray.get(next(g1)))
print(ray.get(next(g1))) # consume one → unblocks generator to produce more
wait_count(10)
output:
2026-06-16 09:45:25,183 INFO worker.py:2024 -- Started a local Ray instance.
0
1
(test pid=1279827) done!in example 1 none of the yields were consumed, but the stream completed and next one ran
in example 2, we only consumed 2 yields and the stream completed and blocked on the next stream
There was a problem hiding this comment.
the reason is because in https://github.com/ray-project/ray/blob/master/src/ray/core_worker/task_manager.cc#L658-L671 we delay the ref_stream_execution_signal_callbacks_ until the num_unconsumed < backpressure_threshold.
in example 1 we are producing only 10 items while threshold was 11
and in example 2 we first produce 5 and stop, then read one -> new item is produced. read one more we reached end of stream so task needs to be marked as completed, we no longer care about the backpressure on the executor side once we get all reply callbacks the task is marked as completed.
There was a problem hiding this comment.
looks a bit weird to me, actually. As a user, g2 being blocked under max_concurrency=1 is much more expected to me, given that g1 is not drained. If I want to guarantee that g2 is not blocked, I would just use max_concurrency=2
for actor level backpressure I feel allowing the next task to run when we havent yet met the backpressure threshold makes more sense even when max_concurrency=1 as the backpressure only tells you how many streaming gen objects the actor can produce at any given time (at actor level not the individual task level) and not the per generator output limit (that is what _generator_backpressure_num_objects tries to solve)
also this difference (of having to consume all objects before marking a stream as executed) lead to perf degradations when testing on a ray data workload as _generator_backpressure_num_objects today does not have this limitation.
There was a problem hiding this comment.
ok, if this improves the perf then let's go.
There was a problem hiding this comment.
@rueian @sampan-s-nayak Hi we observe significant performance regression caused by the newly introduced RPC UpdateGeneratorBackpressureConsumedRequest. The new RPC invocation occupy nearly 25% of the ray data driver flame graph, as a result, ray data task dispatch rate decrease by around 30%. Attached is the flame graph. I wonder if there is a way you can optimize this behavior.

There was a problem hiding this comment.
only reason I can think of for this to happen is because previously we did not make ReportGeneratorItemReturns everytime an item was consumed but now we do (UpdateGeneratorBackpressureConsumed is called every time an item is read from the stream).
I am thinking that we can either:
- move these callbacks into the io_service so that the impact is no longer on the python thread
- bring back logic of witholding in case of task level bp while keeping the per read callback for actor level bp (feels a little complex and can make code hard to read, personally I prefer the first option)
There was a problem hiding this comment.
@chaoqin-li1123 raised a prototype pr for the first approach #67160. could you try once with this branch or share the script you are running?
…ssure Signed-off-by: sampan <[email protected]> # Conflicts: # python/ray/_raylet.pyx # python/ray/actor.py # src/ray/common/task/task_spec.cc # src/ray/common/task/task_spec.h # src/ray/common/task/task_util.h # src/ray/core_worker/actor_management/actor_handle.cc # src/ray/core_worker/core_worker.cc # src/ray/core_worker/generator_waiter.cc # src/ray/core_worker/generator_waiter.h # src/ray/core_worker/task_manager.cc # src/ray/protobuf/common.proto
|
We need a patch to support the newly added diff --git a/python/ray/_raylet.pyx b/python/ray/_raylet.pyx
index 0da92c38a7..412f0f8281 100644
--- a/python/ray/_raylet.pyx
+++ b/python/ray/_raylet.pyx
@@ -1349,17 +1349,20 @@ cdef report_streaming_generator_exception(
def _reserve_actor_generator_slot(
StreamingGeneratorExecutionContext context):
- """Block (with the GIL released) until the actor-wide generator backpressure budget admits another object."""
- cdef CRayStatus status
+ """Block (with the GIL released) until the actor-wide generator backpressure budget admits the next yield's objects."""
+ cdef:
+ CRayStatus status
+ int64_t num_objects = context.num_objects_per_yield
with nogil:
- status = context.actor_backpressure_metadata.get().ReserveSlot()
+ status = context.actor_backpressure_metadata.get().ReserveSlot(num_objects)
check_status(status)
def _release_actor_generator_slot(
StreamingGeneratorExecutionContext context):
+ cdef int64_t num_objects = context.num_objects_per_yield
with nogil:
- context.actor_backpressure_metadata.get().ReleaseSlot()
+ context.actor_backpressure_metadata.get().ReleaseSlot(num_objects)
cdef execute_streaming_generator_sync(StreamingGeneratorExecutionContext context):
@@ -1395,8 +1398,9 @@ cdef execute_streaming_generator_sync(StreamingGeneratorExecutionContext context
while True:
try:
# Actor-wide backpressure pre-check. Block (releasing the
- # GIL) until the actor's shared budget admits another
- # object. No-op when the actor option is disabled.
+ # GIL) until the actor's shared budget admits this yield's
+ # objects (`_num_objects_per_yield`). No-op when the actor
+ # option is disabled.
if context.actor_backpressure_metadata.get() != NULL:
_reserve_actor_generator_slot(context)
# Send object serialization duration to the generator and retrieve
diff --git a/python/ray/includes/libcoreworker.pxd b/python/ray/includes/libcoreworker.pxd
index ce80843f9d..6dd73371e9 100644
--- a/python/ray/includes/libcoreworker.pxd
+++ b/python/ray/includes/libcoreworker.pxd
@@ -111,8 +111,8 @@ cdef extern from "ray/core_worker/generator_waiter.h" nogil:
cdef cppclass CActorTaskBackpressureMetadata "ray::core::ActorTaskBackpressureMetadata": # noqa
CActorTaskBackpressureMetadata(
shared_ptr[CActorWideGeneratorBackpressureWaiter] actor_waiter)
- CRayStatus ReserveSlot()
- void ReleaseSlot()
+ CRayStatus ReserveSlot(int64_t num_objects)
+ void ReleaseSlot(int64_t num_objects)
void OnReport(int64_t total)
void Teardown()
diff --git a/python/ray/tests/test_streaming_generator_backpressure.py b/python/ray/tests/test_streaming_generator_backpressure.py
index d9460ee5e1..bfc1b9538a 100644
--- a/python/ray/tests/test_streaming_generator_backpressure.py
+++ b/python/ray/tests/test_streaming_generator_backpressure.py
@@ -505,6 +505,45 @@ def test_actor_generator_backpressure_task_completes_before_consumed(shutdown_on
_drain_all([g1, g2, g3])
+def test_actor_generator_backpressure_num_objects_per_yield(shutdown_only):
+ """Actor-wide cap counts objects, not yields, when ``_num_objects_per_yield`` > 1."""
+ ray.init(num_cpus=2)
+ reporter = TagReporter.remote()
+
+ # Cap of 4 objects with 2 objects per yield admits at most 2 yields (4
+ # objects) before parking. With the (buggy) per-yield accounting the cap
+ # would instead admit 4 yields (8 objects) before parking.
+ @ray.remote(_actor_generator_backpressure_num_objects=4)
+ class A:
+ @ray.method(_num_objects_per_yield=2)
+ def gen(self, rep, tag):
+ for i in range(5):
+ ray.get(rep.report.remote(tag, i))
+ yield i, i
+
+ a = A.remote()
+ g = a.gen.remote(reporter, "a")
+
+ # Exactly two yields (= 4 objects) fill the cap, then the producer parks.
+ wait_for_condition(
+ lambda: ray.get(reporter.count_tag.remote("a")) == 2,
+ timeout=_ACTOR_GEN_BP_WAIT_S,
+ )
+ time.sleep(1)
+ assert ray.get(reporter.count_tag.remote("a")) == 2
+
+ # Consuming a ref frees budget below the cap and admits one more yield.
+ ray.get(next(g))
+ wait_for_condition(
+ lambda: ray.get(reporter.count_tag.remote("a")) == 3,
+ timeout=_ACTOR_GEN_BP_WAIT_S,
+ )
+
+ # Draining the rest lets the generator run to completion (5 yields total).
+ _drain_all([g])
+ assert ray.get(reporter.count_tag.remote("a")) == 5
+
+
def test_actor_generator_backpressure_mt_actor(shutdown_only):
"""Two concurrent sync generator tasks; actor-wide cap 6; reclaim on drain."""
ray.init(num_cpus=4)
diff --git a/src/mock/ray/rpc/worker/core_worker_client.h b/src/mock/ray/rpc/worker/core_worker_client.h
index 1a27df6465..149cea93ad 100644
--- a/src/mock/ray/rpc/worker/core_worker_client.h
+++ b/src/mock/ray/rpc/worker/core_worker_client.h
@@ -130,6 +130,11 @@ class MockCoreWorkerClientInterface : public CoreWorkerClientInterface {
(ReportGeneratorItemReturnsRequest && request,
const ClientCallback<ReportGeneratorItemReturnsReply> &callback),
(override));
+ MOCK_METHOD(void,
+ UpdateGeneratorBackpressureConsumed,
+ (UpdateGeneratorBackpressureConsumedRequest && request,
+ const ClientCallback<UpdateGeneratorBackpressureConsumedReply> &callback),
+ (override));
MOCK_METHOD(void,
RegisterMutableObjectReader,
(const RegisterMutableObjectReaderRequest &request,
diff --git a/src/ray/core_worker/generator_waiter.cc b/src/ray/core_worker/generator_waiter.cc
index d54f755420..aa9435761b 100644
--- a/src/ray/core_worker/generator_waiter.cc
+++ b/src/ray/core_worker/generator_waiter.cc
@@ -120,8 +120,12 @@ ActorWideGeneratorBackpressureWaiter::ActorWideGeneratorBackpressureWaiter(
}
Status ActorWideGeneratorBackpressureWaiter::ReserveActorWideSlot(
- ActorTaskBackpressureMetadata &metadata) {
+ ActorTaskBackpressureMetadata &metadata, int64_t num_objects) {
absl::MutexLock lock(&mutex_);
+ // Wait until the shared budget is below the cap, then admit the whole group
+ // of `num_objects`. A single group is admitted even if it overshoots the cap
+ // (mirrors the per-task waiter, which reports a full grouped yield before
+ // blocking); otherwise a group larger than the cap could never make progress.
while (metadata.task_alive &&
total_objects_generated_ - total_objects_consumed_ >= backpressure_threshold_) {
backpressure_cond_var_.WaitWithTimeout(&mutex_, absl::Seconds(1));
@@ -133,19 +137,24 @@ Status ActorWideGeneratorBackpressureWaiter::ReserveActorWideSlot(
if (!metadata.task_alive) {
return Status::OK();
}
- total_objects_generated_ += 1;
- metadata.per_task_generated += 1;
+ total_objects_generated_ += num_objects;
+ metadata.per_task_generated += num_objects;
return Status::OK();
}
void ActorWideGeneratorBackpressureWaiter::ReleaseActorWideSlot(
- ActorTaskBackpressureMetadata &metadata) {
+ ActorTaskBackpressureMetadata &metadata, int64_t num_objects) {
absl::MutexLock lock(&mutex_);
- if (!metadata.task_alive || metadata.per_task_generated <= metadata.per_task_consumed) {
+ if (!metadata.task_alive) {
+ return;
+ }
+ const int64_t releasable =
+ std::min(num_objects, metadata.per_task_generated - metadata.per_task_consumed);
+ if (releasable <= 0) {
return;
}
- metadata.per_task_generated -= 1;
- total_objects_generated_ -= 1;
+ metadata.per_task_generated -= releasable;
+ total_objects_generated_ -= releasable;
if (total_objects_generated_ - total_objects_consumed_ < backpressure_threshold_) {
backpressure_cond_var_.SignalAll();
}
@@ -157,8 +166,9 @@ void ActorWideGeneratorBackpressureWaiter::OnConsumedForTask(
if (!metadata.task_alive) {
return;
}
- // per_task_generated counts ReserveActorWideSlot admissions only; reported
- // totals may not line up (e.g. substitute values on RPC failure).
+ // per_task_generated counts ReserveActorWideSlot admissions in object units
+ // (matching the owner-reported consumed total); reported totals may still not
+ // line up (e.g. substitute values on RPC failure), so clamp to what we admitted.
const int64_t clamped_total = std::min(total, metadata.per_task_generated);
int64_t delta = clamped_total - metadata.per_task_consumed;
if (delta <= 0) {
@@ -197,12 +207,12 @@ int64_t ActorWideGeneratorBackpressureWaiter::TotalObjectGenerated() const {
return total_objects_generated_;
}
-Status ActorTaskBackpressureMetadata::ReserveSlot() {
- return actor_waiter->ReserveActorWideSlot(*this);
+Status ActorTaskBackpressureMetadata::ReserveSlot(int64_t num_objects) {
+ return actor_waiter->ReserveActorWideSlot(*this, num_objects);
}
-void ActorTaskBackpressureMetadata::ReleaseSlot() {
- actor_waiter->ReleaseActorWideSlot(*this);
+void ActorTaskBackpressureMetadata::ReleaseSlot(int64_t num_objects) {
+ actor_waiter->ReleaseActorWideSlot(*this, num_objects);
}
void ActorTaskBackpressureMetadata::OnConsumed(int64_t total) {
diff --git a/src/ray/core_worker/generator_waiter.h b/src/ray/core_worker/generator_waiter.h
index 0c8f01fb38..94664def44 100644
--- a/src/ray/core_worker/generator_waiter.h
+++ b/src/ray/core_worker/generator_waiter.h
@@ -43,8 +43,11 @@ struct ActorTaskBackpressureMetadata {
: actor_waiter(std::move(w)) {}
// Thin forwarders for Cython and RPC callbacks.
- Status ReserveSlot();
- void ReleaseSlot();
+ // num_objects is the number of objects the yield produces
+ // (`_num_objects_per_yield`), so a grouped yield reserves/releases its whole
+ // group of objects against the actor-wide budget.
+ Status ReserveSlot(int64_t num_objects = 1);
+ void ReleaseSlot(int64_t num_objects = 1);
void OnConsumed(int64_t total);
void Teardown();
};
@@ -91,8 +94,13 @@ class ActorWideGeneratorBackpressureWaiter {
ActorWideGeneratorBackpressureWaiter(int64_t actor_cap,
std::function<Status()> check_signals);
- Status ReserveActorWideSlot(ActorTaskBackpressureMetadata &metadata);
- void ReleaseActorWideSlot(ActorTaskBackpressureMetadata &metadata);
+ // num_objects is the number of objects admitted/reclaimed in one call so the
+ // actor-wide budget is accounted in object units even when a single yield
+ // produces multiple objects (`_num_objects_per_yield` > 1).
+ Status ReserveActorWideSlot(ActorTaskBackpressureMetadata &metadata,
+ int64_t num_objects = 1);
+ void ReleaseActorWideSlot(ActorTaskBackpressureMetadata &metadata,
+ int64_t num_objects = 1);
void OnConsumedForTask(ActorTaskBackpressureMetadata &metadata, int64_t total);
void TeardownTask(ActorTaskBackpressureMetadata &metadata);
diff --git a/src/ray/core_worker/tests/generator_waiter_test.cc b/src/ray/core_worker/tests/generator_waiter_test.cc
index 0756139650..8cf026017c 100644
--- a/src/ray/core_worker/tests/generator_waiter_test.cc
+++ b/src/ray/core_worker/tests/generator_waiter_test.cc
@@ -183,6 +183,63 @@ TEST(GeneratorWaiterTest, ReserveActorWideSlotBlocksAndAtomicallyIncrements) {
ASSERT_EQ(md.per_task_consumed, 1);
}
+TEST(GeneratorWaiterTest, ReserveActorWideSlotAccountsGroupedYieldsInObjectUnits) {
+ // The cap and the owner-reported consumed totals are both in object units, so
+ // a grouped yield (`_num_objects_per_yield` > 1) must reserve all of its
+ // objects against the actor-wide budget, not just one.
+ constexpr int64_t kPerYield = 3;
+ auto waiter = std::make_shared<ActorWideGeneratorBackpressureWaiter>(
+ 2 * kPerYield, []() { return Status::OK(); });
+ ActorTaskBackpressureMetadata md(waiter);
+
+ // Each grouped yield admits its whole group of objects.
+ ASSERT_TRUE(waiter->ReserveActorWideSlot(md, kPerYield).ok());
+ ASSERT_EQ(md.per_task_generated, kPerYield);
+ ASSERT_EQ(waiter->TotalObjectGenerated(), kPerYield);
+
+ ASSERT_TRUE(waiter->ReserveActorWideSlot(md, kPerYield).ok());
+ ASSERT_EQ(waiter->TotalObjectGenerated(), 2 * kPerYield);
+
+ // The budget is now full (2 * kPerYield objects); the next group blocks.
+ std::atomic<bool> third_done(false);
+ std::thread t([&] {
+ ASSERT_TRUE(waiter->ReserveActorWideSlot(md, kPerYield).ok());
+ third_done = true;
+ });
+ absl::SleepFor(absl::Milliseconds(50));
+ ASSERT_FALSE(third_done.load());
+
+ // Consuming objects (in object units) frees budget below the cap and unblocks.
+ waiter->OnConsumedForTask(md, kPerYield);
+ ASSERT_EQ(md.per_task_consumed, kPerYield);
+ t.join();
+ ASSERT_TRUE(third_done.load());
+ ASSERT_EQ(waiter->TotalObjectGenerated(), 3 * kPerYield);
+}
+
+TEST(GeneratorWaiterTest, ReleaseActorWideSlotReclaimsWholeGroup) {
+ // On StopIteration the pre-reserved group produced no objects, so the whole
+ // reserved group must be reclaimed.
+ constexpr int64_t kPerYield = 3;
+ auto waiter = std::make_shared<ActorWideGeneratorBackpressureWaiter>(
+ 2 * kPerYield, []() { return Status::OK(); });
+ ActorTaskBackpressureMetadata md(waiter);
+
+ ASSERT_TRUE(waiter->ReserveActorWideSlot(md, kPerYield).ok());
+ ASSERT_TRUE(waiter->ReserveActorWideSlot(md, kPerYield).ok());
+ ASSERT_EQ(waiter->TotalObjectGenerated(), 2 * kPerYield);
+
+ waiter->ReleaseActorWideSlot(md, kPerYield);
+ ASSERT_EQ(md.per_task_generated, kPerYield);
+ ASSERT_EQ(waiter->TotalObjectGenerated(), kPerYield);
+
+ // Release clamps to what is still outstanding and never underflows.
+ waiter->OnConsumedForTask(md, kPerYield);
+ waiter->ReleaseActorWideSlot(md, kPerYield);
+ ASSERT_EQ(md.per_task_generated, kPerYield);
+ ASSERT_EQ(waiter->TotalObjectGenerated(), kPerYield);
+}
+
TEST(GeneratorWaiterTest, OnConsumedForTaskAdvancesByDeltaIgnoresStale) {
auto waiter = std::make_shared<ActorWideGeneratorBackpressureWaiter>(
10, []() { return Status::OK(); }); |
The actor-wide cap and the owner-reported consumed totals are both in object units, but ReserveSlot/ReleaseSlot were always incrementing the shared budget by 1 per yield. With _num_objects_per_yield > 1 a grouped yield would reserve N objects on the per-task waiter but only 1 against the actor cap, so a cap of N admitted N yields (= N*N objects) before parking instead of one. Plumb num_objects through ReserveSlot/ReleaseSlot (Cython + ActorTaskBackpressureMetadata + ActorWideGeneratorBackpressureWaiter) so the actor budget is tracked in object units. ReleaseSlot now clamps to the outstanding generated-minus-consumed count so it never underflows when the group was partially consumed. Also: add the missing MockCoreWorkerClientInterface entry for UpdateGeneratorBackpressureConsumed. Patch authored by @rueian in ray-project#63310 (comment) Signed-off-by: sampan <[email protected]>
The actor-wide cap and the owner-reported consumed totals are both in object units, but ReserveSlot/ReleaseSlot were always incrementing the shared budget by 1 per yield. With _num_objects_per_yield > 1 a grouped yield would reserve N objects on the per-task waiter but only 1 against the actor cap, so a cap of N admitted N yields (= N*N objects) before parking instead of one. Plumb num_objects through ReserveSlot/ReleaseSlot (Cython + ActorTaskBackpressureMetadata + ActorWideGeneratorBackpressureWaiter) so the actor budget is tracked in object units. ReleaseSlot now clamps to the outstanding generated-minus-consumed count so it never underflows when the group was partially consumed. Also: add the missing MockCoreWorkerClientInterface entry for UpdateGeneratorBackpressureConsumed. Signed-off-by: sampan <[email protected]>
02527d4 to
ee58d6a
Compare
|
@rueian thanks for the patch, I have now applied it using cc |
…reConsumed TotalObjectConsumed/TotalObjectGenerated lock the waiter's internal mutex. Calling them while holding CoreWorker::mutex_ produced the lock order (mutex_ -> waiter mutex). The generator-execution path acquires them in the reverse order (waiter mutex held while a callback re-enters mutex_), so the two cycle. absl's deadlock detector aborts on it and it is a real latent deadlock under multithreaded actors with actor-wide backpressure enabled. Snapshot the counters before acquiring mutex_. Reading them a moment earlier is benign for the GC decision -- if the entry is erased prematurely, the next generated object recreates it. Signed-off-by: sampan <[email protected]>
Signed-off-by: sampan <[email protected]>
|
LGTM! |
|
@edoakes could you PTAL as well when you get time. |
| # with the per-method `_generator_backpressure_num_objects`: both | ||
| # apply, and the producer blocks on whichever is tighter. -1 (or | ||
| # None / unset) disables the actor-wide cap. | ||
| "_actor_generator_backpressure_num_objects": Option( |
There was a problem hiding this comment.
I think we should remove generator from the API name, even if it's currently internal. The functionality could easily be extended to support admission control for non-generator tasks.
There was a problem hiding this comment.
should we make this change when we extend to non-generator tasks instead of changing it now? as currently its specific to generator tasks only so that we avoid confusion? given this is internal we should be able to deprecate it without too much friction?
| c_bool actor_backpressure_state_owned_by_core_worker | ||
| int64_t num_objects_per_yield | ||
|
|
||
| def __dealloc__(self): |
There was a problem hiding this comment.
why do we do this in dealloc instead of explicitly in the task execution return path? Python gives no guarantee on when this will be called
There was a problem hiding this comment.
will call it explicitly as well, but retain this as a fall back
There was a problem hiding this comment.
Unless there's a strong reason to have it (i.e., there's a codepath where we can't explicitly clean it up), we should remove this. There's no need to add implicit fallbacks when we completely control the cleanup sequence.
There was a problem hiding this comment.
Please do it in a follow up, merging now to unblock integration on this
| state_found = ( | ||
| CCoreWorkerProcess.GetCoreWorker() | ||
| .TeardownGeneratorBackpressureTask(self.generator_id) | ||
| ) | ||
| if not state_found: | ||
| self.actor_backpressure_metadata.get().Teardown() |
There was a problem hiding this comment.
what does state_found indicate and when would we expect it not to be found?
There was a problem hiding this comment.
TeardownGeneratorBackpressureTask returns True if generator_backpressure_states_ contains a GeneratorBackpressureState entry for the given generator id.
this function can return false, if the entry was already cleaned up due to:
HandleUpdateGeneratorBackpressureConsumedcleaning it up after a stream has been fully consumed by a driver.HandleOwnerDiederased the entry on owner-worker failure.- The report failure callback (in
CoreWorker::ReportGeneratorItemReturns) erased it on RPC failure.
There was a problem hiding this comment.
will add this as a comment
Signed-off-by: sampan <[email protected]>
Signed-off-by: sampan <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit f665bc8. Configure here.
…() (#64333) ## Description Removing the implicit __dealloc__() as we fully want to control the object lifecycle. discussion: #63310 (comment) --------- Signed-off-by: sampan <[email protected]> Co-authored-by: sampan <[email protected]>
## Description
introduces `_actor_generator_backpressure_num_objects` option for
configuring actor level streaming generator object generation
backpressure. Unlike the existing `_generator_backpressure_num_objects`
, the config applies at the entire actor level and supports multi
threaded (concurrency > 1) cases. (but does not apply for async actors)
usage:
```python
@ray.remote(
max_concurrency=2,
_actor_generator_backpressure_num_objects=6,
)
class _A:
def gen(self, reporter, tag: str):
for i in range(5):
ray.get(reporter.report.remote(tag, i))
yield i
```
## Related issues
> Link related issues: "Fixes ray-project#1234", "Closes ray-project#1234", or "Related to
ray-project#1234".
## Additional information
> Optional: Add implementation details, API changes, usage examples,
screenshots, etc.
---------
Signed-off-by: sampan <[email protected]>
Co-authored-by: sampan <[email protected]>
…() (ray-project#64333) ## Description Removing the implicit __dealloc__() as we fully want to control the object lifecycle. discussion: ray-project#63310 (comment) --------- Signed-off-by: sampan <[email protected]> Co-authored-by: sampan <[email protected]>
## Description
introduces `_actor_generator_backpressure_num_objects` option for
configuring actor level streaming generator object generation
backpressure. Unlike the existing `_generator_backpressure_num_objects`
, the config applies at the entire actor level and supports multi
threaded (concurrency > 1) cases. (but does not apply for async actors)
usage:
```python
@ray.remote(
max_concurrency=2,
_actor_generator_backpressure_num_objects=6,
)
class _A:
def gen(self, reporter, tag: str):
for i in range(5):
ray.get(reporter.report.remote(tag, i))
yield i
```
## Related issues
> Link related issues: "Fixes ray-project#1234", "Closes ray-project#1234", or "Related to
ray-project#1234".
## Additional information
> Optional: Add implementation details, API changes, usage examples,
screenshots, etc.
---------
Signed-off-by: sampan <[email protected]>
Co-authored-by: sampan <[email protected]>
Signed-off-by: 400Ping <[email protected]>
…() (ray-project#64333) ## Description Removing the implicit __dealloc__() as we fully want to control the object lifecycle. discussion: ray-project#63310 (comment) --------- Signed-off-by: sampan <[email protected]> Co-authored-by: sampan <[email protected]> Signed-off-by: 400Ping <[email protected]>
… increases (#65148) ## Description Regression test to prevent cases like the one identified in #63310 where every worker ended up subscribing to worker death notifications from every other worker. we assert the following to be true during ray cluster startup: | channel | connections| | -------- | -------- | | GCS_WORKER_DELTA | O(num_nodes) | | GCS_JOB | O(num_nodes) | | GCS_ACTOR | all actor events <= 1, keyed (actor_id) specific events >= 1 | | GCS_NODE_ADDRESS_AND_LIVENESS| no keyed(node_id) listeners | --------- Signed-off-by: sampan <[email protected]> Signed-off-by: Rueian <[email protected]> Co-authored-by: sampan <[email protected]> Co-authored-by: Rueian <[email protected]>
… increases (ray-project#65148) ## Description Regression test to prevent cases like the one identified in ray-project#63310 where every worker ended up subscribing to worker death notifications from every other worker. we assert the following to be true during ray cluster startup: | channel | connections| | -------- | -------- | | GCS_WORKER_DELTA | O(num_nodes) | | GCS_JOB | O(num_nodes) | | GCS_ACTOR | all actor events <= 1, keyed (actor_id) specific events >= 1 | | GCS_NODE_ADDRESS_AND_LIVENESS| no keyed(node_id) listeners | --------- Signed-off-by: sampan <[email protected]> Signed-off-by: Rueian <[email protected]> Co-authored-by: sampan <[email protected]> Co-authored-by: Rueian <[email protected]>
) ## Description Since #63310, the owner sends `UpdateGeneratorBackpressureConsumed` to the executor on every read from a backpressured streaming generator. The gRPC send (`grpc_call_start_batch` / `ExecCtx::Flush`) ran inline on the reading thread. For Ray Data that thread is the streaming executor's Python scheduling loop, and Ray Data reads twice per block (block ref + metadata ref), so it pays for 2 RPC sends per block. This was reported as ~25% of the driver flame graph and a ~30% drop in task dispatch rate: #63310 (comment) This PR posts the send to `io_service_` so the reading thread only pays for a post. The RPC, its contents and the executor side are unchanged. ## Related issues Related to #63310 (the performance regression reported in the review thread above). ## Additional information Microbenchmark: 8 generators × 20k items, waiting until all items are reported and then timing only `_next_sync` reads on the driver (4-CPU dev box, 5 trials): | Build | µs per read | |---|---| | master, backpressure off (no RPC) | ~15 | | master, `_generator_backpressure_num_objects` set | ~120–155 | | this PR, `_generator_backpressure_num_objects` set | ~25–52 | Not a duplicate: I searched open PRs for `UpdateGeneratorBackpressureConsumed` and "generator backpressure consumed", and none touch this path. #65136 and #65195 only changed owner-death subscriptions. Tests run: - `python -m pytest -q python/ray/tests/test_streaming_generator_backpressure.py` → 37 passed - `pre-commit run` → passed AI assistance (Claude Code) was used for this change. I reviewed the diff and ran the tests above. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: sampan <[email protected]>

Description
introduces
_actor_generator_backpressure_num_objectsoption for configuring actor level streaming generator object generation backpressure. Unlike the existing_generator_backpressure_num_objects, the config applies at the entire actor level and supports multi threaded (concurrency > 1) cases. (but does not apply for async actors)usage:
Related issues
Additional information