chalk-remote-call-python 1.10.14__tar.gz → 1.11.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/PKG-INFO +1 -1
  2. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk-remote-call-rs/chalk-remote-call-server/src/fnq_client.rs +39 -15
  3. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk-remote-call-rs/chalk-remote-call-server/src/self_consumer.rs +180 -136
  4. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk-remote-call-rs/chalk-remote-call-server/src/server.rs +31 -6
  5. chalk_remote_call_python-1.11.0/chalk_remote_call/_version.py +1 -0
  6. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call_python.egg-info/PKG-INFO +1 -1
  7. chalk_remote_call_python-1.10.14/chalk_remote_call/_version.py +0 -1
  8. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/MANIFEST.in +0 -0
  9. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/README.md +0 -0
  10. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk-remote-call-rs/Cargo.lock +0 -0
  11. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk-remote-call-rs/Cargo.toml +0 -0
  12. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk-remote-call-rs/chalk-remote-call-proto/Cargo.toml +0 -0
  13. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk-remote-call-rs/chalk-remote-call-proto/src/gen/chalk.auth.v1.rs +0 -0
  14. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk-remote-call-rs/chalk-remote-call-proto/src/gen/chalk.common.v1.rs +0 -0
  15. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk-remote-call-rs/chalk-remote-call-proto/src/gen/chalk.runtime.v1.rs +0 -0
  16. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk-remote-call-rs/chalk-remote-call-proto/src/gen/chalk.runtime.v1.tonic.rs +0 -0
  17. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk-remote-call-rs/chalk-remote-call-proto/src/gen/chalk.utils.v1.rs +0 -0
  18. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk-remote-call-rs/chalk-remote-call-proto/src/gen/descriptor.bin +0 -0
  19. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk-remote-call-rs/chalk-remote-call-proto/src/lib.rs +0 -0
  20. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk-remote-call-rs/chalk-remote-call-server/Cargo.toml +0 -0
  21. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk-remote-call-rs/chalk-remote-call-server/build.rs +0 -0
  22. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk-remote-call-rs/chalk-remote-call-server/src/async_service.rs +0 -0
  23. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk-remote-call-rs/chalk-remote-call-server/src/coalesce.rs +0 -0
  24. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk-remote-call-rs/chalk-remote-call-server/src/lib.rs +0 -0
  25. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk-remote-call-rs/chalk-remote-call-server/src/metrics.rs +0 -0
  26. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk-remote-call-rs/chalk-remote-call-server/src/python_bridge.rs +0 -0
  27. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk-remote-call-rs/chalk-remote-call-server/src/service.rs +0 -0
  28. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk-remote-call-rs/rust-toolchain.toml +0 -0
  29. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/__init__.py +0 -0
  30. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/__main__.py +0 -0
  31. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/__init__.py +0 -0
  32. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/chalk/__init__.py +0 -0
  33. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/chalk/auth/__init__.py +0 -0
  34. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/chalk/auth/v1/__init__.py +0 -0
  35. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/chalk/auth/v1/permissions_pb2.py +0 -0
  36. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/chalk/auth/v1/permissions_pb2_grpc.py +0 -0
  37. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/chalk/common/__init__.py +0 -0
  38. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/chalk/common/v1/__init__.py +0 -0
  39. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/chalk/common/v1/chalk_error_pb2.py +0 -0
  40. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/chalk/common/v1/chalk_error_pb2_grpc.py +0 -0
  41. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/chalk/runtime/__init__.py +0 -0
  42. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/chalk/runtime/v1/__init__.py +0 -0
  43. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/chalk/runtime/v1/fnq_consumer_pb2.py +0 -0
  44. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/chalk/runtime/v1/fnq_consumer_pb2_grpc.py +0 -0
  45. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/chalk/runtime/v1/remote_python_call_pb2.py +0 -0
  46. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/chalk/runtime/v1/remote_python_call_pb2_grpc.py +0 -0
  47. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/chalk/utils/__init__.py +0 -0
  48. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/chalk/utils/v1/__init__.py +0 -0
  49. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/chalk/utils/v1/encoding_pb2.py +0 -0
  50. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/chalk/utils/v1/encoding_pb2_grpc.py +0 -0
  51. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/chalk/utils/v1/field_change_pb2.py +0 -0
  52. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/chalk/utils/v1/field_change_pb2_grpc.py +0 -0
  53. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/chalk/utils/v1/large_pb2.py +0 -0
  54. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/chalk/utils/v1/large_pb2_grpc.py +0 -0
  55. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/chalk/utils/v1/sensitive_pb2.py +0 -0
  56. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_gen/chalk/utils/v1/sensitive_pb2_grpc.py +0 -0
  57. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/_native.pyi +0 -0
  58. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/arrow_utils.py +0 -0
  59. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/cli.py +0 -0
  60. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/errors.py +0 -0
  61. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/handler_loader.py +0 -0
  62. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/input_transform.py +0 -0
  63. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/logging.py +0 -0
  64. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/server.py +0 -0
  65. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/servicer.py +0 -0
  66. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call/tracing.py +0 -0
  67. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call_python.egg-info/SOURCES.txt +0 -0
  68. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call_python.egg-info/dependency_links.txt +0 -0
  69. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call_python.egg-info/entry_points.txt +0 -0
  70. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call_python.egg-info/requires.txt +0 -0
  71. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/chalk_remote_call_python.egg-info/top_level.txt +0 -0
  72. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/pyproject.toml +0 -0
  73. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/setup.cfg +0 -0
  74. {chalk_remote_call_python-1.10.14 → chalk_remote_call_python-1.11.0}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: chalk-remote-call-python
3
- Version: 1.10.14
3
+ Version: 1.11.0
4
4
  Summary: Chalk remote call Python runtime interface client
5
5
  Author: Chalk AI, Inc.
6
6
  Project-URL: Homepage, https://chalk.ai
@@ -9,6 +9,7 @@ use chalk_remote_call_proto::chalk::runtime::v1::fnq_consumer_service_client::Fn
9
9
  use chalk_remote_call_proto::chalk::runtime::v1::{
10
10
  AcquireWorkRequest, FnqWork, RenewWorkRequest, ReportResultsRequest,
11
11
  };
12
+ use tokio::sync::watch;
12
13
  use tonic::transport::{Channel, ClientTlsConfig, Endpoint};
13
14
  use tonic::{Request, Status};
14
15
 
@@ -62,6 +63,7 @@ impl FnqClient {
62
63
  pub async fn acquire(
63
64
  &self,
64
65
  request: AcquireWorkRequest,
66
+ shutdown: &mut watch::Receiver<bool>,
65
67
  mut dispatch: impl FnMut(FnqWork),
66
68
  ) -> Result<usize, Status> {
67
69
  let started = Instant::now();
@@ -69,33 +71,51 @@ impl FnqClient {
69
71
  let mut delivered = HashSet::new();
70
72
  let mut backoff = Duration::from_millis(200);
71
73
  loop {
74
+ if *shutdown.borrow() {
75
+ return Ok(delivered.len());
76
+ }
72
77
  if started.elapsed() >= retry_window {
73
78
  return Err(Status::failed_precondition(
74
79
  "Fnq acquisition replay window expired",
75
80
  ));
76
81
  }
77
82
  let result = async {
78
- let mut stream = self
79
- .client
80
- .clone()
81
- .acquire_work(self.request(request.clone()).await?)
82
- .await?
83
- .into_inner();
83
+ let response = tokio::select! {
84
+ biased;
85
+ _ = shutdown.changed() => return Ok(delivered.len()),
86
+ response = async {
87
+ self.client
88
+ .clone()
89
+ .acquire_work(self.request(request.clone()).await?)
90
+ .await
91
+ } => response?,
92
+ };
93
+ let mut stream = response.into_inner();
84
94
 
85
- while let Some(response) =
86
- tokio::time::timeout(Duration::from_secs(5), stream.message())
87
- .await
88
- .map_err(|_| {
89
- Status::deadline_exceeded("Fnq acquisition stream stalled")
90
- })??
91
- {
95
+ loop {
96
+ if *shutdown.borrow() {
97
+ return Ok(delivered.len());
98
+ }
99
+ let response = tokio::select! {
100
+ biased;
101
+ _ = shutdown.changed() => return Ok(delivered.len()),
102
+ response = tokio::time::timeout(Duration::from_secs(5), stream.message()) => {
103
+ response.map_err(|_| {
104
+ Status::deadline_exceeded("Fnq acquisition stream stalled")
105
+ })??
106
+ },
107
+ };
108
+ let Some(mut response) = response else {
109
+ break;
110
+ };
111
+ // Once received, validate and dispatch this delivery before
112
+ // observing shutdown so the caller can drain its work.
92
113
  // Redis's recorded deadline accounts for transit time. Renew
93
114
  // before dispatch if less than half the requested lease remains.
94
115
  let now = std::time::SystemTime::now()
95
116
  .duration_since(std::time::UNIX_EPOCH)
96
117
  .map_err(|_| Status::internal("system clock before Unix epoch"))?
97
118
  .as_millis() as i128;
98
- let mut response = response;
99
119
  if let Some(work) = response
100
120
  .work
101
121
  .as_mut()
@@ -140,7 +160,11 @@ impl FnqClient {
140
160
  ));
141
161
  }
142
162
  tracing::warn!(%error, "Fnq acquisition failed; retrying the same request");
143
- tokio::time::sleep(backoff).await;
163
+ tokio::select! {
164
+ biased;
165
+ _ = shutdown.changed() => return Ok(delivered.len()),
166
+ _ = tokio::time::sleep(backoff) => {},
167
+ }
144
168
  backoff = (backoff * 2).min(Duration::from_secs(2));
145
169
  }
146
170
  Err(error) => return Err(error),
@@ -37,6 +37,7 @@ use chalk_remote_call_proto::chalk::common::v1::ChalkException;
37
37
  use chalk_remote_call_proto::chalk::runtime::v1::report_results_request::Result as ResultEvent;
38
38
  use chalk_remote_call_proto::chalk::runtime::v1::{AcquireWorkRequest, ReportResultsRequest};
39
39
  use std::collections::HashMap;
40
+ use std::future::Future;
40
41
  use std::panic::AssertUnwindSafe;
41
42
  use std::str::FromStr;
42
43
  use std::sync::{Arc, Mutex};
@@ -52,7 +53,8 @@ use dashmap::DashMap;
52
53
  use futures_util::FutureExt;
53
54
  use redis::aio::ConnectionManager;
54
55
  use redis::Client;
55
- use tokio::sync::mpsc;
56
+ use tokio::sync::{mpsc, watch};
57
+ use tokio::task::{JoinHandle, JoinSet};
56
58
  use tracing::{debug, error, info, warn};
57
59
  use uuid::Uuid;
58
60
 
@@ -495,7 +497,7 @@ impl SelfConsumerConfig {
495
497
  /// renewer heartbeats whatever is in the set on each tick.
496
498
  type LiveCalls = Arc<DashMap<String, QueueReceipt>>;
497
499
 
498
- /// Connect to Redis and run the consume loop until the process exits. Returns
500
+ /// Drain API and Stream work on shutdown, retaining legacy List execution. Returns
499
501
  /// `Err` only on a fatal setup failure (bad URL / unreachable Redis at startup);
500
502
  /// transient per-iteration Redis errors are logged and retried so a Redis blip
501
503
  /// does not tear the consumer down.
@@ -504,12 +506,16 @@ pub async fn run(
504
506
  handler: Arc<PythonHandler>,
505
507
  metrics: Option<Arc<CallMetrics>>,
506
508
  coalescing_queue: Option<Arc<CoalescingQueue>>,
509
+ mut shutdown: watch::Receiver<bool>,
507
510
  ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
508
511
  if config.consumer_endpoint.is_some() {
509
- return run_fnq(config, handler, metrics, coalescing_queue).await;
512
+ return run_fnq(config, handler, metrics, coalescing_queue, shutdown).await;
510
513
  }
511
514
  let client = Client::open(config.redis_url.clone())?;
512
- let conn = ConnectionManager::new(client).await?;
515
+ let conn = tokio::select! {
516
+ _ = shutdown.changed() => return Ok(()),
517
+ conn = ConnectionManager::new(client) => conn?,
518
+ };
513
519
  let queue = FunctionQueue::new(conn.clone(), config.tenant.clone());
514
520
  let input_queue = queue.bind(&config.function_name, config.queue_protocol);
515
521
  let sem = queue.semaphore(&config.function_name, config.max_concurrent, config.sem_ttl);
@@ -528,7 +534,7 @@ pub async fn run(
528
534
  input_queue.initialize_consumer_group().await?;
529
535
  }
530
536
 
531
- spawn_renewer(
537
+ let renewer = spawn_renewer(
532
538
  input_queue.clone(),
533
539
  conn.clone(),
534
540
  sem_key,
@@ -548,7 +554,8 @@ pub async fn run(
548
554
 
549
555
  if config.queue_protocol == QueueProtocol::StreamV1 {
550
556
  let legacy_queue = queue.bind(&config.function_name, QueueProtocol::ListV1);
551
- return run_stream_dispatch_loop(
557
+ let mut tasks = JoinSet::new();
558
+ let result = run_stream_dispatch_loop(
552
559
  &config,
553
560
  queue,
554
561
  input_queue,
@@ -560,10 +567,13 @@ pub async fn run(
560
567
  handler,
561
568
  metrics,
562
569
  coalescing_queue,
570
+ shutdown,
571
+ &mut tasks,
563
572
  )
564
573
  .await;
574
+ drain_calls(&mut tasks, renewer).await;
575
+ return result;
565
576
  }
566
-
567
577
  run_list_dispatch_loop(
568
578
  &config,
569
579
  queue,
@@ -586,6 +596,7 @@ async fn run_fnq(
586
596
  handler: Arc<PythonHandler>,
587
597
  metrics: Option<Arc<CallMetrics>>,
588
598
  coalescing_queue: Option<Arc<CoalescingQueue>>,
599
+ mut shutdown: watch::Receiver<bool>,
589
600
  ) -> Result<(), OutputError> {
590
601
  let endpoint = config
591
602
  .consumer_endpoint
@@ -594,12 +605,13 @@ async fn run_fnq(
594
605
  let token_file = std::env::var("CHALK_FUNCTION_QUEUE_TOKEN_FILE")
595
606
  .unwrap_or_else(|_| "/var/run/secrets/chalk-function-queue/identity-token".into());
596
607
  let client = crate::fnq_client::FnqClient::new(endpoint, token_file.into())?;
608
+ let lease_duration_seconds = config.sem_ttl.as_secs().try_into()?;
597
609
  let live: Arc<DashMap<String, ()>> = Arc::new(DashMap::new());
598
610
  let renewal_client = client.clone();
599
611
  let renewal_live = live.clone();
600
612
  let consumer_id = Uuid::new_v4().to_string();
601
613
  let renew_interval = SEM_RENEW_INTERVAL.min(config.sem_ttl / 3);
602
- tokio::spawn(async move {
614
+ let renewer = tokio::spawn(async move {
603
615
  let mut interval = tokio::time::interval(renew_interval);
604
616
  interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
605
617
  loop {
@@ -621,13 +633,13 @@ async fn run_fnq(
621
633
  }
622
634
  }
623
635
  });
624
- let mut tasks = tokio::task::JoinSet::new();
636
+ let mut tasks = JoinSet::new();
625
637
  let mut backoff = config.poll_backoff_initial;
626
- loop {
638
+ while !*shutdown.borrow() {
627
639
  while tasks.try_join_next().is_some() {}
628
640
  let available = config.max_concurrent.saturating_sub(tasks.len() as u32);
629
641
  if available == 0 {
630
- tokio::time::sleep(config.poll_backoff_initial).await;
642
+ wait_backoff(config.poll_backoff_initial, &mut shutdown).await;
631
643
  continue;
632
644
  }
633
645
  let request = AcquireWorkRequest {
@@ -636,105 +648,126 @@ async fn run_fnq(
636
648
  consumer_id: consumer_id.clone(),
637
649
  max_calls: available.min(config.stream_read_count as u32).min(64),
638
650
  max_concurrent: config.max_concurrent,
639
- lease_duration_seconds: config.sem_ttl.as_secs().try_into()?,
651
+ lease_duration_seconds,
640
652
  };
641
- let result = client
642
- .acquire(request, |delivery| {
643
- let handle = delivery.work_handle.clone();
644
- live.insert(handle.clone(), ());
645
- let client = client.clone();
646
- let live = live.clone();
647
- let handler = handler.clone();
648
- let coalescer = coalescing_queue.clone();
649
- let metrics = metrics.clone();
650
- let flush_timeout = config.flush_timeout;
651
- tasks.spawn(async move {
652
- let result = AssertUnwindSafe(async {
653
- let mut output = CallOutput::Fnq {
654
- client,
655
- handle: handle.clone(),
656
- trace_id: String::new(),
657
- call_duration: None,
658
- };
659
- let call = delivery.call.ok_or("Fnq response missing call")?;
660
- let work = QueuedCall {
661
- call_id: delivery.call_id,
662
- call: chalk_queue::types::CallPayload {
663
- name: call.name,
664
- feather_stream: base64::engine::general_purpose::STANDARD
665
- .encode(call.feather_stream),
666
- },
667
- metadata: chalk_queue::types::CallMetadata {
668
- otel_headers: delivery.metadata,
669
- ..Default::default()
670
- },
671
- result_ttl_seconds: 86400,
672
- batch_result: None,
673
- max_retries: (delivery.max_attempts > 1)
674
- .then_some((delivery.max_attempts - 1) as u32),
675
- };
676
- if delivery.attempt > delivery.max_attempts {
677
- return output
678
- .write_error(
679
- 1,
680
- "RetryAttemptsExhausted",
681
- "Fnq retry attempts exhausted",
682
- None,
683
- )
684
- .await;
685
- }
686
- let final_attempt = delivery.attempt == delivery.max_attempts;
687
- let completed = if let Some(coalescer) = coalescer {
688
- coalesced_execute_and_write(
689
- &coalescer,
690
- &mut output,
691
- work,
692
- final_attempt,
693
- metrics.as_ref(),
694
- )
695
- .await?
696
- } else {
697
- execute_and_write(
698
- &handler,
699
- &mut output,
700
- work,
701
- flush_timeout,
702
- final_attempt,
703
- metrics.as_ref(),
653
+ let acquisition = client.acquire(request, &mut shutdown, |delivery| {
654
+ let handle = delivery.work_handle.clone();
655
+ live.insert(handle.clone(), ());
656
+ let client = client.clone();
657
+ let live = live.clone();
658
+ let handler = handler.clone();
659
+ let coalescer = coalescing_queue.clone();
660
+ let metrics = metrics.clone();
661
+ let flush_timeout = config.flush_timeout;
662
+ tasks.spawn(async move {
663
+ let result = AssertUnwindSafe(async {
664
+ let mut output = CallOutput::Fnq {
665
+ client,
666
+ handle: handle.clone(),
667
+ trace_id: String::new(),
668
+ call_duration: None,
669
+ };
670
+ let call = delivery.call.ok_or("Fnq response missing call")?;
671
+ let work = QueuedCall {
672
+ call_id: delivery.call_id,
673
+ call: chalk_queue::types::CallPayload {
674
+ name: call.name,
675
+ feather_stream: base64::engine::general_purpose::STANDARD
676
+ .encode(call.feather_stream),
677
+ },
678
+ metadata: chalk_queue::types::CallMetadata {
679
+ otel_headers: delivery.metadata,
680
+ ..Default::default()
681
+ },
682
+ result_ttl_seconds: 86400,
683
+ batch_result: None,
684
+ max_retries: (delivery.max_attempts > 1)
685
+ .then_some((delivery.max_attempts - 1) as u32),
686
+ };
687
+ if delivery.attempt > delivery.max_attempts {
688
+ return output
689
+ .write_error(
690
+ 1,
691
+ "RetryAttemptsExhausted",
692
+ "Fnq retry attempts exhausted",
693
+ None,
704
694
  )
705
- .await?
706
- };
707
- if !completed {
708
- output.report(1, ResultEvent::Retry(())).await?;
709
- }
710
- Ok::<(), OutputError>(())
711
- })
712
- .catch_unwind()
713
- .await;
714
- live.remove(&handle);
715
- match result {
716
- Ok(Ok(())) => {}
717
- Ok(Err(error)) => {
718
- warn!(%handle, %error, "Fnq call failed; lease will expire")
719
- }
720
- Err(_) => {
721
- error!(%handle, "Fnq execution task panicked; lease will expire")
722
- }
695
+ .await;
723
696
  }
724
- });
725
- })
726
- .await;
697
+ let final_attempt = delivery.attempt == delivery.max_attempts;
698
+ let completed = if let Some(coalescer) = coalescer {
699
+ coalesced_execute_and_write(
700
+ &coalescer,
701
+ &mut output,
702
+ work,
703
+ final_attempt,
704
+ metrics.as_ref(),
705
+ )
706
+ .await?
707
+ } else {
708
+ execute_and_write(
709
+ &handler,
710
+ &mut output,
711
+ work,
712
+ flush_timeout,
713
+ final_attempt,
714
+ metrics.as_ref(),
715
+ )
716
+ .await?
717
+ };
718
+ if !completed {
719
+ output.report(1, ResultEvent::Retry(())).await?;
720
+ }
721
+ Ok::<(), OutputError>(())
722
+ })
723
+ .catch_unwind()
724
+ .await;
725
+ live.remove(&handle);
726
+ match result {
727
+ Ok(Ok(())) => {}
728
+ Ok(Err(error)) => {
729
+ warn!(%handle, %error, "Fnq call failed; lease will expire")
730
+ }
731
+ Err(_) => {
732
+ error!(%handle, "Fnq execution task panicked; lease will expire")
733
+ }
734
+ }
735
+ });
736
+ });
737
+ let result = acquisition.await;
738
+ if *shutdown.borrow() {
739
+ break;
740
+ }
727
741
  match result {
728
742
  Ok(count) if count > 0 => backoff = config.poll_backoff_initial,
729
743
  result => {
730
744
  if let Err(error) = result {
731
745
  warn!(%error, "Fnq acquisition failed; will retry");
732
746
  }
733
- tokio::time::sleep(backoff).await;
747
+ wait_backoff(backoff, &mut shutdown).await;
734
748
  backoff = (backoff * 2).min(config.poll_backoff_max);
735
749
  }
736
750
  }
737
751
  }
752
+ drain_calls(&mut tasks, renewer).await;
753
+ Ok(())
754
+ }
755
+
756
+ async fn wait_backoff(backoff: Duration, shutdown: &mut watch::Receiver<bool>) {
757
+ tokio::select! {
758
+ _ = tokio::time::sleep(backoff) => {},
759
+ _ = shutdown.changed() => {},
760
+ }
761
+ }
762
+
763
+ async fn drain_calls(tasks: &mut JoinSet<()>, renewer: JoinHandle<()>) {
764
+ info!(active_calls = tasks.len(), "Draining queued function calls");
765
+ while let Some(result) = tasks.join_next().await {
766
+ if let Err(error) = result {
767
+ error!(%error, "queued function task failed during shutdown");
768
+ }
769
+ }
770
+ renewer.abort();
738
771
  }
739
772
 
740
773
  /// Consume the legacy Redis List queue one call at a time. Streams use their
@@ -807,7 +840,7 @@ async fn run_list_dispatch_loop(
807
840
 
808
841
  backoff = config.poll_backoff_initial;
809
842
 
810
- dispatch_delivery(
843
+ tokio::spawn(dispatch_delivery(
811
844
  queue.clone(),
812
845
  input_queue.clone(),
813
846
  coalescing_queue.clone(),
@@ -818,7 +851,7 @@ async fn run_list_dispatch_loop(
818
851
  live_calls.clone(),
819
852
  config.flush_timeout,
820
853
  metrics.clone(),
821
- );
854
+ ));
822
855
  // Loop immediately — dispatch as fast as we can acquire + pop. The
823
856
  // semaphore (not this loop) is what bounds in-flight work.
824
857
  }
@@ -837,33 +870,36 @@ async fn run_stream_dispatch_loop(
837
870
  handler: Arc<PythonHandler>,
838
871
  metrics: Option<Arc<CallMetrics>>,
839
872
  coalescing_queue: Option<Arc<CoalescingQueue>>,
873
+ mut shutdown: watch::Receiver<bool>,
874
+ tasks: &mut JoinSet<()>,
840
875
  ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
841
876
  let mut backoff = config.poll_backoff_initial;
842
877
  // Reclaim once immediately to recover work from a prior crashed pod, then
843
878
  // periodically. Healthy messages are kept alive by `spawn_renewer`.
844
879
  let mut last_reclaim = Instant::now() - STREAM_RECLAIM_INTERVAL;
845
880
 
846
- loop {
881
+ while !*shutdown.borrow() {
882
+ while tasks.try_join_next().is_some() {}
847
883
  // Capacity must be reserved before XREADGROUP. Reading first would put
848
884
  // a potentially huge number of messages into this consumer's PEL while
849
885
  // they wait for semaphore slots.
850
886
  let mut leases = match sem.try_acquire_many(config.stream_read_count).await {
851
887
  Ok(leases) if !leases.is_empty() => leases,
852
888
  Ok(_) => {
853
- tokio::time::sleep(backoff).await;
889
+ wait_backoff(backoff, &mut shutdown).await;
854
890
  backoff = (backoff * 2).min(config.poll_backoff_max);
855
891
  continue;
856
892
  }
857
893
  Err(error) => {
858
894
  warn!(%error, "batch semaphore acquire failed; backing off");
859
- tokio::time::sleep(backoff).await;
895
+ wait_backoff(backoff, &mut shutdown).await;
860
896
  backoff = (backoff * 2).min(config.poll_backoff_max);
861
897
  continue;
862
898
  }
863
899
  };
864
900
 
865
901
  let mut deliveries = Vec::with_capacity(leases.len());
866
- if last_reclaim.elapsed() >= STREAM_RECLAIM_INTERVAL {
902
+ if !*shutdown.borrow() && last_reclaim.elapsed() >= STREAM_RECLAIM_INTERVAL {
867
903
  last_reclaim = Instant::now();
868
904
  match input_queue
869
905
  .reclaim_stale(&consumer_name, config.sem_ttl, leases.len())
@@ -879,7 +915,7 @@ async fn run_stream_dispatch_loop(
879
915
  // During the one-way List → Stream migration, drain old List entries
880
916
  // before reading new Stream traffic. This is one bounded operation per
881
917
  // read window, not an LLEN on every Stream message.
882
- if deliveries.len() < leases.len() {
918
+ if !*shutdown.borrow() && deliveries.len() < leases.len() {
883
919
  if let Some(legacy_queue) = &legacy_queue {
884
920
  match legacy_queue
885
921
  .dequeue_many(&consumer_name, leases.len() - deliveries.len())
@@ -896,7 +932,7 @@ async fn run_stream_dispatch_loop(
896
932
  }
897
933
  }
898
934
  }
899
- if deliveries.len() < leases.len() {
935
+ if !*shutdown.borrow() && deliveries.len() < leases.len() {
900
936
  match input_queue
901
937
  .dequeue_many(&consumer_name, leases.len() - deliveries.len())
902
938
  .await
@@ -917,14 +953,17 @@ async fn run_stream_dispatch_loop(
917
953
  let _ = release_many(&mut conn, sem.key(), &unused_tokens).await;
918
954
 
919
955
  if deliveries.is_empty() {
920
- tokio::time::sleep(backoff).await;
956
+ if *shutdown.borrow() {
957
+ break;
958
+ }
959
+ wait_backoff(backoff, &mut shutdown).await;
921
960
  backoff = (backoff * 2).min(config.poll_backoff_max);
922
961
  continue;
923
962
  }
924
963
 
925
964
  backoff = config.poll_backoff_initial;
926
965
  for (delivery, lease) in deliveries.into_iter().zip(leases) {
927
- dispatch_delivery(
966
+ tasks.spawn(dispatch_delivery(
928
967
  queue.clone(),
929
968
  input_queue.clone(),
930
969
  coalescing_queue.clone(),
@@ -935,9 +974,10 @@ async fn run_stream_dispatch_loop(
935
974
  live_calls.clone(),
936
975
  config.flush_timeout,
937
976
  metrics.clone(),
938
- );
977
+ ));
939
978
  }
940
979
  }
980
+ Ok(())
941
981
  }
942
982
 
943
983
  fn attach_queue_wait_timing(work: &mut QueuedCall, attempt: u64) {
@@ -974,33 +1014,37 @@ fn dispatch_delivery(
974
1014
  live_calls: LiveCalls,
975
1015
  flush_timeout: Duration,
976
1016
  metrics: Option<Arc<CallMetrics>>,
977
- ) {
1017
+ ) -> impl Future<Output = ()> {
978
1018
  live_calls.insert(lease.token().to_string(), delivery.receipt.clone());
979
- match coalescing_queue {
980
- Some(cq) => {
981
- tokio::spawn(run_one_coalesced_call(
982
- queue,
983
- input_queue,
984
- cq,
985
- conn,
986
- delivery,
987
- lease,
988
- live_calls,
989
- metrics,
990
- ));
991
- }
992
- None => {
993
- tokio::spawn(run_one_call(
994
- handler,
995
- queue,
996
- input_queue,
997
- conn,
998
- delivery,
999
- lease,
1000
- live_calls,
1001
- flush_timeout,
1002
- metrics,
1003
- ));
1019
+ async move {
1020
+ match coalescing_queue {
1021
+ Some(cq) => {
1022
+ run_one_coalesced_call(
1023
+ queue,
1024
+ input_queue,
1025
+ cq,
1026
+ conn,
1027
+ delivery,
1028
+ lease,
1029
+ live_calls,
1030
+ metrics,
1031
+ )
1032
+ .await;
1033
+ }
1034
+ None => {
1035
+ run_one_call(
1036
+ handler,
1037
+ queue,
1038
+ input_queue,
1039
+ conn,
1040
+ delivery,
1041
+ lease,
1042
+ live_calls,
1043
+ flush_timeout,
1044
+ metrics,
1045
+ )
1046
+ .await;
1047
+ }
1004
1048
  }
1005
1049
  }
1006
1050
  }
@@ -1598,7 +1642,7 @@ fn spawn_renewer(
1598
1642
  sem_key: String,
1599
1643
  live_calls: LiveCalls,
1600
1644
  sem_ttl: Duration,
1601
- ) {
1645
+ ) -> JoinHandle<()> {
1602
1646
  tokio::spawn(async move {
1603
1647
  let mut ticker = tokio::time::interval(SEM_RENEW_INTERVAL);
1604
1648
  ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
@@ -1633,7 +1677,7 @@ fn spawn_renewer(
1633
1677
  Err(error) => warn!(%error, "batch Stream delivery renewal failed"),
1634
1678
  }
1635
1679
  }
1636
- });
1680
+ })
1637
1681
  }
1638
1682
 
1639
1683
  #[cfg(test)]
@@ -71,6 +71,9 @@ pub async fn run_server(
71
71
  is_remote_function,
72
72
  );
73
73
 
74
+ #[cfg(target_os = "linux")]
75
+ let (shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(false);
76
+
74
77
  // Self-consume the Redis fn queue when this pod was provisioned with a
75
78
  // Redis URL (gRPC-only otherwise). The self-consumer shares the gRPC
76
79
  // server's `coalescing_queue`: when batching is on, self-consumed work and
@@ -79,24 +82,28 @@ pub async fn run_server(
79
82
  // queue is `None` and the self-consumer dispatches per-call (streaming).
80
83
 
81
84
  #[cfg(target_os = "linux")]
82
- if let Some(cfg) = crate::self_consumer::SelfConsumerConfig::from_env() {
85
+ let consumer_task = crate::self_consumer::SelfConsumerConfig::from_env().and_then(|cfg| {
86
+ let drain_on_shutdown = cfg.consumer_endpoint.is_some()
87
+ || cfg.queue_protocol == chalk_queue::QueueProtocol::StreamV1;
83
88
  // Share the synchronous gRPC server's function-call metrics pipeline.
84
89
  let consumer_handler = python_handler.clone();
85
90
  let consumer_metrics = metrics.clone();
86
91
  let consumer_coalescing = coalescing_queue.clone();
87
- tokio::spawn(async move {
92
+ let task = tokio::spawn(async move {
88
93
  if let Err(e) = crate::self_consumer::run(
89
94
  cfg,
90
95
  consumer_handler,
91
96
  consumer_metrics,
92
97
  consumer_coalescing,
98
+ shutdown_rx,
93
99
  )
94
100
  .await
95
101
  {
96
102
  tracing::error!(error = %e, "fnq self-consumer failed to start");
97
103
  }
98
104
  });
99
- }
105
+ drain_on_shutdown.then_some(task)
106
+ });
100
107
 
101
108
  // Main service
102
109
  let svc = RemoteCallServiceImpl {
@@ -108,7 +115,12 @@ pub async fn run_server(
108
115
 
109
116
  info!("Server starting on {}", addr);
110
117
 
111
- Server::builder()
118
+ let shutdown = async {
119
+ shutdown_signal().await;
120
+ #[cfg(target_os = "linux")]
121
+ shutdown_tx.send_replace(true);
122
+ };
123
+ let result = Server::builder()
112
124
  .add_service(health_service)
113
125
  .add_service(reflection_service)
114
126
  .add_service(reflection_service_v1alpha)
@@ -122,8 +134,21 @@ pub async fn run_server(
122
134
  .max_decoding_message_size(MAX_MESSAGE_SIZE)
123
135
  .max_encoding_message_size(MAX_MESSAGE_SIZE),
124
136
  )
125
- .serve_with_shutdown(addr, shutdown_signal())
126
- .await?;
137
+ .serve_with_shutdown(addr, shutdown)
138
+ .await;
139
+
140
+ #[cfg(target_os = "linux")]
141
+ {
142
+ // Queue workers live outside tonic's request tasks. Keep the runtime
143
+ // and lease renewals alive until their results have been persisted.
144
+ shutdown_tx.send_replace(true);
145
+ if let Some(task) = consumer_task {
146
+ if let Err(error) = task.await {
147
+ tracing::error!(%error, "fnq self-consumer task failed during shutdown");
148
+ }
149
+ }
150
+ }
151
+ result?;
127
152
 
128
153
  info!("Server shut down");
129
154
  Ok(())
@@ -0,0 +1 @@
1
+ __version__ = "1.11.0"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: chalk-remote-call-python
3
- Version: 1.10.14
3
+ Version: 1.11.0
4
4
  Summary: Chalk remote call Python runtime interface client
5
5
  Author: Chalk AI, Inc.
6
6
  Project-URL: Homepage, https://chalk.ai
@@ -1 +0,0 @@
1
- __version__ = "1.10.14"