csync-local 0.1.0__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.
Files changed (98) hide show
  1. csync_local-0.1.0.dist-info/METADATA +251 -0
  2. csync_local-0.1.0.dist-info/RECORD +98 -0
  3. csync_local-0.1.0.dist-info/WHEEL +5 -0
  4. csync_local-0.1.0.dist-info/entry_points.txt +2 -0
  5. csync_local-0.1.0.dist-info/licenses/LICENSE +21 -0
  6. csync_local-0.1.0.dist-info/top_level.txt +1 -0
  7. localcsync/__init__.py +3 -0
  8. localcsync/__main__.py +6 -0
  9. localcsync/_vendor/VENDORED_FROM +1 -0
  10. localcsync/_vendor/__init__.py +1 -0
  11. localcsync/_vendor/csync/backend/app/__init__.py +2 -0
  12. localcsync/_vendor/csync/backend/app/log_redaction.py +66 -0
  13. localcsync/_vendor/csync/backend/app/runtime_assets/__init__.py +1 -0
  14. localcsync/_vendor/csync/backend/app/runtime_assets/contract.py +168 -0
  15. localcsync/_vendor/csync/backend/app/sentry.py +415 -0
  16. localcsync/_vendor/csync/backend/app/validation/__init__.py +0 -0
  17. localcsync/_vendor/csync/backend/app/validation/codebuild_entry.py +96 -0
  18. localcsync/_vendor/csync/backend/app/validation/codebuild_run.py +291 -0
  19. localcsync/_vendor/csync/backend/app/validation/config_yaml_check/__init__.py +14 -0
  20. localcsync/_vendor/csync/backend/app/validation/config_yaml_check/checker.py +170 -0
  21. localcsync/_vendor/csync/backend/app/validation/config_yaml_check/gather.py +72 -0
  22. localcsync/_vendor/csync/backend/app/validation/config_yaml_check/prompt.py +121 -0
  23. localcsync/_vendor/csync/backend/app/validation/config_yaml_check/rules.py +823 -0
  24. localcsync/_vendor/csync/backend/app/validation/datetime_utc/__init__.py +0 -0
  25. localcsync/_vendor/csync/backend/app/validation/datetime_utc/checker.py +145 -0
  26. localcsync/_vendor/csync/backend/app/validation/datetime_utc/gather.py +541 -0
  27. localcsync/_vendor/csync/backend/app/validation/docker_manager.py +726 -0
  28. localcsync/_vendor/csync/backend/app/validation/engine.py +2787 -0
  29. localcsync/_vendor/csync/backend/app/validation/env_validator/__init__.py +0 -0
  30. localcsync/_vendor/csync/backend/app/validation/env_validator/batch_validators.py +238 -0
  31. localcsync/_vendor/csync/backend/app/validation/env_validator/models.py +64 -0
  32. localcsync/_vendor/csync/backend/app/validation/env_validator/utils/__init__.py +0 -0
  33. localcsync/_vendor/csync/backend/app/validation/env_validator/utils/async_http.py +233 -0
  34. localcsync/_vendor/csync/backend/app/validation/env_validator/utils/docker_utils.py +334 -0
  35. localcsync/_vendor/csync/backend/app/validation/env_validator/utils/http_utils.py +338 -0
  36. localcsync/_vendor/csync/backend/app/validation/env_validator/utils/port_utils.py +113 -0
  37. localcsync/_vendor/csync/backend/app/validation/env_validator/validators.py +661 -0
  38. localcsync/_vendor/csync/backend/app/validation/eval_awareness/__init__.py +0 -0
  39. localcsync/_vendor/csync/backend/app/validation/eval_awareness/checker.py +565 -0
  40. localcsync/_vendor/csync/backend/app/validation/external_network.py +1691 -0
  41. localcsync/_vendor/csync/backend/app/validation/feature_coverage/__init__.py +0 -0
  42. localcsync/_vendor/csync/backend/app/validation/feature_coverage/checker.py +97 -0
  43. localcsync/_vendor/csync/backend/app/validation/feature_coverage/gather.py +385 -0
  44. localcsync/_vendor/csync/backend/app/validation/file_scope.py +293 -0
  45. localcsync/_vendor/csync/backend/app/validation/fingerprint.py +265 -0
  46. localcsync/_vendor/csync/backend/app/validation/github_reporter.py +493 -0
  47. localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/__init__.py +0 -0
  48. localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/checker.py +275 -0
  49. localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/fetch.py +491 -0
  50. localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/keys.py +106 -0
  51. localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/manifest.py +164 -0
  52. localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/models.py +50 -0
  53. localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/reference.py +115 -0
  54. localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/scanner.py +169 -0
  55. localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/search_provider.py +200 -0
  56. localcsync/_vendor/csync/backend/app/validation/live_log.py +135 -0
  57. localcsync/_vendor/csync/backend/app/validation/mcp_parity/__init__.py +9 -0
  58. localcsync/_vendor/csync/backend/app/validation/mcp_parity/detect.py +164 -0
  59. localcsync/_vendor/csync/backend/app/validation/mcp_parity/prompt.py +161 -0
  60. localcsync/_vendor/csync/backend/app/validation/mcp_parity/runner.py +115 -0
  61. localcsync/_vendor/csync/backend/app/validation/multi_rl/__init__.py +35 -0
  62. localcsync/_vendor/csync/backend/app/validation/multi_rl/app_contract.py +378 -0
  63. localcsync/_vendor/csync/backend/app/validation/multi_rl/ci_image.py +542 -0
  64. localcsync/_vendor/csync/backend/app/validation/multi_rl/em_dash.py +225 -0
  65. localcsync/_vendor/csync/backend/app/validation/multi_rl/findings.py +157 -0
  66. localcsync/_vendor/csync/backend/app/validation/multi_rl/image_checks.py +876 -0
  67. localcsync/_vendor/csync/backend/app/validation/multi_rl/pins.py +357 -0
  68. localcsync/_vendor/csync/backend/app/validation/multi_rl/profile_config.py +328 -0
  69. localcsync/_vendor/csync/backend/app/validation/multi_rl/runner.py +356 -0
  70. localcsync/_vendor/csync/backend/app/validation/multi_rl/secrets.py +241 -0
  71. localcsync/_vendor/csync/backend/app/validation/multi_rl/seed_cache.py +112 -0
  72. localcsync/_vendor/csync/backend/app/validation/multi_rl/suite_rules.py +424 -0
  73. localcsync/_vendor/csync/backend/app/validation/naming_audit/__init__.py +6 -0
  74. localcsync/_vendor/csync/backend/app/validation/naming_audit/candidates.py +159 -0
  75. localcsync/_vendor/csync/backend/app/validation/naming_audit/detectors.py +166 -0
  76. localcsync/_vendor/csync/backend/app/validation/naming_audit/prompt.py +181 -0
  77. localcsync/_vendor/csync/backend/app/validation/naming_audit/providers.py +137 -0
  78. localcsync/_vendor/csync/backend/app/validation/naming_audit/runner.py +206 -0
  79. localcsync/_vendor/csync/backend/app/validation/recovery.py +680 -0
  80. localcsync/_vendor/csync/backend/app/validation/registry.py +615 -0
  81. localcsync/_vendor/csync/backend/app/validation/restricted_terms/__init__.py +0 -0
  82. localcsync/_vendor/csync/backend/app/validation/restricted_terms/checker.py +321 -0
  83. localcsync/_vendor/csync/backend/app/validation/runtime_assets.py +121 -0
  84. localcsync/_vendor/csync/backend/app/validation/seed_paths.py +7 -0
  85. localcsync/_vendor/csync/backend/app/validation/single_rl_checks.py +326 -0
  86. localcsync/_vendor/csync/backend/app/validation/worker.py +210 -0
  87. localcsync/_vendor/csync/backend/tools/feature-mapping/action-facts.mjs +142 -0
  88. localcsync/_vendor/csync/backend/tools/feature-mapping/census.mjs +53 -0
  89. localcsync/_vendor/csync/backend/tools/feature-mapping/chain-facts.mjs +286 -0
  90. localcsync/_vendor/csync/backend/tools/feature-mapping/extract.mjs +806 -0
  91. localcsync/_vendor/csync/backend/tools/feature-mapping/keyboard-chords.mjs +211 -0
  92. localcsync/_vendor/csync/backend/tools/feature-mapping/package-lock.json +132 -0
  93. localcsync/_vendor/csync/backend/tools/feature-mapping/package.json +13 -0
  94. localcsync/cli.py +749 -0
  95. localcsync/docker_mode.py +351 -0
  96. localcsync/llm.py +138 -0
  97. localcsync/runtime.py +68 -0
  98. localcsync/verdicts.py +115 -0
@@ -0,0 +1,415 @@
1
+ """Error reporting to Sentry, for every process the backend image runs.
2
+
3
+ Each process calls ``init_sentry(service)`` once, early in its entry point: the API
4
+ (app.main), the RQ workers (app.rq_worker), the loops worker-entrypoint.sh starts beside
5
+ them, both Temporal workers, and the migration step before the API boots. ``service``
6
+ becomes a tag, so one Sentry project can be filtered by process.
7
+
8
+ Nothing happens without SENTRY_DSN, so development, CI and the test suite run exactly as
9
+ before. The settings are read straight from the environment rather than through
10
+ app.config: Settings refuses to load in production without its secrets, and the error
11
+ that refusal raises is one this module should be able to report.
12
+
13
+ This backend holds people's OpenAI, Anthropic and GitHub credentials, so nothing leaves
14
+ for Sentry unscrubbed: no request bodies, no local variables unless asked for, a denylist
15
+ of credential-named keys applied at every depth, and ``_redact_event`` taking credential-
16
+ shaped strings out of messages, breadcrumbs and anything else in the event.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import asyncio
21
+ import logging
22
+ import os
23
+ import re
24
+ import sys
25
+ import threading
26
+ import time
27
+ from collections import OrderedDict
28
+ from typing import Any
29
+
30
+ log = logging.getLogger(__name__)
31
+
32
+ #: Keys whose values are dropped wherever they appear in an event (headers, cookies,
33
+ #: extra, breadcrumb data, frame variables), matched whole and case-insensitively.
34
+ #: Header names arrive with dashes and WSGI-style names with underscores, so both.
35
+ DENYLIST = [
36
+ "authorization", "proxy-authorization", "cookie", "set-cookie", "set_cookie",
37
+ "x-api-key", "x_api_key", "api_key", "api-key", "apikey",
38
+ "token", "access_token", "refresh_token", "id_token", "github_token",
39
+ "secret", "client_secret", "password", "passwd", "private_key", "privatekey",
40
+ "dsn", "database_url", "redis_url", "openai_api_key", "anthropic_api_key",
41
+ "session", "jwt", "credentials", "x-access-token", "x-github-token",
42
+ ]
43
+
44
+ _FILTERED = "[Filtered]"
45
+
46
+ #: Credential shapes, for text the denylist cannot reach: exception messages, log lines,
47
+ #: subprocess command lines and URLs in breadcrumbs. Each group 1, where present, is kept.
48
+ _PATTERNS = [
49
+ # OpenAI (sk-..., sk-proj-...) and Anthropic (sk-ant-...) keys.
50
+ re.compile(r"\bsk-[A-Za-z0-9_\-]{16,}"),
51
+ # xAI keys (xai-...).
52
+ re.compile(r"\bxai-[A-Za-z0-9]{20,}"),
53
+ # GitHub tokens: classic and OAuth (ghp_, gho_), app (ghs_, ghu_), refresh (ghr_),
54
+ # and fine-grained personal tokens.
55
+ re.compile(r"\bgh[pousr]_[A-Za-z0-9]{20,}"),
56
+ re.compile(r"\bgithub_pat_[A-Za-z0-9_]{20,}"),
57
+ # AWS access key ids, long-lived (AKIA) and temporary (ASIA).
58
+ re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"),
59
+ # Slack tokens (the notifier's bot token).
60
+ re.compile(r"\bxox[abposr]-[A-Za-z0-9\-]{10,}"),
61
+ # JWTs: Foundry's own session tokens and GitHub App assertions.
62
+ re.compile(r"\beyJ[A-Za-z0-9_\-]{8,}\.eyJ[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]+"),
63
+ # Bearer and Basic credentials, as an Authorization header prints.
64
+ re.compile(r"(?i)(\b(?:bearer|basic)\s+)[A-Za-z0-9\-._~+/]{8,}=*"),
65
+ # The userinfo of a URL: postgres://user:pw@host, https://x-access-token:ghs_...@github.com.
66
+ # Up to the last @ of the authority, as app.log_redaction does, since a password may hold one.
67
+ re.compile(r"(://)[^/\s:@?#]*:[^/\s?#]+@"),
68
+ # key=value and "key": "value" where the key names a credential: OPENAI_API_KEY=...
69
+ # in a docker command line, ?access_token=... or X-Amz-Signature=... in a URL.
70
+ re.compile(
71
+ r"(?i)(\b[\w\-]*(?:token|secret|passw(?:or)?d|api[_\-]?key|apikey|private[_\-]?key|"
72
+ r"signature|credential)[\"']?\s*[=:]\s*[\"']?)[^\s\"'&,;]+"
73
+ ),
74
+ ]
75
+
76
+ #: Identical events from a log line within this many seconds are sent once. The worker's
77
+ #: loops (dispatcher, notifier, sweeper, status publisher) log an exception on every pass
78
+ #: while a dependency is down, every few seconds, for as long as the outage lasts; Sentry
79
+ #: needs the first, not thousands. Exceptions captured by a framework integration (a
80
+ #: failed request, a failed RQ job, a final Temporal attempt) are never throttled.
81
+ LOG_EVENT_INTERVAL_SECONDS = 60
82
+ _LOG_EVENT_KEYS_KEPT = 1000
83
+
84
+ _lock = threading.Lock() # guards the throttle's state
85
+ _init_lock = threading.Lock() # separate: init logs, and a log line can reach the throttle
86
+ _service: str | None = None
87
+ _last_sent: OrderedDict[tuple, float] = OrderedDict()
88
+
89
+
90
+ def _env(name: str, default: str = "") -> str:
91
+ return (os.environ.get(name) or "").strip() or default
92
+
93
+
94
+ def _truthy(value: str) -> bool:
95
+ return value.lower() in {"1", "true", "yes", "y", "on"}
96
+
97
+
98
+ def _sample_rate(raw: str) -> float:
99
+ try:
100
+ rate = float(raw) if raw else 0.0
101
+ except ValueError:
102
+ log.warning("SENTRY_TRACES_SAMPLE_RATE=%r is not a number; tracing stays off", raw)
103
+ return 0.0
104
+ return min(max(rate, 0.0), 1.0)
105
+
106
+
107
+ def release() -> str | None:
108
+ return _env("SENTRY_RELEASE") or _env("GIT_SHA") or _env("IMAGE_TAG") or None
109
+
110
+
111
+ def redact(text: str, secrets: list[str] | None = None) -> str:
112
+ """``text`` with credential-shaped substrings, and this process's own secrets, replaced.
113
+ NULs go first: a credential printed with one inside it would match neither."""
114
+ text = text.replace("\x00", "")
115
+ if secrets is None:
116
+ secrets = _process_secrets()
117
+ for value in secrets:
118
+ if value in text:
119
+ text = text.replace(value, _FILTERED)
120
+ for pattern in _PATTERNS:
121
+ text = pattern.sub(lambda m: (m.group(1) if m.groups() and m.group(1) else "") + _FILTERED, text)
122
+ return text
123
+
124
+
125
+ def _process_secrets() -> list[str]:
126
+ # The values app.log_redaction keeps out of logs (anything in a KEY/TOKEN/SECRET/
127
+ # PASSWORD/CRED variable, and URL passwords): matched by value, so a packed credential
128
+ # or an unusual one no pattern describes still never reaches Sentry.
129
+ try:
130
+ from .log_redaction import secret_values
131
+ return secret_values()
132
+ except Exception:
133
+ return []
134
+
135
+
136
+ def _redact_in_place(value: Any, secrets: list[str]) -> Any:
137
+ if isinstance(value, str):
138
+ return redact(value, secrets)
139
+ if isinstance(value, dict):
140
+ for key in list(value):
141
+ value[key] = _redact_in_place(value[key], secrets)
142
+ elif isinstance(value, list):
143
+ for index, item in enumerate(value):
144
+ value[index] = _redact_in_place(item, secrets)
145
+ return value
146
+
147
+
148
+ def _redact_event(event: dict) -> dict:
149
+ # The whole event, not just its messages: by the time before_send runs it is plain
150
+ # JSON-shaped data, and a credential is as harmful in a breadcrumb's URL or a frame's
151
+ # source line as in the exception text. Errors are rare enough for this to be cheap.
152
+ return _redact_in_place(event, _process_secrets())
153
+
154
+
155
+ def _ignored_errors() -> tuple[type[BaseException], ...]:
156
+ """Exceptions that are a user's or the platform's normal course, not a fault here.
157
+
158
+ Matched as classes, never by name: "ValidationError" alone would also match
159
+ pydantic's, which is a genuine bug when it escapes.
160
+ """
161
+ ignored: list[type[BaseException]] = [asyncio.CancelledError, KeyboardInterrupt, SystemExit]
162
+ try:
163
+ # A client that hung up mid-request (a GitHub webhook delivery timing out, a tab
164
+ # closed during an upload): nothing to answer and nothing of ours broke.
165
+ from starlette.requests import ClientDisconnect
166
+ ignored.append(ClientDisconnect)
167
+ except ImportError:
168
+ pass
169
+ try:
170
+ ignored += _user_caused_errors()
171
+ except Exception:
172
+ log.warning("Sentry: could not import the user-caused error classes; reporting them", exc_info=True)
173
+ try:
174
+ from temporalio.exceptions import CancelledError as TemporalCancelledError
175
+ ignored.append(TemporalCancelledError)
176
+ except ImportError:
177
+ pass
178
+ return tuple(ignored)
179
+
180
+
181
+ def _user_caused_errors() -> list[type[BaseException]]:
182
+ # A validation run failing on the RL repository it validates: build.sh missing,
183
+ # prepare.sh exiting non-zero, a clone or checkout of the user's commit failing, an
184
+ # invalid task.json. The bulk of the worker's tracebacks, and each is reported to
185
+ # the user on the job itself. A few raise sites are the host's (no free port,
186
+ # `docker run` failing); those still surface in the job's failure diagnosis.
187
+ from .validation.env_validator.models import ValidationError
188
+ # A runtime-asset or config-PR request the repository's own state refuses: no
189
+ # published asset release, a branch that changed, an unsafe asset path. Shown to the
190
+ # user who asked, who has to change something first.
191
+ from .runtime_assets.contract import AssetError
192
+ return [ValidationError, AssetError]
193
+
194
+
195
+ #: User-caused errors whose modules are too heavy to import at start (they load the
196
+ #: settings, the database and boto3, which is what init must not depend on), looked up
197
+ #: only once something has imported them: an exception of the class means it was.
198
+ #: (module, class name), relative to this package.
199
+ _LAZY_USER_CAUSED = [
200
+ # An image build failing on the repository it builds (its Dockerfile, a missing or
201
+ # corrupt committed DB or folder ZIP, a clone of the user's branch) or cancelled by a
202
+ # person (BuildCancelled is one). The failure and its log are on the image's row;
203
+ # anything else a build raises is still reported, as an "Unexpected error".
204
+ ("image_worker", "ImageBuildError"),
205
+ # A sandbox or deploy launch a person cancelled: recorded on its row, said in Slack.
206
+ ("rl_deploy.service", "LaunchCancelled"),
207
+ ]
208
+
209
+
210
+ #: Subclasses of those that are Foundry's own failures after all, and reported.
211
+ _LAZY_REPORTED = [
212
+ # AWS, ECR or configuration failing under a build (image_worker raises these).
213
+ ("image_worker", "ImageBuildPlatformError"),
214
+ ]
215
+
216
+
217
+ def _lazy_classes(entries) -> tuple[type[BaseException], ...]:
218
+ found = []
219
+ for module_name, class_name in entries:
220
+ module = sys.modules.get(f"{__package__}.{module_name}")
221
+ cls = getattr(module, class_name, None) if module is not None else None
222
+ if isinstance(cls, type) and issubclass(cls, BaseException):
223
+ found.append(cls)
224
+ return tuple(found)
225
+
226
+
227
+ def _is_ignored(hint: dict, ignored: tuple[type[BaseException], ...]) -> bool:
228
+ exc_info = hint.get("exc_info")
229
+ if not exc_info or exc_info[0] is None:
230
+ return False
231
+ if issubclass(exc_info[0], _lazy_classes(_LAZY_REPORTED)):
232
+ return False
233
+ return issubclass(exc_info[0], ignored + _lazy_classes(_LAZY_USER_CAUSED))
234
+
235
+
236
+ def _from_log_line(event: dict) -> bool:
237
+ if not event.get("logger"):
238
+ return False
239
+ values = (event.get("exception") or {}).get("values") or []
240
+ mechanisms = {(v.get("mechanism") or {}).get("type") for v in values if isinstance(v, dict)}
241
+ return not mechanisms or mechanisms <= {"logging", None}
242
+
243
+
244
+ def _throttled(event: dict, now: float | None = None) -> bool:
245
+ if not _from_log_line(event):
246
+ return False
247
+ values = (event.get("exception") or {}).get("values") or []
248
+ entry = event.get("logentry") or {}
249
+ key = (
250
+ event.get("logger"),
251
+ entry.get("message") or event.get("message"),
252
+ values[-1].get("type") if values else None,
253
+ )
254
+ now = time.monotonic() if now is None else now
255
+ with _lock:
256
+ last = _last_sent.get(key)
257
+ if last is not None and now - last < LOG_EVENT_INTERVAL_SECONDS:
258
+ return True
259
+ _last_sent[key] = now
260
+ _last_sent.move_to_end(key)
261
+ while len(_last_sent) > _LOG_EVENT_KEYS_KEPT:
262
+ _last_sent.popitem(last=False)
263
+ return False
264
+
265
+
266
+ #: Temporal's activity and workflow loggers append the whole ``activity.info()`` dict to
267
+ #: every message ("... ({'activity_id': '1305', 'attempt': 1, ...})"), which makes each
268
+ #: activity's line its own Sentry issue. The same details are in the event's extra
269
+ #: (``temporal_activity``/``temporal_workflow``), so the suffix is taken off the message.
270
+ _TEMPORAL_LOGGERS = {"temporalio.activity", "temporalio.workflow"}
271
+ _TEMPORAL_SUFFIX = re.compile(r"\s+\(\{'(?:activity_id|attempt|namespace|workflow_id|run_id)'.*\}\)\s*$", re.S)
272
+
273
+
274
+ def _strip_temporal_suffix(event: dict) -> None:
275
+ if event.get("logger") not in _TEMPORAL_LOGGERS:
276
+ return
277
+ entry = event.get("logentry")
278
+ if isinstance(entry, dict):
279
+ for key in ("message", "formatted"):
280
+ if isinstance(entry.get(key), str):
281
+ entry[key] = _TEMPORAL_SUFFIX.sub("", entry[key])
282
+ if isinstance(event.get("message"), str):
283
+ event["message"] = _TEMPORAL_SUFFIX.sub("", event["message"])
284
+
285
+
286
+ def _make_before_send(ignored: tuple[type[BaseException], ...]):
287
+ def before_send(event, hint):
288
+ if _is_ignored(hint or {}, ignored):
289
+ return None
290
+ # Before the throttle, so it keys a Temporal line by the message Sentry gets.
291
+ _strip_temporal_suffix(event)
292
+ if _throttled(event):
293
+ return None
294
+ return _redact_event(event)
295
+ return before_send
296
+
297
+
298
+ #: Request paths never traced: the load balancer's health checks, every few seconds per
299
+ #: instance, would be a steady share of the quota at the api's trace rate and say nothing.
300
+ _UNTRACED = {"/health", "/ready", "/"}
301
+
302
+
303
+ def _before_send_transaction(event, hint):
304
+ if event.get("transaction") in _UNTRACED:
305
+ return None
306
+ return _redact_event(event)
307
+
308
+
309
+ def _tags(service: str, extra: dict[str, str] | None) -> dict[str, str]:
310
+ tags = {"service": service}
311
+ # Which Beanstalk environment, so csync-prod-veriq-worker and its -next fleet, or
312
+ # production and staging sharing a project, can be told apart.
313
+ eb_environment = _env("EB_ENVIRONMENT_NAME")
314
+ if eb_environment:
315
+ tags["eb_environment"] = eb_environment
316
+ fleet_slot = _env("VERIQ_FLEET_SLOT")
317
+ if fleet_slot:
318
+ tags["veriq_fleet_slot"] = fleet_slot
319
+ tags.update({k: v for k, v in (extra or {}).items() if v})
320
+ return tags
321
+
322
+
323
+ def init_sentry(service: str, *, tags: dict[str, str] | None = None) -> bool:
324
+ """Start reporting errors from this process as ``service``. True when reporting is on.
325
+
326
+ Idempotent: the first call in a process wins. Without SENTRY_DSN it does nothing.
327
+ Never raises: a reporting problem must not stop the process it reports on.
328
+ """
329
+ global _service
330
+ dsn = _env("SENTRY_DSN")
331
+ if not dsn:
332
+ return False
333
+ with _init_lock:
334
+ if _service is not None:
335
+ return True
336
+ try:
337
+ _init(service, dsn, tags)
338
+ except Exception:
339
+ log.exception("Sentry could not start; continuing without error reporting")
340
+ return False
341
+ _service = service
342
+ return True
343
+
344
+
345
+ def _init(service: str, dsn: str, tags: dict[str, str] | None) -> None:
346
+ import sentry_sdk
347
+ from sentry_sdk.integrations.fastapi import FastApiIntegration
348
+ from sentry_sdk.integrations.httpx import HttpxIntegration
349
+ from sentry_sdk.integrations.logging import LoggingIntegration
350
+ from sentry_sdk.integrations.rq import RqIntegration
351
+ from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration
352
+ from sentry_sdk.integrations.starlette import StarletteIntegration
353
+ from sentry_sdk.scrubber import EventScrubber
354
+
355
+ # 500 and the unexpected 5xx only. The API raises 502/503/504 on purpose to say a
356
+ # dependency (GitHub, the queue, a model provider) failed and the client should retry
357
+ # (e.g. "Cannot load branches from GitHub"); the dependency's failure is not a fault
358
+ # here, and an uncaught exception is still reported as itself. 501 is a deliberate
359
+ # "not implemented".
360
+ server_errors = {500, *range(505, 600)}
361
+ sentry_sdk.init(
362
+ dsn=dsn,
363
+ environment=_env("SENTRY_ENVIRONMENT", "development"),
364
+ release=release(),
365
+ sample_rate=1.0,
366
+ traces_sample_rate=_sample_rate(_env("SENTRY_TRACES_SAMPLE_RATE")),
367
+ send_default_pii=False,
368
+ include_local_variables=_truthy(_env("SENTRY_SEND_LOCAL_VARIABLES", "false")),
369
+ max_request_body_size="never",
370
+ event_scrubber=EventScrubber(denylist=DENYLIST, recursive=True),
371
+ before_send=_make_before_send(_ignored_errors()),
372
+ before_send_transaction=_before_send_transaction,
373
+ in_app_include=["app"],
374
+ # No sentry-trace/baggage headers on outbound requests: they go to OpenAI, Anthropic,
375
+ # GitHub, Daytona and S3, none of which is ours to trace into (as QC's api).
376
+ trace_propagation_targets=[],
377
+ # Listed rather than auto-detected: the OpenAI and Anthropic integrations would
378
+ # report every failed model call (most are a user's key out of quota, and are
379
+ # handled), and the MCP one would attach tool arguments.
380
+ auto_enabling_integrations=False,
381
+ integrations=[
382
+ # Only server_errors: an HTTPException below 500 is the API answering a
383
+ # client correctly, and 501-504 are answers it gives on purpose (above).
384
+ StarletteIntegration(failed_request_status_codes=server_errors),
385
+ FastApiIntegration(failed_request_status_codes=server_errors),
386
+ SqlalchemyIntegration(),
387
+ # Job failures. Its handler on the rq.worker logger is muted by the
388
+ # integration itself, so a failed job is one event, not two.
389
+ RqIntegration(),
390
+ HttpxIntegration(),
391
+ LoggingIntegration(level=logging.INFO, event_level=logging.ERROR),
392
+ ],
393
+ )
394
+ scope = sentry_sdk.get_global_scope()
395
+ for key, value in _tags(service, tags).items():
396
+ scope.set_tag(key, value)
397
+
398
+
399
+ def temporal_interceptors() -> list:
400
+ """The interceptors a Temporal ``Worker`` takes to report its failures (app.temporal.sentry).
401
+
402
+ Empty while reporting is off, so a worker without SENTRY_DSN runs exactly as before
403
+ and never imports the SDK.
404
+ """
405
+ if _service is None:
406
+ return []
407
+ from .temporal.sentry import interceptors
408
+ return interceptors()
409
+
410
+
411
+ def _reset_for_tests() -> None:
412
+ global _service
413
+ with _init_lock, _lock:
414
+ _service = None
415
+ _last_sent.clear()
@@ -0,0 +1,96 @@
1
+ """The validation engine's entry point when it runs on CodeBuild (infra/codebuild/validate.yml).
2
+
3
+ python -m app.validation.codebuild_entry
4
+
5
+ Everything it needs comes from the build's environment, set when the worker started it:
6
+
7
+ VALIDATION_JOB_ID the job to validate
8
+ VALIDATION_HOLDER the claim of the worker that started this build
9
+ VALIDATION_ATTEMPT which run of the job this is
10
+
11
+ This is deliberately thin. It is not a second way to validate -- it builds the same
12
+ ValidationEngine that app/validation/worker.py builds, against the same database and the
13
+ same Redis, so the job's checks, logs, progress and GitHub report are written by the same
14
+ code whichever machine runs it. What it replaces is only the part that cannot travel: the
15
+ lease.
16
+
17
+ The lease stays with the worker. That worker holds it, beats it and is following this
18
+ build; if it dies, recovery hands the job to another worker, which finds this build in the
19
+ lease's checkpoint and keeps following it rather than starting the hour again. So the
20
+ engine here is given a stand-in that answers the few questions it asks of a lease and
21
+ never claims one -- two processes beating one lease would each think the other had lost it.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import logging
26
+ import os
27
+ import sys
28
+ from uuid import UUID
29
+
30
+ logging.basicConfig(level=logging.INFO, stream=sys.stdout,
31
+ format="%(asctime)s %(levelname)s %(name)s: %(message)s")
32
+ logger = logging.getLogger("validate")
33
+
34
+
35
+ class BorrowedLease:
36
+ """A lease held by the worker following this build, as the engine sees it.
37
+
38
+ The engine asks a lease for four things: who holds it (it names its working directory
39
+ after that), which run this is, whether it has been lost, and to check in on a commit.
40
+ The first three are the worker's answers, passed in. The fourth is the worker's job and
41
+ not this process's: checking in here would lock and beat a lease this process does not
42
+ hold, and a run that lost its lease would go on writing. Instead the worker stops
43
+ following and stops the build.
44
+ """
45
+
46
+ lost = False
47
+
48
+ def __init__(self, subject: str, holder: str, attempt: int):
49
+ self.subject = subject
50
+ self.holder = holder
51
+ self.attempt = attempt
52
+
53
+ def check_in(self, session) -> None:
54
+ return None
55
+
56
+
57
+ def main() -> int:
58
+ job_id = (os.getenv("VALIDATION_JOB_ID") or "").strip()
59
+ if not job_id:
60
+ logger.error("VALIDATION_JOB_ID is not set; nothing to validate")
61
+ return 2
62
+ holder = (os.getenv("VALIDATION_HOLDER") or "codebuild").strip() or "codebuild"
63
+ try:
64
+ attempt = int(os.getenv("VALIDATION_ATTEMPT") or 1)
65
+ except ValueError:
66
+ attempt = 1
67
+
68
+ # Every model module, so SQLAlchemy can resolve ValidationJob's string-based
69
+ # relationships, exactly as app/validation/worker.py does before building an engine.
70
+ from .. import auth_models as _auth_models # noqa: F401
71
+ from .. import models as _models # noqa: F401
72
+ from .. import rbac as _rbac # noqa: F401
73
+ from .. import rl_models as _rl_models # noqa: F401
74
+ from .. import validation_models as _validation_models # noqa: F401
75
+ from ..db import SessionLocal
76
+ from .engine import ValidationEngine
77
+
78
+ lease = BorrowedLease(job_id, holder, attempt)
79
+ db = SessionLocal()
80
+ try:
81
+ logger.info("Validating job %s on CodeBuild (attempt %s, for worker %s)", job_id, attempt, holder)
82
+ result = ValidationEngine(UUID(job_id), db, lease).run()
83
+ # A validation that found problems is a finished validation, not a failed build:
84
+ # the engine has recorded the checks and the job's status, and the worker reads
85
+ # them from the job's row. Only an engine that could not run fails the build.
86
+ logger.info("Job %s ended %s", job_id, result.get("status"))
87
+ return 0
88
+ except Exception:
89
+ logger.exception("The validation of job %s could not run", job_id)
90
+ return 1
91
+ finally:
92
+ db.close()
93
+
94
+
95
+ if __name__ == "__main__":
96
+ sys.exit(main())