data-to-decision-copilot 0.0.1__py3-none-any.whl
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.
- d2d/__init__.py +3 -0
- d2d/alerts.py +414 -0
- d2d/api.py +493 -0
- d2d/application.py +423 -0
- d2d/aws_s3_qualification_checks.py +184 -0
- d2d/cli.py +724 -0
- d2d/connectors/__init__.py +1 -0
- d2d/connectors/base.py +73 -0
- d2d/connectors/duckdb.py +190 -0
- d2d/connectors/files.py +299 -0
- d2d/core/__init__.py +1 -0
- d2d/core/archive_copy_verification.py +435 -0
- d2d/core/archive_encryption.py +140 -0
- d2d/core/archive_signatures.py +859 -0
- d2d/core/archive_transport.py +117 -0
- d2d/core/contracts.py +187 -0
- d2d/core/decision_generation.py +492 -0
- d2d/core/decision_trace.py +153 -0
- d2d/core/decision_trace_store.py +500 -0
- d2d/core/evidence.py +81 -0
- d2d/core/evidence_store.py +418 -0
- d2d/core/isolated_query_executor.py +366 -0
- d2d/core/isolated_worker.py +86 -0
- d2d/core/journal_archive.py +324 -0
- d2d/core/journal_backup.py +130 -0
- d2d/core/journal_chain.py +661 -0
- d2d/core/journal_lock.py +99 -0
- d2d/core/journal_quiescence.py +460 -0
- d2d/core/journal_restore.py +609 -0
- d2d/core/journal_rotation.py +762 -0
- d2d/core/journal_rotation_coordinator.py +989 -0
- d2d/core/model_planning.py +201 -0
- d2d/core/offhost_archive.py +266 -0
- d2d/core/ollama_provider.py +178 -0
- d2d/core/query_planning.py +392 -0
- d2d/core/retention_anchor_dynamodb.py +156 -0
- d2d/core/retention_anchors.py +491 -0
- d2d/core/retention_policy.py +304 -0
- d2d/core/runtime.py +419 -0
- d2d/core/runtime_recovery.py +494 -0
- d2d/core/s3_archive_transport.py +387 -0
- d2d/core/semantic_evaluation.py +139 -0
- d2d/core/semantic_layer.py +79 -0
- d2d/core/semantic_planning.py +235 -0
- d2d/core/semantic_review.py +458 -0
- d2d/core/sql_executor.py +190 -0
- d2d/core/sql_guard.py +72 -0
- d2d/demo.py +73 -0
- d2d/diagnostics.py +290 -0
- d2d/identity.py +183 -0
- d2d/identity_quota.py +39 -0
- d2d/mcp.py +113 -0
- d2d/operational_events.py +483 -0
- d2d/query_history.py +299 -0
- d2d/release_fixtures.py +272 -0
- d2d/runtime_supervisor.py +224 -0
- d2d/tenant_runtime.py +204 -0
- d2d/web/index.html +336 -0
- data_to_decision_copilot-0.0.1.dist-info/METADATA +336 -0
- data_to_decision_copilot-0.0.1.dist-info/RECORD +63 -0
- data_to_decision_copilot-0.0.1.dist-info/WHEEL +4 -0
- data_to_decision_copilot-0.0.1.dist-info/entry_points.txt +2 -0
- data_to_decision_copilot-0.0.1.dist-info/licenses/LICENSE +21 -0
d2d/__init__.py
ADDED
d2d/alerts.py
ADDED
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
"""Bounded, opt-in delivery of redacted operational state transitions."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import math
|
|
8
|
+
import queue
|
|
9
|
+
import ssl
|
|
10
|
+
import threading
|
|
11
|
+
import time
|
|
12
|
+
from collections import OrderedDict
|
|
13
|
+
from collections.abc import Callable
|
|
14
|
+
from datetime import UTC, datetime
|
|
15
|
+
from typing import Any
|
|
16
|
+
from urllib.error import HTTPError, URLError
|
|
17
|
+
from urllib.parse import urlsplit
|
|
18
|
+
from urllib.request import HTTPRedirectHandler, HTTPSHandler, Request, build_opener
|
|
19
|
+
|
|
20
|
+
_LOG = logging.getLogger("d2d.alerts")
|
|
21
|
+
_ALLOWED_EVENTS = {
|
|
22
|
+
"storage_pressure_warning",
|
|
23
|
+
"storage_pressure_critical",
|
|
24
|
+
"storage_pressure_recovered",
|
|
25
|
+
"storage_probe_unavailable",
|
|
26
|
+
"journal_integrity_failure",
|
|
27
|
+
"journal_integrity_recovered",
|
|
28
|
+
"journal_storage_busy",
|
|
29
|
+
"journal_storage_full",
|
|
30
|
+
"journal_probe_recovered",
|
|
31
|
+
"journal_probe_unavailable",
|
|
32
|
+
"query_worker_start_failed",
|
|
33
|
+
"query_worker_timeout",
|
|
34
|
+
"query_worker_failed",
|
|
35
|
+
"provider_unavailable",
|
|
36
|
+
"provider_timeout",
|
|
37
|
+
"provider_malformed_response",
|
|
38
|
+
"catalog_open_failed",
|
|
39
|
+
"catalog_validation_failed",
|
|
40
|
+
"evidence_persistence_failed",
|
|
41
|
+
"decision_trace_persistence_failed",
|
|
42
|
+
"query_history_persistence_failed",
|
|
43
|
+
"background_task_failed",
|
|
44
|
+
"supervisor_started",
|
|
45
|
+
"shutdown_signal_received",
|
|
46
|
+
"shutdown_graceful",
|
|
47
|
+
"supervisor_start_failed",
|
|
48
|
+
"supervisor_force_termination_incomplete",
|
|
49
|
+
"shutdown_forced_termination",
|
|
50
|
+
"supervisor_cleanup_incomplete",
|
|
51
|
+
"supervised_child_exited",
|
|
52
|
+
}
|
|
53
|
+
_SEVERITY = {
|
|
54
|
+
"storage_pressure_warning": "warning",
|
|
55
|
+
"storage_pressure_critical": "critical",
|
|
56
|
+
"storage_pressure_recovered": "info",
|
|
57
|
+
"storage_probe_unavailable": "warning",
|
|
58
|
+
"journal_integrity_failure": "critical",
|
|
59
|
+
"journal_integrity_recovered": "info",
|
|
60
|
+
"journal_storage_busy": "warning",
|
|
61
|
+
"journal_storage_full": "critical",
|
|
62
|
+
"journal_probe_recovered": "info",
|
|
63
|
+
"journal_probe_unavailable": "warning",
|
|
64
|
+
"query_worker_start_failed": "critical",
|
|
65
|
+
"query_worker_timeout": "warning",
|
|
66
|
+
"query_worker_failed": "critical",
|
|
67
|
+
"provider_unavailable": "warning",
|
|
68
|
+
"provider_timeout": "warning",
|
|
69
|
+
"provider_malformed_response": "critical",
|
|
70
|
+
"catalog_open_failed": "critical",
|
|
71
|
+
"catalog_validation_failed": "critical",
|
|
72
|
+
"evidence_persistence_failed": "critical",
|
|
73
|
+
"decision_trace_persistence_failed": "critical",
|
|
74
|
+
"query_history_persistence_failed": "warning",
|
|
75
|
+
"background_task_failed": "critical",
|
|
76
|
+
"supervisor_started": "info",
|
|
77
|
+
"shutdown_signal_received": "info",
|
|
78
|
+
"shutdown_graceful": "info",
|
|
79
|
+
"supervisor_start_failed": "critical",
|
|
80
|
+
"supervisor_force_termination_incomplete": "critical",
|
|
81
|
+
"shutdown_forced_termination": "critical",
|
|
82
|
+
"supervisor_cleanup_incomplete": "critical",
|
|
83
|
+
"supervised_child_exited": "warning",
|
|
84
|
+
}
|
|
85
|
+
_MAX_PAYLOAD_BYTES = 4096
|
|
86
|
+
_WORKER_FAILURES = {
|
|
87
|
+
"response_limit_exceeded",
|
|
88
|
+
"malformed_response",
|
|
89
|
+
"invalid_response_type",
|
|
90
|
+
"worker_reported_error",
|
|
91
|
+
"invalid_response_schema",
|
|
92
|
+
"output_limit_violation",
|
|
93
|
+
}
|
|
94
|
+
_WORKER_ERROR_TYPES = {
|
|
95
|
+
"FileNotFoundError",
|
|
96
|
+
"PermissionError",
|
|
97
|
+
"OSError",
|
|
98
|
+
"TimeoutError",
|
|
99
|
+
"UnicodeDecodeError",
|
|
100
|
+
"JSONDecodeError",
|
|
101
|
+
"SQLValidationError",
|
|
102
|
+
"QueryExecutionError",
|
|
103
|
+
"QueryTimeoutError",
|
|
104
|
+
"QueryWorkerError",
|
|
105
|
+
"ValueError",
|
|
106
|
+
"RuntimeError",
|
|
107
|
+
"WorkerProtocolError",
|
|
108
|
+
"WorkerError",
|
|
109
|
+
"URLError",
|
|
110
|
+
"HTTPError",
|
|
111
|
+
"DuckDBConnectorError",
|
|
112
|
+
"DatabaseError",
|
|
113
|
+
"OperationalError",
|
|
114
|
+
"IntegrityError",
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def create_verified_alert_ssl_context() -> ssl.SSLContext:
|
|
119
|
+
"""Create the platform default client context with certificate verification."""
|
|
120
|
+
return ssl.create_default_context()
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def deliver_with_retry(send: Callable[[], None], *, retries: int) -> bool:
|
|
124
|
+
"""Run a bounded delivery callback with capped exponential backoff."""
|
|
125
|
+
if not 0 <= retries <= 3:
|
|
126
|
+
raise ValueError("alert retries must be between 0 and 3")
|
|
127
|
+
for attempt in range(retries + 1):
|
|
128
|
+
try:
|
|
129
|
+
send()
|
|
130
|
+
return True
|
|
131
|
+
except (HTTPError, URLError, TimeoutError, OSError) as exc:
|
|
132
|
+
if attempt >= retries:
|
|
133
|
+
_LOG.warning(
|
|
134
|
+
"Operational alert delivery failed (%s)", type(exc).__name__
|
|
135
|
+
)
|
|
136
|
+
return False
|
|
137
|
+
time.sleep(min(0.25 * (2**attempt), 1.0))
|
|
138
|
+
return False
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class NoRedirectHandler(HTTPRedirectHandler):
|
|
142
|
+
def redirect_request(
|
|
143
|
+
self, req: Request, fp: Any, code: int, msg: str, headers: Any, newurl: str
|
|
144
|
+
) -> None:
|
|
145
|
+
return None
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def build_alert_payload(event: dict[str, object]) -> dict[str, object]:
|
|
149
|
+
"""Build the deliberately small, redacted webhook payload."""
|
|
150
|
+
code = event.get("event")
|
|
151
|
+
if not isinstance(code, str) or code not in _ALLOWED_EVENTS:
|
|
152
|
+
raise ValueError("unsupported operational alert event")
|
|
153
|
+
context: dict[str, object] = {}
|
|
154
|
+
component = event.get("component")
|
|
155
|
+
if isinstance(component, str) and component in {
|
|
156
|
+
"ollama_provider", "duckdb_catalog", "evidence_store",
|
|
157
|
+
"decision_trace_store", "query_history_store", "background_task",
|
|
158
|
+
"runtime_supervisor",
|
|
159
|
+
}:
|
|
160
|
+
context["component"] = component
|
|
161
|
+
filesystem = event.get("filesystem")
|
|
162
|
+
if isinstance(filesystem, str) and filesystem and len(filesystem) <= 64:
|
|
163
|
+
context["filesystem"] = filesystem
|
|
164
|
+
journal = event.get("journal")
|
|
165
|
+
if isinstance(journal, str) and journal and len(journal) <= 64:
|
|
166
|
+
context["journal"] = journal
|
|
167
|
+
for key in ("status", "previous_status"):
|
|
168
|
+
value = event.get(key)
|
|
169
|
+
if isinstance(value, str) and value in {
|
|
170
|
+
"ok",
|
|
171
|
+
"warning",
|
|
172
|
+
"critical",
|
|
173
|
+
"unavailable",
|
|
174
|
+
"integrity_failure",
|
|
175
|
+
"transient_busy",
|
|
176
|
+
"storage_full",
|
|
177
|
+
}:
|
|
178
|
+
context[key] = value
|
|
179
|
+
free_percent = event.get("free_percent")
|
|
180
|
+
if (
|
|
181
|
+
isinstance(free_percent, (int, float))
|
|
182
|
+
and not isinstance(free_percent, bool)
|
|
183
|
+
and 0 <= float(free_percent) <= 100
|
|
184
|
+
):
|
|
185
|
+
context["free_percent"] = round(float(free_percent), 2)
|
|
186
|
+
failure = event.get("failure")
|
|
187
|
+
if isinstance(failure, str) and failure in _WORKER_FAILURES:
|
|
188
|
+
context["failure"] = failure
|
|
189
|
+
error_type = event.get("error_type")
|
|
190
|
+
if isinstance(error_type, str) and error_type in _WORKER_ERROR_TYPES:
|
|
191
|
+
context["error_type"] = error_type
|
|
192
|
+
for key in ("duration_seconds", "timeout_seconds"):
|
|
193
|
+
value = event.get(key)
|
|
194
|
+
if (
|
|
195
|
+
isinstance(value, (int, float))
|
|
196
|
+
and not isinstance(value, bool)
|
|
197
|
+
and math.isfinite(float(value))
|
|
198
|
+
and 0 <= float(value) <= 3600
|
|
199
|
+
):
|
|
200
|
+
context[key] = round(float(value), 3)
|
|
201
|
+
exit_code = event.get("exit_code")
|
|
202
|
+
if isinstance(exit_code, int) and not isinstance(exit_code, bool) and -255 <= exit_code <= 255:
|
|
203
|
+
context["exit_code"] = exit_code
|
|
204
|
+
for key in ("child_exit_code", "supervisor_exit_code"):
|
|
205
|
+
value = event.get(key)
|
|
206
|
+
if isinstance(value, int) and not isinstance(value, bool) and -255 <= value <= 255:
|
|
207
|
+
context[key] = value
|
|
208
|
+
signal_name = event.get("signal")
|
|
209
|
+
if signal_name in {"SIGINT", "SIGTERM"}:
|
|
210
|
+
context["signal"] = signal_name
|
|
211
|
+
shutdown_timeout = event.get("shutdown_timeout_seconds")
|
|
212
|
+
if (
|
|
213
|
+
isinstance(shutdown_timeout, (int, float))
|
|
214
|
+
and not isinstance(shutdown_timeout, bool)
|
|
215
|
+
and math.isfinite(float(shutdown_timeout))
|
|
216
|
+
and 0 < float(shutdown_timeout) <= 300
|
|
217
|
+
):
|
|
218
|
+
context["shutdown_timeout_seconds"] = round(float(shutdown_timeout), 3)
|
|
219
|
+
for key in ("response_bytes", "stderr_bytes"):
|
|
220
|
+
value = event.get(key)
|
|
221
|
+
if (
|
|
222
|
+
isinstance(value, int)
|
|
223
|
+
and not isinstance(value, bool)
|
|
224
|
+
and 0 <= value <= 1_048_576
|
|
225
|
+
):
|
|
226
|
+
context[key] = value
|
|
227
|
+
severity = _SEVERITY[code]
|
|
228
|
+
if code == "supervised_child_exited" and event.get("child_exit_code") == 0:
|
|
229
|
+
severity = "info"
|
|
230
|
+
payload: dict[str, object] = {
|
|
231
|
+
"event": code,
|
|
232
|
+
"severity": severity,
|
|
233
|
+
"timestamp": datetime.now(UTC).isoformat(),
|
|
234
|
+
"context": context,
|
|
235
|
+
}
|
|
236
|
+
encoded = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
|
237
|
+
if len(encoded) > _MAX_PAYLOAD_BYTES:
|
|
238
|
+
raise ValueError("operational alert payload exceeds the configured size limit")
|
|
239
|
+
return payload
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
class RedactedAlertDispatcher:
|
|
243
|
+
"""Deliver allowlisted event fields asynchronously with strict resource bounds.
|
|
244
|
+
|
|
245
|
+
The destination is an explicit HTTPS URL whose hostname must be in the
|
|
246
|
+
operator-supplied allowlist. TLS certificate verification remains enabled.
|
|
247
|
+
Delivery failure is logged locally and never changes journal state.
|
|
248
|
+
"""
|
|
249
|
+
|
|
250
|
+
def __init__(
|
|
251
|
+
self,
|
|
252
|
+
destination: str,
|
|
253
|
+
*,
|
|
254
|
+
allowed_hosts: tuple[str, ...],
|
|
255
|
+
bearer_token: str | None = None,
|
|
256
|
+
timeout_seconds: float = 3.0,
|
|
257
|
+
retries: int = 2,
|
|
258
|
+
queue_size: int = 100,
|
|
259
|
+
deduplication_window_seconds: float = 30.0,
|
|
260
|
+
deduplication_cache_size: int = 1024,
|
|
261
|
+
) -> None:
|
|
262
|
+
parsed = urlsplit(destination)
|
|
263
|
+
host = (parsed.hostname or "").lower()
|
|
264
|
+
allowed = {item.strip().lower() for item in allowed_hosts if item.strip()}
|
|
265
|
+
if (
|
|
266
|
+
parsed.scheme != "https"
|
|
267
|
+
or not host
|
|
268
|
+
or host not in allowed
|
|
269
|
+
or parsed.username is not None
|
|
270
|
+
or parsed.password is not None
|
|
271
|
+
or parsed.fragment
|
|
272
|
+
):
|
|
273
|
+
raise ValueError("alert destination must be HTTPS and match an allowed hostname")
|
|
274
|
+
if not math.isfinite(timeout_seconds) or not 0.1 <= timeout_seconds <= 10.0:
|
|
275
|
+
raise ValueError("alert timeout must be finite and between 0.1 and 10 seconds")
|
|
276
|
+
if not 0 <= retries <= 3:
|
|
277
|
+
raise ValueError("alert retries must be between 0 and 3")
|
|
278
|
+
if queue_size < 1 or queue_size > 1000:
|
|
279
|
+
raise ValueError("alert queue size must be between 1 and 1000")
|
|
280
|
+
if (
|
|
281
|
+
not math.isfinite(deduplication_window_seconds)
|
|
282
|
+
or not 0 <= deduplication_window_seconds <= 3600
|
|
283
|
+
):
|
|
284
|
+
raise ValueError("alert deduplication window must be finite and between 0 and 3600 seconds")
|
|
285
|
+
if not 1 <= deduplication_cache_size <= 10_000:
|
|
286
|
+
raise ValueError("alert deduplication cache size must be between 1 and 10000")
|
|
287
|
+
if bearer_token is not None and (len(bearer_token) < 16 or "\n" in bearer_token):
|
|
288
|
+
raise ValueError("alert bearer token must be at least 16 characters")
|
|
289
|
+
self._destination = destination
|
|
290
|
+
self._token = bearer_token
|
|
291
|
+
self._timeout = timeout_seconds
|
|
292
|
+
self._retries = retries
|
|
293
|
+
self._deduplication_window = deduplication_window_seconds
|
|
294
|
+
self._recent_events: OrderedDict[str, float] = OrderedDict()
|
|
295
|
+
self._deduplication_cache_size = deduplication_cache_size
|
|
296
|
+
self._deduplication_lock = threading.Lock()
|
|
297
|
+
self._queue: queue.Queue[dict[str, object]] = queue.Queue(maxsize=queue_size)
|
|
298
|
+
self._closed = False
|
|
299
|
+
self._stop_requested = threading.Event()
|
|
300
|
+
self._opener = build_opener(
|
|
301
|
+
NoRedirectHandler(),
|
|
302
|
+
HTTPSHandler(context=create_verified_alert_ssl_context()),
|
|
303
|
+
)
|
|
304
|
+
self._thread = threading.Thread(
|
|
305
|
+
target=self._run, name="d2d-alert-delivery", daemon=True
|
|
306
|
+
)
|
|
307
|
+
self._thread.start()
|
|
308
|
+
|
|
309
|
+
def submit(self, event: dict[str, object]) -> bool:
|
|
310
|
+
"""Queue one redacted event; return False rather than blocking when full."""
|
|
311
|
+
if self._closed:
|
|
312
|
+
return False
|
|
313
|
+
payload = build_alert_payload(event)
|
|
314
|
+
fingerprint = hashlib.sha256(
|
|
315
|
+
json.dumps(
|
|
316
|
+
{
|
|
317
|
+
"event": payload["event"],
|
|
318
|
+
"severity": payload["severity"],
|
|
319
|
+
"context": payload["context"],
|
|
320
|
+
},
|
|
321
|
+
ensure_ascii=False,
|
|
322
|
+
sort_keys=True,
|
|
323
|
+
separators=(",", ":"),
|
|
324
|
+
).encode("utf-8")
|
|
325
|
+
).hexdigest()
|
|
326
|
+
now = time.monotonic()
|
|
327
|
+
if self._deduplication_window > 0:
|
|
328
|
+
with self._deduplication_lock:
|
|
329
|
+
while self._recent_events:
|
|
330
|
+
oldest_key, oldest_at = next(iter(self._recent_events.items()))
|
|
331
|
+
if now - oldest_at <= self._deduplication_window:
|
|
332
|
+
break
|
|
333
|
+
self._recent_events.pop(oldest_key)
|
|
334
|
+
previous = self._recent_events.get(fingerprint)
|
|
335
|
+
if previous is not None and now - previous <= self._deduplication_window:
|
|
336
|
+
_LOG.info("Operational alert event deduplicated (%s)", payload["event"])
|
|
337
|
+
return False
|
|
338
|
+
self._recent_events[fingerprint] = now
|
|
339
|
+
self._recent_events.move_to_end(fingerprint)
|
|
340
|
+
while len(self._recent_events) > self._deduplication_cache_size:
|
|
341
|
+
self._recent_events.popitem(last=False)
|
|
342
|
+
try:
|
|
343
|
+
self._queue.put_nowait(payload)
|
|
344
|
+
except queue.Full:
|
|
345
|
+
if self._deduplication_window > 0:
|
|
346
|
+
with self._deduplication_lock:
|
|
347
|
+
self._recent_events.pop(fingerprint, None)
|
|
348
|
+
_LOG.warning("Operational alert queue is full; event dropped")
|
|
349
|
+
return False
|
|
350
|
+
return True
|
|
351
|
+
|
|
352
|
+
def deliver(self, payload: dict[str, object]) -> bool:
|
|
353
|
+
"""Deliver one already-redacted payload using verified HTTPS and bounded retries."""
|
|
354
|
+
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode()
|
|
355
|
+
headers = {"Content-Type": "application/json"}
|
|
356
|
+
if self._token is not None:
|
|
357
|
+
headers["Authorization"] = f"Bearer {self._token}"
|
|
358
|
+
request = Request(self._destination, data=body, headers=headers, method="POST")
|
|
359
|
+
|
|
360
|
+
def send() -> None:
|
|
361
|
+
with self._opener.open(request, timeout=self._timeout) as response:
|
|
362
|
+
if not 200 <= response.status < 300:
|
|
363
|
+
raise OSError("alert endpoint returned a non-success status")
|
|
364
|
+
|
|
365
|
+
return deliver_with_retry(send, retries=self._retries)
|
|
366
|
+
|
|
367
|
+
def _run(self) -> None:
|
|
368
|
+
while True:
|
|
369
|
+
try:
|
|
370
|
+
item = self._queue.get(timeout=0.1)
|
|
371
|
+
except queue.Empty:
|
|
372
|
+
if self._stop_requested.is_set():
|
|
373
|
+
return
|
|
374
|
+
continue
|
|
375
|
+
try:
|
|
376
|
+
self.deliver(item)
|
|
377
|
+
finally:
|
|
378
|
+
self._queue.task_done()
|
|
379
|
+
|
|
380
|
+
def wait_for_idle(self, *, timeout_seconds: float = 2.0) -> bool:
|
|
381
|
+
"""Wait for queued work to finish; intended for deterministic operator tests."""
|
|
382
|
+
deadline = time.monotonic() + max(0.0, timeout_seconds)
|
|
383
|
+
while self._queue.unfinished_tasks and time.monotonic() < deadline:
|
|
384
|
+
time.sleep(0.01)
|
|
385
|
+
return self._queue.unfinished_tasks == 0
|
|
386
|
+
|
|
387
|
+
def wait_closed(self, *, timeout_seconds: float = 1.0) -> bool:
|
|
388
|
+
"""Wait for the delivery worker to exit after close has been requested."""
|
|
389
|
+
if not math.isfinite(timeout_seconds) or not 0 <= timeout_seconds <= 10:
|
|
390
|
+
raise ValueError("alert worker wait timeout must be between 0 and 10 seconds")
|
|
391
|
+
self._thread.join(timeout_seconds)
|
|
392
|
+
return not self._thread.is_alive()
|
|
393
|
+
|
|
394
|
+
def close(self, *, drain_timeout_seconds: float = 2.0) -> None:
|
|
395
|
+
"""Bound shutdown; pending in-memory events are dropped after the deadline."""
|
|
396
|
+
if self._closed:
|
|
397
|
+
return
|
|
398
|
+
self._closed = True
|
|
399
|
+
deadline = time.monotonic() + max(0.0, drain_timeout_seconds)
|
|
400
|
+
while self._queue.unfinished_tasks and time.monotonic() < deadline:
|
|
401
|
+
time.sleep(0.02)
|
|
402
|
+
if self._queue.unfinished_tasks:
|
|
403
|
+
_LOG.warning("Operational alert queue did not drain before shutdown; dropping pending events")
|
|
404
|
+
while True:
|
|
405
|
+
try:
|
|
406
|
+
self._queue.get_nowait()
|
|
407
|
+
except queue.Empty:
|
|
408
|
+
break
|
|
409
|
+
else:
|
|
410
|
+
self._queue.task_done()
|
|
411
|
+
self._stop_requested.set()
|
|
412
|
+
self._thread.join(timeout=min(0.2, max(0.0, deadline - time.monotonic())))
|
|
413
|
+
if self._thread.is_alive():
|
|
414
|
+
_LOG.warning("Operational alert worker exceeded shutdown drain deadline")
|