cloudsprite 0.11.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 (70) hide show
  1. cloudsprite/__init__.py +451 -0
  2. cloudsprite/_antenna.py +83 -0
  3. cloudsprite/_auth.py +295 -0
  4. cloudsprite/_client.py +502 -0
  5. cloudsprite/_config.py +203 -0
  6. cloudsprite/_consent.py +104 -0
  7. cloudsprite/_context.py +945 -0
  8. cloudsprite/_exceptions.py +136 -0
  9. cloudsprite/_figure_models.py +158 -0
  10. cloudsprite/_figure_validation.py +168 -0
  11. cloudsprite/_filter_foster.py +165 -0
  12. cloudsprite/_filter_synthesis.py +400 -0
  13. cloudsprite/_filtering.py +134 -0
  14. cloudsprite/_impedance_matching.py +262 -0
  15. cloudsprite/_interpolation.py +47 -0
  16. cloudsprite/_lineage.py +775 -0
  17. cloudsprite/_link_budget.py +99 -0
  18. cloudsprite/_logging.py +53 -0
  19. cloudsprite/_mixed_mode.py +49 -0
  20. cloudsprite/_monte_carlo.py +193 -0
  21. cloudsprite/_noise_figure.py +44 -0
  22. cloudsprite/_pagination.py +130 -0
  23. cloudsprite/_parsers.py +75 -0
  24. cloudsprite/_publish.py +162 -0
  25. cloudsprite/_redact.py +179 -0
  26. cloudsprite/_response.py +63 -0
  27. cloudsprite/_resultset.py +65 -0
  28. cloudsprite/_rf_network.py +111 -0
  29. cloudsprite/_run_config.py +46 -0
  30. cloudsprite/_script_runner.py +217 -0
  31. cloudsprite/_script_workspace.py +271 -0
  32. cloudsprite/_sparameter_metrics.py +75 -0
  33. cloudsprite/_tdr.py +283 -0
  34. cloudsprite/_trace.py +112 -0
  35. cloudsprite/_version.py +23 -0
  36. cloudsprite/_visualizer.py +380 -0
  37. cloudsprite/_visualizer_cli.py +412 -0
  38. cloudsprite/_visualizer_preview.py +864 -0
  39. cloudsprite/_work_context.py +116 -0
  40. cloudsprite/_ws.py +577 -0
  41. cloudsprite/cli.py +300 -0
  42. cloudsprite/py.typed +0 -0
  43. cloudsprite/resources/__init__.py +1 -0
  44. cloudsprite/resources/_base.py +293 -0
  45. cloudsprite/resources/_models.py +50 -0
  46. cloudsprite/resources/cloudscripts.py +173 -0
  47. cloudsprite/resources/datasets.py +431 -0
  48. cloudsprite/resources/figures.py +282 -0
  49. cloudsprite/resources/instruments.py +295 -0
  50. cloudsprite/resources/notebooks.py +183 -0
  51. cloudsprite/resources/orbs.py +99 -0
  52. cloudsprite/resources/parameters.py +77 -0
  53. cloudsprite/resources/projects.py +182 -0
  54. cloudsprite/resources/related.py +125 -0
  55. cloudsprite/resources/reports.py +992 -0
  56. cloudsprite/resources/search.py +245 -0
  57. cloudsprite/resources/shares.py +229 -0
  58. cloudsprite/resources/sprites.py +15 -0
  59. cloudsprite/resources/tags.py +107 -0
  60. cloudsprite/resources/teams.py +86 -0
  61. cloudsprite/resources/traces.py +147 -0
  62. cloudsprite/resources/usage.py +152 -0
  63. cloudsprite/resources/visualizer_templates.py +466 -0
  64. cloudsprite/resources/workflows.py +59 -0
  65. cloudsprite-0.11.0.dist-info/METADATA +358 -0
  66. cloudsprite-0.11.0.dist-info/RECORD +70 -0
  67. cloudsprite-0.11.0.dist-info/WHEEL +5 -0
  68. cloudsprite-0.11.0.dist-info/entry_points.txt +3 -0
  69. cloudsprite-0.11.0.dist-info/licenses/LICENSE +21 -0
  70. cloudsprite-0.11.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,775 @@
1
+ """Lineage tracking: cs.cloudscript(), input/output recording, and run reporting.
2
+
3
+ When cloudscript() is active, the SDK posts a completed run to POST /api/script-runs/
4
+ (ScriptRunReportSchema).
5
+
6
+ Privacy / consent
7
+ -----------------
8
+ Calling cloudscript() enables provenance tracking. What leaves the machine is
9
+ documented on the public ``cloudscript`` docstring and in the README. Channels:
10
+
11
+ - **CloudScript source** — uploaded as a DataFile on each ``publish()`` only after consent: asked
12
+ once in an interactive session and stored in ``~/.cloudsprite/config``, or set by
13
+ ``upload_source=`` / ``CLOUDSPRITE_UPLOAD_SOURCE``. Cloud runs (``CS_RUN_TOKEN``) always upload.
14
+ - **Git state** — HEAD sha (+ optional ``-dirty``); never remote URL or username.
15
+ - **Error text** — exception type + message only (no traceback frames / paths).
16
+ - **Arguments** — ``sys.argv[1:]`` of a script run (not interactive sessions), redacted;
17
+ ``params=`` as passed, redacted; ``purpose`` text. Environment variables are never sent.
18
+ - **Hooks** — ``sys.excepthook`` + ``atexit`` are **opt-in** (``install_hooks=True``).
19
+
20
+ Per-channel kwargs and env vars; blanket ``CLOUDSPRITE_NO_TELEMETRY=1`` disables
21
+ source upload, git state, error text, and argv.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import atexit
27
+ import hashlib
28
+ import logging
29
+ import os
30
+ import subprocess
31
+ import sys
32
+ import uuid
33
+ import warnings
34
+ import weakref
35
+ from datetime import datetime, timezone
36
+ from pathlib import Path
37
+ from types import TracebackType
38
+ from typing import TYPE_CHECKING, Any, Callable
39
+
40
+ from cloudsprite import _consent, _redact, _work_context
41
+ from cloudsprite._version import sdk_version as _sdk_version
42
+
43
+ logger = logging.getLogger(__name__)
44
+
45
+ if TYPE_CHECKING:
46
+ from cloudsprite._context import Client
47
+
48
+ Excepthook = Callable[[type[BaseException], BaseException, TracebackType | None], Any]
49
+
50
+
51
+ # Pinned contract: error_message ≤ 10 KB client-side
52
+ _ERROR_MAX_BYTES = 10 * 1024
53
+ _SEED_MAX_CHARS = 64
54
+ _SDK_VERSION_MAX = 32
55
+ _SCRIPT_NAME_MAX = 255
56
+ _DATASET_IDS_MAX = 200
57
+ _REPORT_TIMEOUT_S = 5
58
+ _GIT_TIMEOUT_S = 2
59
+ _SCRIPT_RUNS_PATH = "/api/script-runs/"
60
+
61
+ # ---------------------------------------------------------------------------
62
+ # Defaults — one-line flips for public packaging decisions
63
+ # ---------------------------------------------------------------------------
64
+ # Source upload has no default value: it is off until the user says yes once
65
+ # (see ``_consent``), or a cloud run supplies it, or a kwarg/env var decides.
66
+ _DEFAULT_INCLUDE_GIT = True
67
+ _DEFAULT_INCLUDE_ERROR = True
68
+ _DEFAULT_INCLUDE_ARGV = True
69
+ _PURPOSE_MAX = 280
70
+ # Hooks mutate process-global state — opt-in for a public data SDK.
71
+ _DEFAULT_INSTALL_HOOKS = False
72
+
73
+ # Env vars (truthy: 1/true/yes/on)
74
+ _ENV_NO_TELEMETRY = "CLOUDSPRITE_NO_TELEMETRY"
75
+ _ENV_NO_SOURCE = "CLOUDSPRITE_NO_SOURCE_UPLOAD"
76
+ _ENV_NO_GIT = "CLOUDSPRITE_NO_GIT_STATE"
77
+ _ENV_NO_ERROR = "CLOUDSPRITE_NO_ERROR_MESSAGE"
78
+ _ENV_NO_ARGV = "CLOUDSPRITE_NO_ARGV"
79
+
80
+ # Session-level: warn once when endpoint is missing (older server)
81
+ _script_runs_unavailable_warned = False
82
+ # Session-level: one notice when source is not uploaded for lack of consent
83
+ _source_notice_shown = False
84
+
85
+
86
+ def _reset_session_flags() -> None:
87
+ """Test helper — clear module-level degraded-API warn latch."""
88
+ global _script_runs_unavailable_warned, _source_notice_shown
89
+ _script_runs_unavailable_warned = False
90
+ _source_notice_shown = False
91
+
92
+
93
+ def _env_truthy(name: str) -> bool:
94
+ val = os.environ.get(name)
95
+ if val is None:
96
+ return False
97
+ return val.strip().lower() in ("1", "true", "yes", "on")
98
+
99
+
100
+ def _resolve_flag(
101
+ explicit: bool | None,
102
+ *,
103
+ default: bool,
104
+ disable_env: str,
105
+ no_telemetry: bool,
106
+ ) -> bool:
107
+ """Resolve a privacy flag: explicit kwarg > env > default.
108
+
109
+ ``no_telemetry`` forces False. A channel-specific disable env forces False
110
+ when the kwarg is omitted.
111
+ """
112
+ if explicit is not None:
113
+ return bool(explicit)
114
+ if no_telemetry or _env_truthy(disable_env):
115
+ return False
116
+ return default
117
+
118
+
119
+ def resolve_git_sha(cwd: str | Path | None) -> str | None:
120
+ """Return HEAD sha with optional -dirty suffix, or None on any failure.
121
+
122
+ cwd is the script directory. 2 s timeout per git invocation. Never raises.
123
+ Does not read or transmit remote URLs or usernames.
124
+ """
125
+ if cwd is None:
126
+ return None
127
+ try:
128
+ workdir = str(Path(cwd))
129
+ head = subprocess.run(
130
+ ["git", "rev-parse", "HEAD"],
131
+ cwd=workdir,
132
+ capture_output=True,
133
+ text=True,
134
+ timeout=_GIT_TIMEOUT_S,
135
+ )
136
+ if head.returncode != 0:
137
+ return None
138
+ sha = head.stdout.strip()
139
+ if not sha:
140
+ return None
141
+ dirty = subprocess.run(
142
+ ["git", "status", "--porcelain"],
143
+ cwd=workdir,
144
+ capture_output=True,
145
+ text=True,
146
+ timeout=_GIT_TIMEOUT_S,
147
+ )
148
+ if dirty.returncode == 0 and dirty.stdout.strip():
149
+ return f"{sha}-dirty"
150
+ return sha
151
+ except Exception:
152
+ return None
153
+
154
+
155
+ def _truncate_error(text: str) -> str:
156
+ """Keep the error text within the 10 KB contract limit (prefix preserved).
157
+
158
+ Type+message strings put the exception class at the front; prefer the head
159
+ over the old traceback-tail strategy.
160
+ """
161
+ encoded = text.encode("utf-8", errors="replace")
162
+ if len(encoded) <= _ERROR_MAX_BYTES:
163
+ return text
164
+ return encoded[:_ERROR_MAX_BYTES].decode("utf-8", errors="replace")
165
+
166
+
167
+ def format_error_message(exc_type: type | None, exc: BaseException | None) -> str:
168
+ """Build a path-free error string: ``ExceptionType: message`` only.
169
+
170
+ Deliberately omits traceback frames (which contain absolute filesystem
171
+ paths and source lines). Prefer this over ``traceback.format_exception``.
172
+ """
173
+ if exc_type is None and exc is None:
174
+ return "unknown error"
175
+ if exc_type is not None:
176
+ name = getattr(exc_type, "__name__", "Exception")
177
+ elif exc is not None:
178
+ name = type(exc).__name__
179
+ else:
180
+ name = "Exception"
181
+ if exc is None:
182
+ return name
183
+ msg = str(exc)
184
+ if not msg:
185
+ return name
186
+ return _truncate_error(f"{name}: {msg}")
187
+
188
+
189
+ def _file_type_for(path: Path | None, script_name: str) -> str:
190
+ name = (path.name if path else script_name).lower()
191
+ if name.endswith(".py"):
192
+ return "py"
193
+ if name.endswith(".ipynb"):
194
+ return "ipynb"
195
+ return "other"
196
+
197
+
198
+ def _stringify_seed(seed: Any) -> str | None:
199
+ if seed is None:
200
+ return None
201
+ s = str(seed)
202
+ if len(s) > _SEED_MAX_CHARS:
203
+ s = s[:_SEED_MAX_CHARS]
204
+ return s
205
+
206
+
207
+ def _blames_work_context(body: str) -> bool:
208
+ """A 400/422 body that names the work context (api!821 messages, or a schema error on the field)."""
209
+ low = body.lower()
210
+ return "work context" in low or "work_context" in low
211
+
212
+
213
+ def _clean_purpose(purpose: Any) -> str | None:
214
+ text = str(purpose).strip() if purpose is not None else ""
215
+ return _redact.redact_string(text)[:_PURPOSE_MAX] or None
216
+
217
+
218
+ def _clean_params(params: Any) -> dict[str, Any] | None:
219
+ if not params:
220
+ return None
221
+ if not isinstance(params, dict):
222
+ warnings.warn(
223
+ f"cloudsprite: cloudscript(params=...) must be a dict, got {type(params).__name__}; not sent", stacklevel=4
224
+ )
225
+ return None
226
+ clean = _redact.redact_params(params)
227
+ if clean is None:
228
+ warnings.warn("cloudsprite: cloudscript(params=...) is over 15 KB; not sent in the run report", stacklevel=4)
229
+ return clean
230
+
231
+
232
+ class LineageTracker:
233
+ """Tracks script source, I/O datasets, and reports completed runs to the API."""
234
+
235
+ def __init__(self, owner: "Client | None" = None) -> None:
236
+ self._script_source: str | None = None
237
+ self._script_hash: str | None = None
238
+ self._script_name: str | None = None
239
+ self._script_path: Path | None = None
240
+ self._script_dir: Path | None = None
241
+ self._file_type: str = "py"
242
+ self._size: int = 0
243
+ self._accessed: list[dict[str, Any]] = []
244
+ self._output_ids: list[str] = []
245
+ self._client_run_id: str | None = None
246
+ self._seed: str | None = None
247
+ self._started_at: datetime | None = None
248
+ self._status: str = "succeeded"
249
+ self._error_message: str | None = None
250
+ self._reported: bool = False
251
+ self._hooks_installed: bool = False
252
+ self._prev_excepthook: Excepthook | None = None
253
+ self._git_sha: str | None = None
254
+ # Privacy channel flags (set in cloudscript)
255
+ # None = not decided yet; resolved on first use (consent may need a prompt).
256
+ self._upload_source: bool | None = None
257
+ self._include_git: bool = _DEFAULT_INCLUDE_GIT
258
+ self._include_error: bool = _DEFAULT_INCLUDE_ERROR
259
+ self._include_argv: bool = _DEFAULT_INCLUDE_ARGV
260
+ # Run report extras: why, with what, and for which activity
261
+ self._purpose: str | None = None
262
+ self._params: dict[str, Any] | None = None
263
+ self._argv: list[str] = []
264
+ self._work: _work_context.WorkContext | None = None
265
+ # Owning Client for atexit report — never re-enter the process default.
266
+ self._owner_ref: weakref.ReferenceType[Client] | None = weakref.ref(owner) if owner is not None else None
267
+
268
+ def _owner(self) -> "Client | None":
269
+ if self._owner_ref is None:
270
+ return None
271
+ return self._owner_ref()
272
+
273
+ @property
274
+ def is_tracking(self) -> bool:
275
+ return self._script_source is not None
276
+
277
+ @property
278
+ def script_source(self) -> str | None:
279
+ return self._script_source
280
+
281
+ @property
282
+ def upload_source(self) -> bool:
283
+ """Whether publish() should attach the script source as a DataFile.
284
+
285
+ May ask for consent once (interactive sessions only) the first time it is read.
286
+ """
287
+ if not self.is_tracking:
288
+ return False
289
+ if self._upload_source is None:
290
+ self._upload_source = self._decide_source_upload()
291
+ return self._upload_source
292
+
293
+ def _decide_source_upload(self) -> bool:
294
+ """No kwarg/env/cloud decision was made: use the stored answer, else ask, else stay off."""
295
+ global _source_notice_shown
296
+ stored = _consent.stored_answer()
297
+ if stored is not None:
298
+ return stored
299
+ if _consent.is_interactive():
300
+ answer = _consent.ask()
301
+ if answer is not None:
302
+ try:
303
+ where = _consent.store_answer(answer)
304
+ print(
305
+ f"cloudsprite: saved your choice ({'yes' if answer else 'no'}) in {where} "
306
+ f"under [privacy]. Change it there, set {_consent.ENV_UPLOAD_SOURCE}=1/0, "
307
+ "or pass upload_source= to cs.cloudscript().",
308
+ file=sys.stderr,
309
+ )
310
+ except OSError as exc:
311
+ warnings.warn(
312
+ f"cloudsprite: could not save your choice ({exc}); asking again next run", stacklevel=2
313
+ )
314
+ return answer
315
+ if not _source_notice_shown:
316
+ _source_notice_shown = True
317
+ warnings.warn(
318
+ "cloudsprite: script source is not uploaded (no consent on record). To upload it for run "
319
+ f"lineage, run once in a terminal and answer yes, set {_consent.ENV_UPLOAD_SOURCE}=1, "
320
+ "or pass upload_source=True to cs.cloudscript().",
321
+ stacklevel=2,
322
+ )
323
+ return False
324
+
325
+ @property
326
+ def include_git(self) -> bool:
327
+ return self._include_git
328
+
329
+ @property
330
+ def include_error(self) -> bool:
331
+ return self._include_error
332
+
333
+ @property
334
+ def script_hash(self) -> str | None:
335
+ return self._script_hash
336
+
337
+ @property
338
+ def script_name(self) -> str | None:
339
+ return self._script_name
340
+
341
+ @property
342
+ def client_run_id(self) -> str | None:
343
+ return self._client_run_id
344
+
345
+ @property
346
+ def seed(self) -> str | None:
347
+ return self._seed
348
+
349
+ @property
350
+ def started_at(self) -> datetime | None:
351
+ return self._started_at
352
+
353
+ @property
354
+ def status(self) -> str:
355
+ return self._status
356
+
357
+ @property
358
+ def error_message(self) -> str | None:
359
+ return self._error_message
360
+
361
+ @property
362
+ def purpose(self) -> str | None:
363
+ return self._purpose
364
+
365
+ @property
366
+ def work(self) -> "_work_context.WorkContext | None":
367
+ """Work context this run reports under (see ``build_report_payload``)."""
368
+ return self._work
369
+
370
+ @property
371
+ def accessed_datasets(self) -> list[dict[str, Any]]:
372
+ return list(self._accessed)
373
+
374
+ @property
375
+ def output_dataset_ids(self) -> list[str]:
376
+ return list(self._output_ids)
377
+
378
+ def cloudscript(
379
+ self,
380
+ file_path: str | None = None,
381
+ seed: Any = None,
382
+ *,
383
+ install_hooks: bool | None = None,
384
+ upload_source: bool | None = None,
385
+ include_git: bool | None = None,
386
+ include_error: bool | None = None,
387
+ purpose: str | None = None,
388
+ params: dict[str, Any] | None = None,
389
+ include_argv: bool | None = None,
390
+ ) -> None:
391
+ """Read and store the CloudScript source; activate run reporting for this process.
392
+
393
+ Args:
394
+ file_path: Path to the running CloudScript (typically ``__file__``). When
395
+ omitted or empty, records an ``<interactive>`` REPL/notebook run.
396
+ seed: Optional engineer-supplied seed; stringified and truncated to 64 chars.
397
+ The SDK never invents a seed.
398
+ install_hooks: Install ``sys.excepthook`` + ``atexit`` reporters.
399
+ Default is False (opt-in). Pass True to enable automatic failure
400
+ capture and exit-time run reporting.
401
+ upload_source: Attach CloudScript source on ``publish()``. Default: off until
402
+ you consent once (asked in an interactive terminal, saved in
403
+ ``~/.cloudsprite/config``); cloud runs always attach it. Env:
404
+ ``CLOUDSPRITE_UPLOAD_SOURCE=1/0``; ``CLOUDSPRITE_NO_SOURCE_UPLOAD=1``
405
+ forces off. The kwarg wins over all of them.
406
+ include_git: Include git HEAD sha in run reports. Default True.
407
+ Env: ``CLOUDSPRITE_NO_GIT_STATE=1``. Never sends remote URL.
408
+ include_error: Include exception type+message on failure. Default True.
409
+ Env: ``CLOUDSPRITE_NO_ERROR_MESSAGE=1``. Never sends traceback frames.
410
+ purpose: Why this run is being made, in a few words (truncated to 280 chars).
411
+ params: The run's parameters (a dict). Secrets are redacted before sending;
412
+ dropped with a warning when over 15 KB.
413
+ include_argv: Include ``sys.argv[1:]`` (redacted) in run reports. Default True.
414
+ Env: ``CLOUDSPRITE_NO_ARGV=1``. Environment variables are never sent.
415
+
416
+ Blanket disable: ``CLOUDSPRITE_NO_TELEMETRY=1`` turns off source upload,
417
+ git state, and error text (kwargs still win when explicitly set).
418
+ """
419
+ no_telemetry = _env_truthy(_ENV_NO_TELEMETRY)
420
+ self._upload_source = self._explicit_source_choice(upload_source, no_telemetry)
421
+ self._include_git = _resolve_flag(
422
+ include_git,
423
+ default=_DEFAULT_INCLUDE_GIT,
424
+ disable_env=_ENV_NO_GIT,
425
+ no_telemetry=no_telemetry,
426
+ )
427
+ self._include_error = _resolve_flag(
428
+ include_error,
429
+ default=_DEFAULT_INCLUDE_ERROR,
430
+ disable_env=_ENV_NO_ERROR,
431
+ no_telemetry=no_telemetry,
432
+ )
433
+ self._include_argv = _resolve_flag(
434
+ include_argv,
435
+ default=_DEFAULT_INCLUDE_ARGV,
436
+ disable_env=_ENV_NO_ARGV,
437
+ no_telemetry=no_telemetry,
438
+ )
439
+ self._purpose = _clean_purpose(purpose)
440
+ self._params = _clean_params(params)
441
+ # Interactive sessions (REPL, ipykernel's ``-f <connection file>``) have no script argv.
442
+ self._argv = _redact.redact_argv(sys.argv[1:]) if self._include_argv and file_path else []
443
+ self._work = self._active_work()
444
+ if install_hooks is None:
445
+ # Hooks are opt-in; NO_TELEMETRY does not force them on/off when
446
+ # explicit, but default remains False (no invasive process hooks).
447
+ install_hooks = _DEFAULT_INSTALL_HOOKS
448
+
449
+ if file_path:
450
+ path = Path(file_path)
451
+ try:
452
+ source = path.read_text()
453
+ size = path.stat().st_size
454
+ except OSError:
455
+ # Unreadable path → interactive-style placeholder so reporting still works
456
+ source = ""
457
+ size = 0
458
+ path = path # keep name for script_name
459
+ script_name = path.name[:_SCRIPT_NAME_MAX] or "<interactive>"
460
+ script_dir = path.resolve().parent if path.exists() else None
461
+ self._script_path = path if path.exists() else None
462
+ self._script_dir = script_dir
463
+ self._script_source = source
464
+ self._size = size
465
+ self._script_name = script_name
466
+ self._file_type = _file_type_for(path, script_name)
467
+ else:
468
+ self._script_path = None
469
+ self._script_dir = None
470
+ self._script_source = ""
471
+ self._size = 0
472
+ self._script_name = "<interactive>"
473
+ self._file_type = "other"
474
+
475
+ hash_val = hashlib.sha256(self._script_source.encode()).hexdigest()
476
+ self._script_hash = f"sha256:{hash_val}"
477
+
478
+ # New run identity on each activation
479
+ self._client_run_id = str(uuid.uuid4())
480
+ self._seed = _stringify_seed(seed)
481
+ self._started_at = datetime.now(timezone.utc)
482
+ self._status = "succeeded"
483
+ self._error_message = None
484
+ self._reported = False
485
+ self._output_ids = []
486
+ # Keep existing _accessed if re-activated mid-session? Spec: new run — clear I/O.
487
+ self._accessed = []
488
+ if self._include_git:
489
+ self._git_sha = resolve_git_sha(self._script_dir)
490
+ else:
491
+ self._git_sha = None
492
+
493
+ if install_hooks:
494
+ self._install_hooks()
495
+
496
+ # Legacy names kept as true aliases (same object).
497
+ sprite = cloudscript
498
+ track_script = cloudscript
499
+
500
+ @staticmethod
501
+ def _explicit_source_choice(explicit: bool | None, no_telemetry: bool) -> bool | None:
502
+ """kwarg > disable envs > CLOUDSPRITE_UPLOAD_SOURCE > cloud run; None means ask/stored later."""
503
+ if explicit is not None:
504
+ return bool(explicit)
505
+ if no_telemetry or _env_truthy(_ENV_NO_SOURCE):
506
+ return False
507
+ choice = _consent.env_choice()
508
+ if choice is not None:
509
+ return choice
510
+ if _work_context.under_run_token():
511
+ return True # CloudSprite's own runtime: the source already lives on our side
512
+ return None
513
+
514
+ def _active_work(self) -> "_work_context.WorkContext | None":
515
+ owner = self._owner()
516
+ if owner is not None:
517
+ return owner.current_work_context()
518
+ return None if _work_context.under_run_token() else _work_context.env_context()
519
+
520
+ def _explicit_work(self) -> "_work_context.WorkContext | None":
521
+ owner = self._owner()
522
+ return owner.explicit_work_context() if owner is not None else None
523
+
524
+ def observe_work(self, ctx: "_work_context.WorkContext") -> None:
525
+ """Remember the latest work context a request ran under (atexit reports after the block)."""
526
+ self._work = ctx
527
+
528
+ def record_access(self, dataset_id: str, dataset_name: str) -> None:
529
+ """Record a dataset access for lineage input tracking."""
530
+ if not dataset_id:
531
+ return
532
+ entry = {"dataset_id": dataset_id, "name": dataset_name}
533
+ if entry not in self._accessed:
534
+ self._accessed.append(entry)
535
+
536
+ def record_output(self, dataset_id: str) -> None:
537
+ """Record a dataset id produced by cs.publish() during this run."""
538
+ if not dataset_id:
539
+ return
540
+ if dataset_id not in self._output_ids:
541
+ self._output_ids.append(dataset_id)
542
+
543
+ def mark_failed(self, error_message: str | None) -> None:
544
+ """Mark the run as failed (excepthook / explicit report_run)."""
545
+ self._status = "failed"
546
+ if error_message and self._include_error:
547
+ self._error_message = _truncate_error(error_message)
548
+ else:
549
+ self._error_message = None
550
+
551
+ def build_metadata(self) -> dict[str, Any]:
552
+ """Build lineage metadata dict for cs.publish()."""
553
+ meta: dict[str, Any] = {
554
+ "sdk_version": _sdk_version(),
555
+ "is_computed": True,
556
+ "inputs": list(self._accessed),
557
+ "executed_at": datetime.now(timezone.utc).isoformat(),
558
+ }
559
+ if self._script_hash:
560
+ meta["script_hash"] = self._script_hash
561
+ return meta
562
+
563
+ def build_report_payload(
564
+ self,
565
+ project_id: str,
566
+ *,
567
+ status: str | None = None,
568
+ error: str | None = None,
569
+ finished_at: datetime | None = None,
570
+ ) -> dict[str, Any]:
571
+ """Build a ScriptRunReportSchema payload (field-for-field with the API schema)."""
572
+ if not self.is_tracking or not self._client_run_id or not self._started_at:
573
+ raise RuntimeError("cloudscript() must be active before building a run report")
574
+
575
+ run_status = status or self._status
576
+ if run_status not in ("succeeded", "failed"):
577
+ run_status = "failed"
578
+
579
+ err = error if error is not None else self._error_message
580
+ if run_status == "failed" and err and self._include_error:
581
+ err = _truncate_error(err)
582
+ else:
583
+ err = None
584
+
585
+ finished = finished_at or datetime.now(timezone.utc)
586
+ started = self._started_at
587
+ if finished < started:
588
+ finished = started
589
+
590
+ input_ids = [e["dataset_id"] for e in self._accessed][:_DATASET_IDS_MAX]
591
+ output_ids = list(self._output_ids)[:_DATASET_IDS_MAX]
592
+
593
+ sdk_ver = str(_sdk_version())[:_SDK_VERSION_MAX]
594
+
595
+ payload: dict[str, Any] = {
596
+ "client_run_id": self._client_run_id,
597
+ "project_id": project_id,
598
+ "script_name": (self._script_name or "<interactive>")[:_SCRIPT_NAME_MAX],
599
+ "file_type": self._file_type if self._file_type in ("py", "ipynb", "other") else "other",
600
+ "size": max(0, int(self._size)),
601
+ "content_hash": self._script_hash,
602
+ "git_sha": self._git_sha if self._include_git else None,
603
+ "sdk_version": sdk_ver,
604
+ "seed": self._seed,
605
+ "status": run_status,
606
+ "started_at": started.isoformat(),
607
+ "finished_at": finished.isoformat(),
608
+ "error_message": err,
609
+ "input_dataset_ids": input_ids,
610
+ "output_dataset_ids": output_ids,
611
+ }
612
+ if self._purpose:
613
+ payload["purpose"] = self._purpose
614
+ if self._params:
615
+ payload["params"] = self._params
616
+ if self._argv:
617
+ payload["argv"] = list(self._argv)
618
+ # Under a run token the run's own activity applies; a body would override it (it wins).
619
+ work = None if _work_context.under_run_token() else (self._explicit_work() or self._work or self._active_work())
620
+ if work is not None:
621
+ payload["work_context"] = work.body()
622
+ return payload
623
+
624
+ def report_run(
625
+ self,
626
+ client: Any,
627
+ project_id: str,
628
+ *,
629
+ status: str | None = None,
630
+ error: str | None = None,
631
+ ) -> dict[str, Any] | None:
632
+ """POST the run report once. Never raises. Returns response body or None.
633
+
634
+ Single attempt, 5 s timeout. On 404 (older server): warn once per session, no-op.
635
+ On any other failure: warnings.warn and return.
636
+ """
637
+ global _script_runs_unavailable_warned
638
+
639
+ if not self.is_tracking:
640
+ warnings.warn(
641
+ "cs.report_run() called without cloudscript()/sprite()/track_script(); ignoring", stacklevel=2
642
+ )
643
+ return None
644
+
645
+ if self._reported:
646
+ return None
647
+
648
+ try:
649
+ payload = self.build_report_payload(project_id, status=status, error=error)
650
+ except Exception as exc:
651
+ warnings.warn(f"cloudsprite: could not build run report: {exc}", stacklevel=2)
652
+ return None
653
+
654
+ if status == "failed" or (status is None and self._status == "failed"):
655
+ self._status = "failed"
656
+ if error and self._include_error:
657
+ self._error_message = _truncate_error(error)
658
+ elif not self._include_error:
659
+ self._error_message = None
660
+ elif status == "succeeded":
661
+ self._status = "succeeded"
662
+ self._error_message = None
663
+
664
+ try:
665
+ import requests as req
666
+
667
+ url = f"{client._config.base_url}{_SCRIPT_RUNS_PATH}"
668
+ headers = dict(client._auth.get_auth_header())
669
+ headers["Content-Type"] = "application/json"
670
+ # One-shot request — no retry queue in v1 (explicit contract)
671
+ resp = req.post(url, headers=headers, json=payload, timeout=_REPORT_TIMEOUT_S)
672
+
673
+ # An explicit body context is validated (400 when the activity is not available to
674
+ # the caller or belongs to another project; 422 when malformed). Lineage matters
675
+ # more than the stamp: report again without it, once, rather than lose the run.
676
+ if resp.status_code in (400, 422) and "work_context" in payload and _blames_work_context(resp.text):
677
+ warnings.warn(
678
+ "cloudsprite: the API rejected the work context; reporting the run without it",
679
+ stacklevel=2,
680
+ )
681
+ payload = {k: v for k, v in payload.items() if k != "work_context"}
682
+ resp = req.post(url, headers=headers, json=payload, timeout=_REPORT_TIMEOUT_S)
683
+
684
+ if resp.status_code == 404:
685
+ if not _script_runs_unavailable_warned:
686
+ warnings.warn(
687
+ "cloudsprite: POST /api/script-runs/ not available on this server; "
688
+ "run reporting disabled for this session",
689
+ stacklevel=2,
690
+ )
691
+ _script_runs_unavailable_warned = True
692
+ self._reported = True # don't hammer atexit
693
+ return None
694
+
695
+ if resp.status_code >= 400:
696
+ try:
697
+ body = resp.json()
698
+ except ValueError:
699
+ body = {"detail": resp.text}
700
+ detail = body.get("detail", resp.text)
701
+ warnings.warn(
702
+ f"cloudsprite: run report failed ({resp.status_code}): {detail}",
703
+ stacklevel=2,
704
+ )
705
+ return None
706
+
707
+ self._reported = True
708
+ if resp.status_code == 204 or not resp.content:
709
+ return {}
710
+ try:
711
+ body = resp.json()
712
+ return body if isinstance(body, dict) else {}
713
+ except ValueError:
714
+ return {}
715
+ except Exception as exc:
716
+ # Catch network errors, timeouts, import issues — never break the user script
717
+ warnings.warn(f"cloudsprite: run report failed: {exc}", stacklevel=2)
718
+ return None
719
+
720
+ def _install_hooks(self) -> None:
721
+ if self._hooks_installed:
722
+ return
723
+ self._prev_excepthook = sys.excepthook
724
+ sys.excepthook = self._excepthook
725
+ atexit.register(self._atexit_report)
726
+ self._hooks_installed = True
727
+
728
+ def _excepthook(
729
+ self,
730
+ exc_type: type[BaseException],
731
+ exc: BaseException,
732
+ tb: TracebackType | None,
733
+ ) -> None:
734
+ try:
735
+ # Type + message only — never format_exception (paths + source lines)
736
+ self.mark_failed(format_error_message(exc_type, exc))
737
+ except Exception:
738
+ self.mark_failed(str(exc) if exc else "unknown error")
739
+ prev = self._prev_excepthook or sys.__excepthook__
740
+ prev(exc_type, exc, tb)
741
+
742
+ def _atexit_report(self) -> None:
743
+ """Best-effort report on process exit. Never raises."""
744
+ if self._reported or not self.is_tracking:
745
+ return
746
+ try:
747
+ owner = self._owner()
748
+ if owner is None:
749
+ # Owner was garbage-collected, i.e. the caller dropped their
750
+ # reference. Not worth a warning at interpreter exit — they are
751
+ # not waiting on the report. The warning below is for the case
752
+ # where a live client is closed or disconnected.
753
+ logger.debug("owning Client collected before exit; run report skipped")
754
+ return
755
+ if not owner.is_connected:
756
+ warnings.warn(
757
+ "cloudsprite: owning Client is closed or disconnected; run report skipped",
758
+ stacklevel=1,
759
+ )
760
+ return
761
+ project_slug = owner.project_slug
762
+ if not project_slug:
763
+ warnings.warn(
764
+ "cloudsprite: cloudscript() active but no project set; skipping run report",
765
+ stacklevel=1,
766
+ )
767
+ return
768
+ try:
769
+ project_id = owner.resolve_project_id(project_slug)
770
+ except Exception as exc:
771
+ warnings.warn(f"cloudsprite: could not resolve project for run report: {exc}", stacklevel=1)
772
+ return
773
+ self.report_run(owner.client, project_id)
774
+ except Exception as exc:
775
+ warnings.warn(f"cloudsprite: atexit run report failed: {exc}", stacklevel=1)