charisma-cli 0.5.1__tar.gz → 0.5.3__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 (38) hide show
  1. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/PKG-INFO +1 -1
  2. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/pyproject.toml +1 -1
  3. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/src/charisma_cli/__init__.py +1 -1
  4. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/src/charisma_cli/config.py +28 -3
  5. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/src/charisma_cli/main.py +15 -0
  6. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/src/charisma_cli/uploader.py +339 -24
  7. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/tests/test_config.py +50 -0
  8. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/tests/test_uploader.py +714 -3
  9. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/.gitignore +0 -0
  10. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/README.md +0 -0
  11. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/src/charisma_cli/launch_url.py +0 -0
  12. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/src/charisma_cli/models.py +0 -0
  13. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/src/charisma_cli/parser.py +0 -0
  14. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/src/charisma_cli/read_client.py +0 -0
  15. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/src/charisma_cli/read_models.py +0 -0
  16. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/src/charisma_cli/retry.py +0 -0
  17. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/src/charisma_cli/subprocess_mgr.py +0 -0
  18. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/src/charisma_cli/watcher.py +0 -0
  19. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/tests/__init__.py +0 -0
  20. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/tests/conftest.py +0 -0
  21. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/tests/test_bamboo_labels.py +0 -0
  22. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/tests/test_cli.py +0 -0
  23. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/tests/test_integration.py +0 -0
  24. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/tests/test_launch_url.py +0 -0
  25. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/tests/test_models.py +0 -0
  26. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/tests/test_open_launch_payload.py +0 -0
  27. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/tests/test_parser.py +0 -0
  28. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/tests/test_read_client.py +0 -0
  29. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/tests/test_read_client_attachments.py +0 -0
  30. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/tests/test_read_client_integration.py +0 -0
  31. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/tests/test_read_client_launches.py +0 -0
  32. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/tests/test_read_client_pagination.py +0 -0
  33. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/tests/test_read_client_results.py +0 -0
  34. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/tests/test_read_client_single_result.py +0 -0
  35. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/tests/test_retry.py +0 -0
  36. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/tests/test_silent_mode.py +0 -0
  37. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/tests/test_subprocess_mgr.py +0 -0
  38. {charisma_cli-0.5.1 → charisma_cli-0.5.3}/tests/test_watcher.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: charisma-cli
3
- Version: 0.5.1
3
+ Version: 0.5.3
4
4
  Summary: CLI tool that watches allure-results and streams test results + attachments to Charisma.
5
5
  Author: Charisma Team
6
6
  License-Expression: MIT
@@ -5,7 +5,7 @@ build-backend = "hatchling.build"
5
5
 
6
6
  [project]
7
7
  name = "charisma-cli"
8
- version = "0.5.1"
8
+ version = "0.5.3"
9
9
  description = "CLI tool that watches allure-results and streams test results + attachments to Charisma."
10
10
  readme = "README.md"
11
11
  license = "MIT"
@@ -4,4 +4,4 @@
4
4
  # is generated from pyproject.toml [project].version, so keeping this literal
5
5
  # equal to pyproject guarantees `--version` reports the published version. The
6
6
  # prepare-commit step owns the PATCH bump — do not hand-bump here.
7
- __version__ = "0.5.1"
7
+ __version__ = "0.5.3"
@@ -5,6 +5,10 @@ from dataclasses import dataclass
5
5
 
6
6
  import click
7
7
 
8
+ # Default drain/stop timeout in seconds when neither a flag nor an env var is
9
+ # given. Used by both drain() (stall window) and stop() (consumer-thread join).
10
+ _DEFAULT_DRAIN_TIMEOUT = 30
11
+
8
12
 
9
13
  def _resolve_env(bare_name: str) -> str | None:
10
14
  """Resolve an env var by its bare name, falling back to the CHARISMA_ prefix.
@@ -57,7 +61,7 @@ class Config:
57
61
  results: str | None = None,
58
62
  silent: bool = False,
59
63
  skip_too_big: bool = False,
60
- drain_timeout: int = 30,
64
+ drain_timeout: int | None = None,
61
65
  component: str | None = None,
62
66
  source_url: str | None = None,
63
67
  build_plan_key: str | None = None,
@@ -76,7 +80,9 @@ class Config:
76
80
  results: --results flag override
77
81
  silent: --silent flag
78
82
  skip_too_big: --skip-too-big flag
79
- drain_timeout: drain timeout in seconds
83
+ drain_timeout: --drain-timeout flag override (seconds). When None,
84
+ resolves from DRAIN_TIMEOUT / CHARISMA_DRAIN_TIMEOUT, else the
85
+ default. Governs both drain()'s stall window and stop()'s join.
80
86
  component: --component flag override (component alias within the
81
87
  project). Env: COMPONENT, fallback CHARISMA_COMPONENT.
82
88
  source_url: --source-url flag override (CI/CD build link). Env:
@@ -121,6 +127,25 @@ class Config:
121
127
  resolved_name = (_resolve_env("LAUNCH_NAME") or "").strip() or None
122
128
  resolved_tags = [t.strip() for t in (_resolve_env("TAGS") or "").split(",") if t.strip()] or None
123
129
 
130
+ # Drain/stop timeout (seconds). Resolution order mirrors the other
131
+ # metadata fields: explicit flag (drain_timeout is not None) > env
132
+ # (DRAIN_TIMEOUT, CHARISMA_DRAIN_TIMEOUT via _resolve_env) > default.
133
+ # Governs both drain()'s stall window and stop()'s join, so a large/slow
134
+ # upload can be given more time without a code change. A non-positive or
135
+ # unparseable value falls back to the default.
136
+ resolved_drain_timeout = _DEFAULT_DRAIN_TIMEOUT
137
+ if drain_timeout is not None:
138
+ resolved_drain_timeout = drain_timeout
139
+ else:
140
+ env_drain = _resolve_env("DRAIN_TIMEOUT")
141
+ if env_drain:
142
+ try:
143
+ resolved_drain_timeout = int(env_drain)
144
+ except ValueError:
145
+ resolved_drain_timeout = _DEFAULT_DRAIN_TIMEOUT
146
+ if resolved_drain_timeout <= 0:
147
+ resolved_drain_timeout = _DEFAULT_DRAIN_TIMEOUT
148
+
124
149
  # Merge Bamboo agent labels into resolved_tags (zero-config, opportunistic).
125
150
  # bamboo_agentLabelString is a space-separated list of CI agent labels set
126
151
  # automatically by Bamboo. Tokens are deduplicated against any explicit TAGS.
@@ -149,7 +174,7 @@ class Config:
149
174
  results_dir=resolved_results,
150
175
  silent=silent,
151
176
  skip_too_big=skip_too_big,
152
- drain_timeout=drain_timeout,
177
+ drain_timeout=resolved_drain_timeout,
153
178
  build_id=resolved_build_id,
154
179
  commit_sha=_resolve_env("COMMIT_SHA"),
155
180
  branch=_resolve_env("BRANCH"),
@@ -46,6 +46,7 @@ def _resolve_config(
46
46
  build_id: str | None = None,
47
47
  environment: str | None = None,
48
48
  run_key: str | None = None,
49
+ drain_timeout: int | None = None,
49
50
  ) -> Config:
50
51
  """Resolve CLI config from flags + env vars. Re-raises UsageError on failure."""
51
52
  return Config.from_env(
@@ -61,6 +62,7 @@ def _resolve_config(
61
62
  build_id=build_id,
62
63
  environment=environment,
63
64
  run_key=run_key,
65
+ drain_timeout=drain_timeout,
64
66
  )
65
67
 
66
68
 
@@ -163,6 +165,15 @@ def _common_options(func: Callable) -> Callable:
163
165
  click.option("--project", envvar="CHARISMA_PROJECT_ID", required=True, help="Project alias."),
164
166
  click.option("--silent", is_flag=True, default=False, help="Don't fail if upload errors occur."),
165
167
  click.option("--skip-too-big", is_flag=True, default=False, help="Skip result files larger than 2MB."),
168
+ click.option(
169
+ "--drain-timeout",
170
+ envvar="CHARISMA_DRAIN_TIMEOUT",
171
+ type=int,
172
+ default=None,
173
+ help="Seconds to wait with no progress before giving up draining/stopping "
174
+ "the uploader (default 30). Raise for very large/slow uploads. Also "
175
+ "reads DRAIN_TIMEOUT / CHARISMA_DRAIN_TIMEOUT.",
176
+ ),
166
177
  click.option("--component", default=None, help="Component alias within the project."),
167
178
  click.option("--source-url", default=None, help="CI/CD build link for this run."),
168
179
  click.option("--build-plan-key", default=None, help="Explicit build plan key for resolution."),
@@ -198,6 +209,7 @@ def watch(
198
209
  project: str,
199
210
  silent: bool,
200
211
  skip_too_big: bool,
212
+ drain_timeout: int | None,
201
213
  component: str | None,
202
214
  source_url: str | None,
203
215
  build_plan_key: str | None,
@@ -223,6 +235,7 @@ def watch(
223
235
  build_id,
224
236
  environment,
225
237
  run_key,
238
+ drain_timeout,
226
239
  )
227
240
 
228
241
  queue: PriorityQueue[FileEvent] = PriorityQueue()
@@ -316,6 +329,7 @@ def upload(
316
329
  project: str,
317
330
  silent: bool,
318
331
  skip_too_big: bool,
332
+ drain_timeout: int | None,
319
333
  component: str | None,
320
334
  source_url: str | None,
321
335
  build_plan_key: str | None,
@@ -340,6 +354,7 @@ def upload(
340
354
  build_id,
341
355
  environment,
342
356
  run_key,
357
+ drain_timeout,
343
358
  )
344
359
 
345
360
  queue: PriorityQueue[FileEvent] = PriorityQueue()
@@ -2,8 +2,12 @@
2
2
 
3
3
  import json
4
4
  import logging
5
+ import mimetypes
6
+ import os
7
+ import sys
5
8
  import threading
6
9
  import time
10
+ from collections.abc import Callable
7
11
  from pathlib import Path
8
12
  from queue import Empty, PriorityQueue
9
13
  from typing import Any
@@ -40,6 +44,45 @@ _CONTAINER_ASSOCIATION_TIMEOUT = 60.0
40
44
  # attachment: enough for an at-a-glance cause without approaching the field cap.
41
45
  _SPILL_INLINE_HEAD_BYTES = 2 * 1024
42
46
 
47
+ # Attachment-transport routing threshold (NOT a truncation threshold). An
48
+ # attachment whose content is at or below this size is sent via the existing
49
+ # API-Gateway multipart route (cheap single request). Anything larger is routed
50
+ # to the presigned-S3 path (presign -> PUT direct to S3 -> complete), so the
51
+ # byte transport bypasses API Gateway's hard ~10MB REST payload ceiling
52
+ # (effectively ~7.5MB after base64 + multipart envelope) and is bounded only by
53
+ # S3 / the backend's single-attachment domain policy. 5MB is a conservative
54
+ # floor well under that ceiling, leaving slack for base64 inflation (4/3) and
55
+ # the multipart envelope. Env-overridable (CHARISMA_ATTACHMENT_APIGW_SAFE_BYTES)
56
+ # for tuning without a code change; a non-positive / unparseable value falls
57
+ # back to the 5MB default.
58
+ _DEFAULT_ATTACHMENT_APIGW_SAFE_BYTES = 5 * 1024 * 1024
59
+
60
+
61
+ def _resolve_apigw_safe_bytes() -> int:
62
+ """Resolve the API-GW attachment routing threshold from env, with a safe default.
63
+
64
+ Reads ``CHARISMA_ATTACHMENT_APIGW_SAFE_BYTES`` (bytes). A missing, empty,
65
+ unparseable, or non-positive value falls back to the 5MB default so the
66
+ threshold is always a sane positive size.
67
+
68
+ Returns:
69
+ The routing threshold in bytes.
70
+ """
71
+ raw = os.getenv("CHARISMA_ATTACHMENT_APIGW_SAFE_BYTES", "").strip()
72
+ if not raw:
73
+ return _DEFAULT_ATTACHMENT_APIGW_SAFE_BYTES
74
+ try:
75
+ value = int(raw)
76
+ except ValueError:
77
+ return _DEFAULT_ATTACHMENT_APIGW_SAFE_BYTES
78
+ return value if value > 0 else _DEFAULT_ATTACHMENT_APIGW_SAFE_BYTES
79
+
80
+
81
+ # text/plain is the content type for spilled error_message / stack_trace fields
82
+ # (safe_attachment_filename always yields a ``*.txt`` name). Fixed once so the
83
+ # presign-signed Content-Type and the PUT Content-Type match byte-for-byte.
84
+ _SPILL_CONTENT_TYPE = "text/plain; charset=utf-8"
85
+
43
86
  # Sentinel expectedTests for CLI launches: the total count is unknown at open
44
87
  # time (directory-watch streaming), so we send the backend maximum. This keeps
45
88
  # the launch in 'receiving' across all appends; close_launch() finalizes it.
@@ -112,6 +155,10 @@ class Uploader:
112
155
  # avoiding the 404 an early upload would hit (attachments are validated
113
156
  # against a stored test_results.id).
114
157
  self._pending_spills: list[tuple[str, bytes, str]] = []
158
+ # Attachment-transport routing threshold (bytes). Content at or below
159
+ # this goes via the API-GW multipart route; larger content goes via the
160
+ # presigned-S3 route. Resolved once (env-overridable) at construction.
161
+ self._attachment_apigw_safe_bytes = _resolve_apigw_safe_bytes()
115
162
 
116
163
  @property
117
164
  def summary(self) -> UploadSummary:
@@ -162,15 +209,65 @@ class Uploader:
162
209
  self._thread = threading.Thread(target=self._run, daemon=True, name="charisma-uploader")
163
210
  self._thread.start()
164
211
 
165
- def stop(self) -> None:
166
- """Signal the uploader thread to exit and wait for it."""
212
+ def stop(self, timeout: float | None = None) -> None:
213
+ """Signal the uploader thread to exit, wait for it, then close the client.
214
+
215
+ Completion is owned by :meth:`drain`, which callers run FIRST: it waits
216
+ progress-based until every consumed result is sent (or the consumer
217
+ genuinely stalls). ``stop()`` is the teardown that follows — its only
218
+ jobs are to join the consumer thread and close the HTTP client.
219
+
220
+ The join timeout is CONFIGURABLE (``timeout`` arg → ``config.drain_timeout``
221
+ → module default), replacing the old hardcoded 10s that was too short for
222
+ a large/slow final flush. If the worker is STILL alive after the join —
223
+ i.e. drain() already gave up and the consumer is wedged — a loud warning
224
+ is emitted on stderr (bypassing ``--silent``, which only raises the logger
225
+ to CRITICAL) naming the unsent counts, so a dropped upload is never
226
+ invisible. The client is then closed unconditionally: the worker is a
227
+ daemon thread and the process exits immediately after, so leaving the
228
+ client open would not let a wedged request complete — it only leaks the
229
+ connection. Normal runs never reach the warning because drain() has
230
+ already finished the work before stop() is called.
231
+
232
+ Args:
233
+ timeout: Seconds to wait for the consumer thread to exit. A missing or
234
+ non-positive value falls back to ``config.drain_timeout``.
235
+ """
236
+ join_timeout = (
237
+ timeout if (timeout is not None and timeout > 0) else self._config.drain_timeout
238
+ )
167
239
  self._stop_event.set()
168
240
  if self._thread is not None:
169
- self._thread.join(timeout=10.0)
241
+ self._thread.join(timeout=join_timeout)
242
+ if self._thread.is_alive():
243
+ self._warn_stop_incomplete(join_timeout)
170
244
  if self._client is not None:
171
245
  self._client.close()
172
246
  self._client = None
173
247
 
248
+ def _warn_stop_incomplete(self, join_timeout: float) -> None:
249
+ """Warn on stderr when the consumer is still alive after the join.
250
+
251
+ Reached only when drain() already gave up and the consumer is wedged.
252
+ Routed straight to stderr (not the ``charisma_cli`` logger, which
253
+ ``--silent`` raises to CRITICAL) so a dropped/unfinished upload is never
254
+ swallowed. Names the counts and the ACTUAL join timeout used so the
255
+ operator can raise ``--drain-timeout`` or investigate connectivity.
256
+
257
+ Args:
258
+ join_timeout: The timeout (seconds) the join actually waited.
259
+ """
260
+ print(
261
+ f"Warning: uploader did not finish within {join_timeout:g}s "
262
+ f"(results_sent={self._summary.results_sent}, "
263
+ f"results_failed={self._summary.results_failed}, "
264
+ f"attachments_sent={self._summary.attachments_sent}, "
265
+ f"attachments_skipped={self._summary.attachments_skipped}). "
266
+ "Some results/attachments may not have been uploaded; raise "
267
+ "--drain-timeout or check connectivity.",
268
+ file=sys.stderr,
269
+ )
270
+
174
271
  def drain(self, timeout: float) -> bool:
175
272
  """Signal drain and wait until all consumed items are flushed/sent.
176
273
 
@@ -476,15 +573,33 @@ class Uploader:
476
573
  attachment_suffix="stack-trace",
477
574
  )
478
575
  if result.labels:
479
- # Convert Allure's [{name, value}] array to {name: value} dict
480
- # (matches batch ingestion format expected by frontend)
576
+ # 'tag' is the one MULTI-VALUED Allure label: a result can carry
577
+ # several {"name":"tag","value":...} entries. Collapsing the whole
578
+ # label list into a {name: value} dict (as before) kept only the LAST
579
+ # tag — the per-character-tags production bug (launch efad6338-…),
580
+ # where a single surviving tag string was later promoted and rendered
581
+ # one character per chip. Collect EVERY tag value into the backend's
582
+ # dedicated flat `tags` list (used verbatim by TestResultInput.
583
+ # to_canonical), de-duplicated in encounter order to match the batch/
584
+ # Allure-ZIP path (allure_parser `all_tags`). The remaining
585
+ # single-valued labels (owner, layer, issue, tms, …) still flow
586
+ # through the labels dict for the backend's promote_labels.
481
587
  labels_dict: dict[str, str] = {}
588
+ tags: list[str] = []
482
589
  for label in result.labels:
483
590
  name_key = label.get("name", "")
484
591
  value_str = label.get("value", "")
485
- if name_key and value_str:
592
+ if not name_key or not value_str:
593
+ continue
594
+ if name_key == "tag":
595
+ if value_str not in tags:
596
+ tags.append(value_str)
597
+ else:
486
598
  labels_dict[name_key] = value_str
487
- payload["labels"] = labels_dict
599
+ if labels_dict:
600
+ payload["labels"] = labels_dict
601
+ if tags:
602
+ payload["tags"] = tags
488
603
  if result.parameters:
489
604
  # Convert Allure's [{name, value}] array to {name: value} dict
490
605
  params_dict: dict[str, str] = {}
@@ -740,31 +855,65 @@ class Uploader:
740
855
  return
741
856
 
742
857
  # The no-open-launch guard lives in _post_attachment (single owner).
743
- self._post_attachment(path.name, content, result_id)
744
-
745
- def _post_attachment(self, filename: str, content: bytes, result_id: str) -> None:
746
- """POST attachment bytes to the Charisma attachment API with retry.
747
-
748
- Shared HTTP core for both file-backed attachments (``_upload_attachment``)
749
- and in-memory field spills (``_flush_pending_spills``). ``result_id`` is
750
- the backend-assigned ``test_results.id`` from the append-results response
751
- (ADR-031), sent as the ``resultId`` form field and matched exactly by the
752
- backend. Transient failures (5xx, 429, connect/timeout) are retried with
753
- exponential backoff; terminal failures count the attachment skipped and
754
- log at WARNING (a silent DEBUG-only skip is what hid the original
755
- attachments-skipped bug).
858
+ # Coerce the content type to a concrete MIME string ONCE here (never
859
+ # None): guess_type returns None for an unrecognized extension, and None
860
+ # cannot be signed/sent as a Content-Type on the presigned-S3 path (it
861
+ # would diverge from the signature). Same fallback the backend's own
862
+ # handle_upload_attachment uses.
863
+ content_type = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
864
+ self._post_attachment(path.name, content, result_id, content_type)
865
+
866
+ def _post_attachment(
867
+ self, filename: str, content: bytes, result_id: str, content_type: str
868
+ ) -> None:
869
+ """POST attachment bytes to Charisma, routing by size.
870
+
871
+ Shared entry point for both file-backed attachments (``_upload_attachment``)
872
+ and in-memory field spills (``_flush_pending_spills``). Content at or below
873
+ the API-GW routing threshold is sent via the multipart API-GW route
874
+ (``_post_attachment_apigw`` — unchanged behavior for today's normal case).
875
+ Larger content is routed to the presigned-S3 path
876
+ (``_post_attachment_via_s3``) so its byte transport bypasses the API
877
+ Gateway payload ceiling and is bounded only by S3 / the backend's
878
+ single-attachment domain policy.
879
+
880
+ ``result_id`` is the backend-assigned ``test_results.id`` from the
881
+ append-results response (ADR-031), matched exactly by the backend.
882
+ ``content_type`` is the already-coerced concrete MIME string (never None),
883
+ fixed by the caller so the presign-signed and PUT Content-Type match.
756
884
 
757
885
  Args:
758
- filename: Attachment filename sent in the multipart body.
886
+ filename: Attachment filename.
759
887
  content: Raw attachment bytes.
760
- result_id: Backend-assigned ``test_results.id`` for the owning result
761
- (from the append-results response), sent as ``resultId``.
888
+ result_id: Backend-assigned ``test_results.id`` for the owning result.
889
+ content_type: Concrete MIME type (never None).
762
890
  """
763
891
  if self._client is None or not self._launch_id:
764
892
  self._summary.attachments_skipped += 1
765
893
  logger.warning("Cannot upload attachment %s: no open launch", filename)
766
894
  return
767
895
 
896
+ if len(content) > self._attachment_apigw_safe_bytes:
897
+ self._post_attachment_via_s3(filename, content, result_id, content_type)
898
+ else:
899
+ self._post_attachment_apigw(filename, content, result_id)
900
+
901
+ def _post_attachment_apigw(self, filename: str, content: bytes, result_id: str) -> None:
902
+ """POST attachment bytes via the API-Gateway multipart route, with retry.
903
+
904
+ The original (and still default, for content at or below the routing
905
+ threshold) attachment transport: a single multipart request to
906
+ ``/api/v1/launches/{launchId}/attachments``. Transient failures (5xx,
907
+ 429, connect/timeout) are retried with exponential backoff; terminal
908
+ failures count the attachment skipped and log at WARNING (a silent
909
+ DEBUG-only skip is what hid the original attachments-skipped bug).
910
+
911
+ Args:
912
+ filename: Attachment filename sent in the multipart body.
913
+ content: Raw attachment bytes.
914
+ result_id: Backend-assigned ``test_results.id`` for the owning result
915
+ (from the append-results response), sent as ``resultId``.
916
+ """
768
917
  files = {"file": (filename, content)}
769
918
  data = {"name": filename, "resultId": result_id}
770
919
 
@@ -807,6 +956,172 @@ class Uploader:
807
956
  logger.warning("Attachment upload unexpected error for %s", filename, exc_info=True)
808
957
  return
809
958
 
959
+ def _request_with_retry(
960
+ self,
961
+ describe: str,
962
+ filename: str,
963
+ send: Callable[[], httpx.Response],
964
+ ) -> httpx.Response | None:
965
+ """Run one attachment-step request with the shared retry policy.
966
+
967
+ Centralizes the retry/backoff/terminal-skip contract used by every step
968
+ of the presigned-S3 path (presign, PUT, complete) so the three steps
969
+ cannot drift from each other or from the API-GW route. ``send`` performs
970
+ a single HTTP attempt and returns its ``httpx.Response``. Transient
971
+ failures (status in ``RETRYABLE_STATUS_CODES``, or ``ConnectError`` /
972
+ ``TimeoutException``) are retried with exponential backoff; on a terminal
973
+ outcome the attachment is counted skipped, a WARNING is logged, and
974
+ ``None`` is returned so the caller aborts the remaining steps.
975
+
976
+ Args:
977
+ describe: Short step label for the WARNING message (e.g. "presign").
978
+ filename: Attachment filename, for the WARNING message.
979
+ send: Zero-arg callable performing one HTTP attempt.
980
+
981
+ Returns:
982
+ The successful ``httpx.Response`` (status not retryable and not an
983
+ error the caller rejects), or ``None`` when the step terminally
984
+ failed (already counted skipped + logged).
985
+ """
986
+ for attempt in range(MAX_RETRIES + 1):
987
+ try:
988
+ response = send()
989
+ if response.status_code in RETRYABLE_STATUS_CODES and attempt < MAX_RETRIES:
990
+ time.sleep(exponential_backoff(attempt))
991
+ continue
992
+ return response
993
+ except (httpx.ConnectError, httpx.TimeoutException) as e:
994
+ if attempt < MAX_RETRIES:
995
+ time.sleep(exponential_backoff(attempt))
996
+ continue
997
+ self._summary.attachments_skipped += 1
998
+ logger.warning(
999
+ "Attachment %s step failed after %d retries: %s for %s",
1000
+ describe,
1001
+ MAX_RETRIES,
1002
+ e,
1003
+ filename,
1004
+ )
1005
+ return None
1006
+ return None
1007
+
1008
+ def _post_attachment_via_s3(
1009
+ self, filename: str, content: bytes, result_id: str, content_type: str
1010
+ ) -> None:
1011
+ """Upload a large attachment via presign -> direct S3 PUT -> complete.
1012
+
1013
+ Used for content larger than the API-GW routing threshold. The bytes go
1014
+ straight to S3 over a presigned PUT, bypassing API Gateway's payload
1015
+ ceiling; only two small JSON requests (presign, complete) traverse the
1016
+ API. This is the path that makes the attachment size bounded by S3 /
1017
+ the backend single-attachment policy rather than by API Gateway.
1018
+
1019
+ Contract matched to ``_post_attachment_apigw``: a fully successful
1020
+ round-trip increments ``attachments_sent``; any terminal step failure
1021
+ increments ``attachments_skipped`` (once) with a WARNING. Each step uses
1022
+ the shared retry/backoff policy.
1023
+
1024
+ Two hard requirements on the S3 PUT (see design):
1025
+ - The PUT ``Content-Type`` header equals ``content_type`` byte-for-byte
1026
+ (the string the backend signed into the URL), else S3 returns 403
1027
+ SignatureDoesNotMatch.
1028
+ - The PUT goes through a SEPARATE httpx client with NO ``Authorization``
1029
+ header. ``self._client`` carries a client-level Bearer that httpx
1030
+ merges into every request (a per-request override does not remove it),
1031
+ which must never be sent to S3 — the presigned URL is self-authorizing.
1032
+
1033
+ Args:
1034
+ filename: Attachment filename.
1035
+ content: Raw attachment bytes.
1036
+ result_id: Backend-assigned ``test_results.id`` for the owning result.
1037
+ content_type: Concrete MIME type, signed into the presigned URL and
1038
+ echoed verbatim on the PUT and complete steps.
1039
+ """
1040
+ presign_body = {
1041
+ "resultId": result_id,
1042
+ "name": filename,
1043
+ "contentType": content_type,
1044
+ "size": len(content),
1045
+ }
1046
+ presign_resp = self._request_with_retry(
1047
+ "presign",
1048
+ filename,
1049
+ lambda: self._client.post(
1050
+ f"/api/v1/launches/{self._launch_id}/attachments/presign",
1051
+ json=presign_body,
1052
+ ),
1053
+ )
1054
+ if presign_resp is None:
1055
+ return
1056
+ if presign_resp.status_code != 201:
1057
+ self._summary.attachments_skipped += 1
1058
+ logger.warning(
1059
+ "Attachment presign failed: HTTP %d for %s",
1060
+ presign_resp.status_code,
1061
+ filename,
1062
+ )
1063
+ return
1064
+
1065
+ try:
1066
+ presign_data = presign_resp.json()
1067
+ upload_url = presign_data["uploadUrl"]
1068
+ attachment_id = presign_data["attachmentId"]
1069
+ s3_key = presign_data["s3Key"]
1070
+ except (ValueError, json.JSONDecodeError, KeyError, TypeError):
1071
+ self._summary.attachments_skipped += 1
1072
+ logger.warning("Attachment presign returned a malformed body for %s", filename)
1073
+ return
1074
+
1075
+ # Direct S3 PUT: separate client, NO Authorization, Content-Type must
1076
+ # match the signed value exactly.
1077
+ put_resp = self._request_with_retry(
1078
+ "S3 PUT",
1079
+ filename,
1080
+ lambda: httpx.put(
1081
+ upload_url,
1082
+ content=content,
1083
+ headers={"Content-Type": content_type},
1084
+ timeout=60.0,
1085
+ ),
1086
+ )
1087
+ if put_resp is None:
1088
+ return
1089
+ if put_resp.status_code not in (200, 201):
1090
+ self._summary.attachments_skipped += 1
1091
+ logger.warning(
1092
+ "Attachment S3 PUT failed: HTTP %d for %s",
1093
+ put_resp.status_code,
1094
+ filename,
1095
+ )
1096
+ return
1097
+
1098
+ complete_body = {
1099
+ "attachmentId": attachment_id,
1100
+ "resultId": result_id,
1101
+ "name": filename,
1102
+ "contentType": content_type,
1103
+ "s3Key": s3_key,
1104
+ }
1105
+ complete_resp = self._request_with_retry(
1106
+ "complete",
1107
+ filename,
1108
+ lambda: self._client.post(
1109
+ f"/api/v1/launches/{self._launch_id}/attachments/complete",
1110
+ json=complete_body,
1111
+ ),
1112
+ )
1113
+ if complete_resp is None:
1114
+ return
1115
+ if complete_resp.status_code == 201:
1116
+ self._summary.attachments_sent += 1
1117
+ return
1118
+ self._summary.attachments_skipped += 1
1119
+ logger.warning(
1120
+ "Attachment complete failed: HTTP %d for %s",
1121
+ complete_resp.status_code,
1122
+ filename,
1123
+ )
1124
+
810
1125
  def _flush_pending_spills(self) -> None:
811
1126
  """Upload buffered oversized-field spills after results are persisted.
812
1127
 
@@ -830,7 +1145,7 @@ class Uploader:
830
1145
  history_id,
831
1146
  )
832
1147
  continue
833
- self._post_attachment(filename, content, result_id)
1148
+ self._post_attachment(filename, content, result_id, _SPILL_CONTENT_TYPE)
834
1149
 
835
1150
  def _try_associate_containers(self) -> None:
836
1151
  """Try to associate buffered containers with known results."""
@@ -381,3 +381,53 @@ class TestConfigLaunchMetadata:
381
381
  assert config.build_plan_key == "BI-KDLQA"
382
382
  assert config.build_id == "22"
383
383
  assert config.environment == "qa3"
384
+
385
+
386
+ class TestConfigDrainTimeout:
387
+ """drain_timeout is configurable via flag + env (watch data-loss fix).
388
+
389
+ Before: Config.drain_timeout existed but was ALWAYS the default 30 — no CLI
390
+ flag or env var reached it, and Uploader.stop()'s join was a separate
391
+ hardcoded 10s. A large/slow upload could neither be given more drain time
392
+ nor kept from being abandoned. These tests pin the plumbing: an explicit
393
+ flag wins, an env var is honored, and the default is preserved.
394
+ """
395
+
396
+ def test_drain_timeout_flag_overrides_default(
397
+ self, monkeypatch: pytest.MonkeyPatch
398
+ ) -> None:
399
+ monkeypatch.setenv("CHARISMA_ENDPOINT", "https://api.example.com")
400
+ monkeypatch.setenv("CHARISMA_TOKEN", "tok")
401
+ monkeypatch.setenv("CHARISMA_PROJECT_ID", "proj")
402
+ monkeypatch.delenv("CHARISMA_DRAIN_TIMEOUT", raising=False)
403
+ monkeypatch.delenv("DRAIN_TIMEOUT", raising=False)
404
+
405
+ config = Config.from_env(drain_timeout=120)
406
+
407
+ assert config.drain_timeout == 120
408
+
409
+ def test_drain_timeout_resolves_from_env(
410
+ self, monkeypatch: pytest.MonkeyPatch
411
+ ) -> None:
412
+ monkeypatch.setenv("CHARISMA_ENDPOINT", "https://api.example.com")
413
+ monkeypatch.setenv("CHARISMA_TOKEN", "tok")
414
+ monkeypatch.setenv("CHARISMA_PROJECT_ID", "proj")
415
+ monkeypatch.setenv("DRAIN_TIMEOUT", "90")
416
+
417
+ # No explicit flag → env var must be honored.
418
+ config = Config.from_env()
419
+
420
+ assert config.drain_timeout == 90
421
+
422
+ def test_drain_timeout_defaults_to_30(
423
+ self, monkeypatch: pytest.MonkeyPatch
424
+ ) -> None:
425
+ monkeypatch.setenv("CHARISMA_ENDPOINT", "https://api.example.com")
426
+ monkeypatch.setenv("CHARISMA_TOKEN", "tok")
427
+ monkeypatch.setenv("CHARISMA_PROJECT_ID", "proj")
428
+ monkeypatch.delenv("CHARISMA_DRAIN_TIMEOUT", raising=False)
429
+ monkeypatch.delenv("DRAIN_TIMEOUT", raising=False)
430
+
431
+ config = Config.from_env()
432
+
433
+ assert config.drain_timeout == 30