From d95c2430468e85bfbc1b0b602eaf2ef3ae348bc5 Mon Sep 17 00:00:00 2001 From: Akanksha Gupta Date: Wed, 18 Nov 2026 00:46:56 -0800 Subject: [PATCH] Reset Shared Pathways Service usage metrics when a session ends PiperOrigin-RevId: 1024426947 --- .../shared_pathways_service/isc_pathways.py | 40 ++- .../metrics_collector.py | 150 ++++++++++-- .../isc_pathways_test.py | 79 ++++++ .../metrics_collector_test.py | 230 ++++++++++++++++++ 4 files changed, 483 insertions(+), 16 deletions(-) diff --git a/pathwaysutils/experimental/shared_pathways_service/isc_pathways.py b/pathwaysutils/experimental/shared_pathways_service/isc_pathways.py index e730240..8c376c6 100644 --- a/pathwaysutils/experimental/shared_pathways_service/isc_pathways.py +++ b/pathwaysutils/experimental/shared_pathways_service/isc_pathways.py @@ -185,8 +185,22 @@ def _wait_for_placement( metrics_collector_inst: Any = None, start_time: float | None = None, total_chips: int = 0, + placement_complete: threading.Event | None = None, ) -> None: - """Waits for the placement to be complete by checking proxy logs.""" + """Waits for the placement to be complete by checking proxy logs. + + Args: + log_process: The process streaming the proxy pod logs. + num_slices: The number of slices to wait for. + metrics_collector_inst: The metrics collector to report placement to. + start_time: The time at which the capacity request started. + total_chips: The total number of chips requested. + placement_complete: If given, set once all slices are placed and the + placement metrics are recorded. + + Raises: + RuntimeError: If the log streaming process has no stdout. + """ _logger.info("Streaming proxy logs until the placement is complete...") keywords = [ "placement", @@ -221,12 +235,15 @@ def _wait_for_placement( ) else: _logger.info("TPU placement for %d slice(s) complete!", num_slices) + metrics_collector_inst.record_user_waiting(False) metrics_collector_inst.record_active_user(True) metrics_collector_inst.record_capacity_in_use(total_chips) if start_time: duration = time.time() - start_time metrics_collector_inst.record_assignment_time(duration) metrics_collector_inst.record_successful_request() + if placement_complete is not None: + placement_complete.set() break @@ -262,6 +279,7 @@ class _ISCPathways: metrics_collector: The metrics collector instance if enabled. start_time: The start time of the TPU assignment. total_chips: The total number of TPU chips expected across all instances. + placement_complete: Set once all TPU slices are placed. """ def __init__( @@ -311,6 +329,7 @@ def __init__( self._old_jax_backend_target_config = None self.total_chips = self._get_total_chips() self._proxy_deployed = False + self.placement_complete = threading.Event() self._cleaned_up = False self._cleanup_lock = threading.Lock() self._original_signal_handlers: dict[signal.Signals, Any] = {} @@ -498,6 +517,7 @@ def _cleanup(self) -> None: atexit.unregister(self._cleanup) self._restore_signal_handlers() + self._record_final_metrics() # Clear JAX caches and run garbage collection. _logger.info("Starting Pathways proxy cleanup.") @@ -555,6 +575,23 @@ def _cleanup(self) -> None: ) _logger.info("JAX variables restored.") + # Send the buffered metrics last, since this can wait for the Cloud + # Monitoring sampling window and should not delay releasing resources. + self.metrics_collector.close() + + def _record_final_metrics(self) -> None: + """Records the metric values for the end of this session. + + Gauges keep their last value until the time series goes stale, so reset + the ones that this session set to a non-zero value. + """ + if self.placement_complete.is_set(): + self.metrics_collector.record_active_user(False) + self.metrics_collector.record_capacity_in_use(0) + elif self._proxy_deployed: + # The user was waiting for capacity and never got it. + self.metrics_collector.record_user_waiting(False) + def _get_username() -> str: """Gets the username from the environment. @@ -698,6 +735,7 @@ def connect( t.metrics_collector, t.start_time, t.total_chips, + t.placement_complete, ), daemon=True, ) diff --git a/pathwaysutils/experimental/shared_pathways_service/metrics_collector.py b/pathwaysutils/experimental/shared_pathways_service/metrics_collector.py index d00ab4e..cd80cfb 100644 --- a/pathwaysutils/experimental/shared_pathways_service/metrics_collector.py +++ b/pathwaysutils/experimental/shared_pathways_service/metrics_collector.py @@ -1,6 +1,7 @@ """Metrics collector for Shared Pathways Service.""" import atexit +import dataclasses import logging import threading import time @@ -71,6 +72,42 @@ }, ] +# Maximum number of times to try sending a metric point before dropping it. +_MAX_SEND_ATTEMPTS = 3 + +# Maximum time in seconds to wait for the background flusher thread to stop. +_FLUSHER_JOIN_TIMEOUT_S = 5 + + +@dataclasses.dataclass +class _BufferedPoint: + """A metric point waiting to be sent to Cloud Monitoring. + + Attributes: + value: The value of the point. + value_type: The `TypedValue` field to set, for example "int64_value". + metric_labels: The labels to attach to the point. + attempts: The number of failed attempts to send the point so far. + """ + + value: Any + value_type: str + metric_labels: Dict[str, str] | None + attempts: int = 0 + + +def _is_retryable_error(error: Exception) -> bool: + """Returns whether a failed Cloud Monitoring write may succeed if retried.""" + return isinstance( + error, + ( + exceptions.DeadlineExceeded, + exceptions.InternalServerError, + exceptions.ResourceExhausted, + exceptions.ServiceUnavailable, + ), + ) + class MetricsCollector: """Collects usage metrics for Shared Pathways Service and reports to Cloud Monitoring.""" @@ -87,17 +124,23 @@ def __init__( self.client = monitoring_v3.MetricServiceClient() self.project_name = f"projects/{self.project_id}" self._lock = threading.Lock() - self._buffer: Dict[str, list[tuple[Any, str, Dict[str, str] | None]]] = {} + # Serializes flushes so that a point being sent, which may be put back in + # the buffer after a failure, is never skipped or overtaken by another + # flush. Held for all of `_shutdown()`. + self._flush_lock = threading.Lock() + self._buffer: Dict[str, list[_BufferedPoint]] = {} self._last_sent_time: Dict[str, float] = {} self._instance_id = str(uuid.uuid4()) - self._running = True + self._stop_event = threading.Event() + self._close_lock = threading.Lock() + self._closed = False for descriptor in _METRIC_DESCRIPTORS: self._create_metric_descriptor(**descriptor) self._flusher_thread = threading.Thread( target=self._flush_loop, daemon=True ) self._flusher_thread.start() - atexit.register(self._shutdown) + atexit.register(self.close) _logger.info("Metrics collection initialized.") def _create_time_series_object( @@ -134,13 +177,18 @@ def _create_time_series_object( return series def _flush_loop(self): - """Runs continuously to flush the metrics buffer.""" - while self._running: + """Runs continuously to flush the metrics buffer until stopped.""" + while not self._stop_event.is_set(): self.flush() - time.sleep(1) + self._stop_event.wait(1) def flush(self): """Sends any eligible buffered metrics to Cloud Monitoring.""" + with self._flush_lock: + self._flush_locked() + + def _flush_locked(self): + """Implements `flush()`. The caller must hold `self._flush_lock`.""" with self._lock: now = time.time() to_send = [] @@ -151,18 +199,68 @@ def flush(self): last_time = self._last_sent_time.get(metric_type, 0) # Add a slight cushion (10.5s) to prevent sub-second drift errors. if now - last_time >= 10.5 or last_time == 0: - item = queue.pop(0) - to_send.append((metric_type, *item)) + point = queue.pop(0) + to_send.append((metric_type, point)) self._last_sent_time[metric_type] = now if not queue: del self._buffer[metric_type] - for metric_type, value, value_type, metric_labels in to_send: - self._transmit(metric_type, value, value_type, metric_labels) + for metric_type, point in to_send: + if self._transmit( + metric_type, point.value, point.value_type, point.metric_labels + ): + continue + point.attempts += 1 + if point.attempts >= _MAX_SEND_ATTEMPTS: + _logger.warning( + "Dropping metric %s after %d failed attempts.", + metric_type, + point.attempts, + ) + continue + # Put the point back at the front of its queue so that it is retried + # before any newer points of the same metric. The retry waits for the + # next sampling window, which also spaces out the attempts. + with self._lock: + self._buffer.setdefault(metric_type, []).insert(0, point) + + def close(self) -> None: + """Stops background flushing and sends all buffered metrics. + + Blocks until every buffered point is sent or dropped. Cloud Monitoring + accepts at most one point per time series every 10 seconds, so this can + take about 10.5 seconds for each point still queued for a metric. Metrics + recorded after this call are dropped. + + This is safe to call more than once. If it is never called, it runs when + the interpreter exits. + """ + with self._close_lock: + if self._closed: + return + self._closed = True + atexit.unregister(self.close) + self._stop_event.set() + if self._flusher_thread is not threading.current_thread(): + self._flusher_thread.join(timeout=_FLUSHER_JOIN_TIMEOUT_S) + if self._flusher_thread.is_alive(): + _logger.warning( + "Metrics flusher thread did not stop within %s seconds.", + _FLUSHER_JOIN_TIMEOUT_S, + ) + self._shutdown() def _shutdown(self): """Synchronously drains the final state of the queue before exiting.""" - self._running = False + self._stop_event.set() + # Holding the flush lock waits for any flush in progress on the flusher + # thread, so that a point it puts back after a failure is still drained + # here, and keeps that thread from flushing until the drain is done. + with self._flush_lock: + self._drain_locked() + + def _drain_locked(self): + """Implements `_shutdown()`. The caller must hold `self._flush_lock`.""" while True: with self._lock: if not any(self._buffer.values()): @@ -181,7 +279,7 @@ def _shutdown(self): "Waiting %.1fs for Cloud Monitoring sampling window...", min_wait ) time.sleep(min_wait) - self.flush() + self._flush_locked() def _send_metric( self, @@ -191,6 +289,13 @@ def _send_metric( metric_labels: Dict[str, str] | None = None, ): """Queues a single metric in the buffer.""" + if self._closed: + _logger.warning( + "Metrics collector is closed. Dropping metric %s: %s", + metric_type, + value, + ) + return default_labels = {"client_instance_id": self._instance_id} default_labels["cluster_name"] = self.cluster_name if self.job_name: @@ -210,7 +315,9 @@ def _send_metric( metric_type, (value, value_type, default_labels), ) - self._buffer[metric_type].append((value, value_type, default_labels)) + self._buffer[metric_type].append( + _BufferedPoint(value, value_type, default_labels) + ) def _transmit( self, @@ -218,8 +325,19 @@ def _transmit( value: Any, value_type: str, metric_labels: Dict[str, str] | None = None, - ): - """Physically transmits a TimeSeries to Cloud Monitoring.""" + ) -> bool: + """Physically transmits a TimeSeries to Cloud Monitoring. + + Args: + metric_type: The metric name, without `METRIC_PREFIX`. + value: The value of the point. + value_type: The `TypedValue` field to set, for example "int64_value". + metric_labels: The labels to attach to the point. + + Returns: + False if the write failed with an error that may go away on retry, and + True otherwise, including when the write failed permanently. + """ series = self._create_time_series_object( metric_type, value, value_type, metric_labels ) @@ -230,6 +348,8 @@ def _transmit( _logger.info("Sent metric %s: %s", metric_type, value) except exceptions.GoogleAPICallError as e: _logger.warning("Failed to send metric %s: %s", metric_type, e) + return not _is_retryable_error(e) + return True def _create_metric_descriptor( self, diff --git a/pathwaysutils/test/experimental/shared_pathways_service/isc_pathways_test.py b/pathwaysutils/test/experimental/shared_pathways_service/isc_pathways_test.py index 6e16546..bac52d2 100644 --- a/pathwaysutils/test/experimental/shared_pathways_service/isc_pathways_test.py +++ b/pathwaysutils/test/experimental/shared_pathways_service/isc_pathways_test.py @@ -4,6 +4,7 @@ import os import signal import subprocess +import threading from unittest import mock from absl import flags @@ -40,14 +41,18 @@ def test_wait_for_placement_success(self): " -> placed\n" ) mock_metrics_collector = mock.Mock() + placement_complete = threading.Event() isc_pathways._wait_for_placement( mock_process, num_slices=1, metrics_collector_inst=mock_metrics_collector, + placement_complete=placement_complete, ) mock_metrics_collector.record_active_user.assert_called_once_with(True) + mock_metrics_collector.record_user_waiting.assert_called_once_with(False) + self.assertTrue(placement_complete.is_set()) def test_wait_for_placement_empty_stdout_raises(self): """Tests that _wait_for_placement terminates and raises if stdout is None.""" @@ -593,6 +598,12 @@ def test_isc_pathways(self): mock_collector_instance.record_requested_capacity.assert_called_once_with( 64 ) + # The proxy was deployed but placement never completed, so the user stops + # waiting when the session ends. + mock_collector_instance.record_user_waiting.assert_has_calls( + [mock.call(True), mock.call(False)] + ) + mock_collector_instance.close.assert_called_once() mock_run.assert_called_with( [ "kubectl", @@ -791,6 +802,7 @@ def test_connect_success(self): mock_manager_instance.metrics_collector, mock_manager_instance.start_time, mock_manager_instance.total_chips, + mock_manager_instance.placement_complete, ), daemon=True, ) @@ -1546,6 +1558,73 @@ def test_is_alive_false_after_port_forward_exits(self): manager._port_forward_process = mock_pf_proc self.assertFalse(manager.is_alive()) + def _create_manager_with_mock_metrics(self): + """Creates an _ISCPathways whose metrics collector is a mock.""" + manager = isc_pathways._ISCPathways( + cluster="test-cluster", + project="test-project", + region="test-region", + gcs_bucket="test-bucket", + pathways_service="test-service:1234", + expected_tpu_instances={"tpuv6e:2x2": 1}, + proxy_job_name="test-proxy", + proxy_server_image="test-image", + ) + manager.metrics_collector = mock.Mock() + self.enter_context( + mock.patch.object( + isc_pathways.gke_utils, "delete_gke_resource", autospec=True + ) + ) + return manager + + def test_cleanup_after_placement_resets_usage_metrics_and_closes(self): + manager = self._create_manager_with_mock_metrics() + manager._proxy_deployed = True + manager.placement_complete.set() + + manager._cleanup() + + collector = manager.metrics_collector + collector.record_active_user.assert_called_once_with(False) + collector.record_capacity_in_use.assert_called_once_with(0) + collector.record_user_waiting.assert_not_called() + collector.close.assert_called_once() + + def test_cleanup_before_placement_resets_waiting_metric_and_closes(self): + manager = self._create_manager_with_mock_metrics() + manager._proxy_deployed = True + + manager._cleanup() + + collector = manager.metrics_collector + collector.record_user_waiting.assert_called_once_with(False) + collector.record_active_user.assert_not_called() + collector.record_capacity_in_use.assert_not_called() + collector.close.assert_called_once() + + def test_cleanup_without_deployed_proxy_only_closes_metrics(self): + manager = self._create_manager_with_mock_metrics() + + manager._cleanup() + + collector = manager.metrics_collector + collector.record_user_waiting.assert_not_called() + collector.record_active_user.assert_not_called() + collector.record_capacity_in_use.assert_not_called() + collector.close.assert_called_once() + + def test_cleanup_twice_closes_metrics_once(self): + manager = self._create_manager_with_mock_metrics() + manager._proxy_deployed = True + manager.placement_complete.set() + + manager._cleanup() + manager._cleanup() + + manager.metrics_collector.record_active_user.assert_called_once_with(False) + manager.metrics_collector.close.assert_called_once() + def test_connect_auto_detect_proxy_image_success(self): """Tests that connect auto-detects compatible proxy image when not provided.""" self.enter_context(mock.patch.dict(os.environ, {"USER": "testuser"})) diff --git a/pathwaysutils/test/experimental/shared_pathways_service/metrics_collector_test.py b/pathwaysutils/test/experimental/shared_pathways_service/metrics_collector_test.py index 9f8f3d5..f6ce6be 100644 --- a/pathwaysutils/test/experimental/shared_pathways_service/metrics_collector_test.py +++ b/pathwaysutils/test/experimental/shared_pathways_service/metrics_collector_test.py @@ -1,5 +1,6 @@ """Unit tests for the MetricsCollector class.""" +import threading from unittest import mock from absl.testing import absltest from pathwaysutils.experimental.shared_pathways_service import metrics_collector @@ -242,6 +243,235 @@ def mock_time_func(): self.assertEqual(mock_client.create_time_series.call_count, 2) mock_sleep.assert_called() + def _create_collector_without_flusher(self, mock_client_class): + """Creates a collector whose background flusher thread is stopped.""" + mock_client = mock.Mock() + mock_client_class.return_value = mock_client + collector = metrics_collector.MetricsCollector("gcp_project", "gke_cluster") + collector._stop_event.set() + collector._flusher_thread.join() + return collector, mock_client + + def _flush_after_sampling_window(self, collector, metric_type): + """Flushes as if the Cloud Monitoring sampling window has passed.""" + with mock.patch( + "time.time", + return_value=collector._last_sent_time[metric_type] + 11.0, + ): + collector.flush() + + @mock.patch( + "pathwaysutils.experimental.shared_pathways_service.metrics_collector.monitoring_v3.MetricServiceClient" + ) + def test_flush_retries_point_after_transient_error(self, mock_client_class): + collector, mock_client = self._create_collector_without_flusher( + mock_client_class + ) + mock_client.create_time_series.side_effect = [ + metrics_collector.exceptions.ServiceUnavailable("unavailable"), + None, + ] + collector.record_capacity_in_use(16) + collector.record_capacity_in_use(0) + + collector.flush() + + # The failed point goes back to the front of the queue. + queue = collector._buffer["capacity_in_use"] + self.assertEqual([point.value for point in queue], [16, 0]) + self.assertEqual(queue[0].attempts, 1) + + self._flush_after_sampling_window(collector, "capacity_in_use") + + self.assertEqual(mock_client.create_time_series.call_count, 2) + _, kwargs = mock_client.create_time_series.call_args + self.assertEqual( + kwargs["time_series"][0].points[0].value.int64_value, 16 + ) + self.assertEqual( + [point.value for point in collector._buffer["capacity_in_use"]], [0] + ) + + @mock.patch( + "pathwaysutils.experimental.shared_pathways_service.metrics_collector.monitoring_v3.MetricServiceClient" + ) + def test_flush_drops_point_after_permanent_error(self, mock_client_class): + collector, mock_client = self._create_collector_without_flusher( + mock_client_class + ) + mock_client.create_time_series.side_effect = ( + metrics_collector.exceptions.InvalidArgument("written too frequently") + ) + collector.record_capacity_in_use(16) + + collector.flush() + + mock_client.create_time_series.assert_called_once() + self.assertNotIn("capacity_in_use", collector._buffer) + + @mock.patch( + "pathwaysutils.experimental.shared_pathways_service.metrics_collector.monitoring_v3.MetricServiceClient" + ) + def test_flush_drops_point_after_max_attempts(self, mock_client_class): + collector, mock_client = self._create_collector_without_flusher( + mock_client_class + ) + mock_client.create_time_series.side_effect = ( + metrics_collector.exceptions.ServiceUnavailable("unavailable") + ) + collector.record_capacity_in_use(16) + + collector.flush() + for _ in range(metrics_collector._MAX_SEND_ATTEMPTS - 1): + self._flush_after_sampling_window(collector, "capacity_in_use") + + self.assertEqual( + mock_client.create_time_series.call_count, + metrics_collector._MAX_SEND_ATTEMPTS, + ) + self.assertNotIn("capacity_in_use", collector._buffer) + + @mock.patch( + "pathwaysutils.experimental.shared_pathways_service.metrics_collector.monitoring_v3.MetricServiceClient" + ) + def test_shutdown_retries_transient_errors(self, mock_client_class): + collector, mock_client = self._create_collector_without_flusher( + mock_client_class + ) + mock_client.create_time_series.side_effect = [ + metrics_collector.exceptions.DeadlineExceeded("deadline"), + None, + ] + collector.record_capacity_in_use(0) + + current_time = [1000.0] + + def mock_sleep_func(seconds): + current_time[0] += seconds + + with mock.patch("time.sleep", side_effect=mock_sleep_func): + with mock.patch("time.time", side_effect=lambda: current_time[0]): + collector._shutdown() + + self.assertEqual(mock_client.create_time_series.call_count, 2) + self.assertNotIn("capacity_in_use", collector._buffer) + + @mock.patch( + "pathwaysutils.experimental.shared_pathways_service.metrics_collector.monitoring_v3.MetricServiceClient" + ) + def test_shutdown_drains_retry_from_flush_in_progress( + self, mock_client_class + ): + collector, mock_client = self._create_collector_without_flusher( + mock_client_class + ) + first_send_started = threading.Event() + release_first_send = threading.Event() + + def create_time_series(**kwargs): + del kwargs + if not first_send_started.is_set(): + first_send_started.set() + release_first_send.wait() + raise metrics_collector.exceptions.DeadlineExceeded("deadline") + + mock_client.create_time_series.side_effect = create_time_series + collector.record_capacity_in_use(0) + + # Signals when `_shutdown()` starts waiting for the flush lock. + real_flush_lock = collector._flush_lock + shutdown_waiting = threading.Event() + + class SignalingLock: + + def __enter__(self): + if threading.current_thread() is shutdown_thread: + shutdown_waiting.set() + return real_flush_lock.__enter__() + + def __exit__(self, *args): + return real_flush_lock.__exit__(*args) + + collector._flush_lock = SignalingLock() + flush_thread = threading.Thread(target=collector.flush) + shutdown_thread = threading.Thread(target=collector._shutdown) + current_time = [1000.0] + + def mock_sleep_func(seconds): + current_time[0] += seconds + + with mock.patch("time.sleep", side_effect=mock_sleep_func): + with mock.patch("time.time", side_effect=lambda: current_time[0]): + # A flush on another thread is sending the only point when shutdown + # starts. Its send then fails and the point goes back in the buffer. + flush_thread.start() + first_send_started.wait() + shutdown_thread.start() + shutdown_waiting.wait() + release_first_send.set() + flush_thread.join() + shutdown_thread.join() + + self.assertEqual(mock_client.create_time_series.call_count, 2) + self.assertNotIn("capacity_in_use", collector._buffer) + + @mock.patch.object(metrics_collector.atexit, "unregister", autospec=True) + @mock.patch.object(metrics_collector.atexit, "register", autospec=True) + @mock.patch( + "pathwaysutils.experimental.shared_pathways_service.metrics_collector.monitoring_v3.MetricServiceClient" + ) + def test_close_stops_flusher_drains_queue_and_unregisters_atexit( + self, mock_client_class, mock_register, mock_unregister + ): + mock_client = mock.Mock() + mock_client_class.return_value = mock_client + collector = metrics_collector.MetricsCollector("gcp_project", "gke_cluster") + mock_register.assert_called_once_with(collector.close) + collector.record_capacity_in_use(16) + collector.record_capacity_in_use(0) + + current_time = [1000.0] + + def mock_sleep_func(seconds): + current_time[0] += seconds + + with mock.patch("time.sleep", side_effect=mock_sleep_func): + with mock.patch("time.time", side_effect=lambda: current_time[0]): + collector.close() + + self.assertFalse(collector._flusher_thread.is_alive()) + self.assertEqual(mock_client.create_time_series.call_count, 2) + _, kwargs = mock_client.create_time_series.call_args + self.assertEqual(kwargs["time_series"][0].points[0].value.int64_value, 0) + mock_unregister.assert_called_once_with(collector.close) + + @mock.patch.object(metrics_collector.atexit, "unregister", autospec=True) + @mock.patch( + "pathwaysutils.experimental.shared_pathways_service.metrics_collector.monitoring_v3.MetricServiceClient" + ) + def test_close_is_idempotent(self, mock_client_class, mock_unregister): + mock_client_class.return_value = mock.Mock() + collector = metrics_collector.MetricsCollector("gcp_project", "gke_cluster") + + collector.close() + collector.close() + + mock_unregister.assert_called_once_with(collector.close) + + @mock.patch( + "pathwaysutils.experimental.shared_pathways_service.metrics_collector.monitoring_v3.MetricServiceClient" + ) + def test_record_after_close_is_dropped(self, mock_client_class): + mock_client = mock.Mock() + mock_client_class.return_value = mock_client + collector = metrics_collector.MetricsCollector("gcp_project", "gke_cluster") + collector.close() + + collector.record_active_user(True) + + self.assertEmpty(collector._buffer) + mock_client.create_time_series.assert_not_called() + if __name__ == "__main__": absltest.main()