code-loader 1.0.218.dev1__tar.gz → 1.0.219.dev1__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. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/PKG-INFO +1 -1
  2. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/contract/datasetclasses.py +4 -1
  3. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/contract/responsedataclasses.py +0 -1
  4. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/inner_leap_binder/fp_confidence_contract.py +6 -11
  5. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/inner_leap_binder/leapbinder.py +7 -7
  6. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/inner_leap_binder/leapbinder_decorators.py +71 -23
  7. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/leaploader.py +1 -2
  8. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/mixpanel_tracker.py +81 -1
  9. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/pyproject.toml +1 -1
  10. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/LICENSE +0 -0
  11. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/README.md +0 -0
  12. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/__init__.py +0 -0
  13. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/contract/__init__.py +0 -0
  14. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/contract/enums.py +0 -0
  15. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/contract/exceptions.py +0 -0
  16. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/contract/mapping.py +0 -0
  17. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/contract/sim_config.py +0 -0
  18. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/contract/visualizer_classes.py +0 -0
  19. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/default_losses.py +0 -0
  20. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/default_metrics.py +0 -0
  21. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/experiment_api/__init__.py +0 -0
  22. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/experiment_api/api.py +0 -0
  23. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/experiment_api/cli_config_utils.py +0 -0
  24. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/experiment_api/client.py +0 -0
  25. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/experiment_api/epoch.py +0 -0
  26. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/experiment_api/experiment.py +0 -0
  27. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/experiment_api/experiment_context.py +0 -0
  28. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/experiment_api/types.py +0 -0
  29. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/experiment_api/utils.py +0 -0
  30. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/experiment_api/workingspace_config_utils.py +0 -0
  31. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/inner_leap_binder/__init__.py +0 -0
  32. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/leaploaderbase.py +0 -0
  33. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/plot_functions/__init__.py +0 -0
  34. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/plot_functions/plot_functions.py +0 -0
  35. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/plot_functions/visualize.py +0 -0
  36. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/utils.py +0 -0
  37. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/visualizers/__init__.py +0 -0
  38. {code_loader-1.0.218.dev1 → code_loader-1.0.219.dev1}/code_loader/visualizers/default_visualizers.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: code-loader
3
- Version: 1.0.218.dev1
3
+ Version: 1.0.219.dev1
4
4
  Summary:
5
5
  Home-page: https://github.com/tensorleap/code-loader
6
6
  License: MIT
@@ -179,7 +179,11 @@ class ElementInstance:
179
179
  # Per-instance metric values keyed by the registered name of a tensorleap_custom_instances_metric.
180
180
  # Only meaningful on false-positive instances (they have no ground-truth row for the metric to run on).
181
181
  instance_metrics: Optional[Dict[str, float]] = None
182
+ # Confidence mode (the FP encoder declares operating_threshold): the candidate's score, required on every
183
+ # candidate. Ignored (may stay None) when no threshold is declared.
182
184
  score: Optional[float] = None
185
+ # Confidence mode, training / validation / test only: whether this candidate matches a ground-truth instance,
186
+ # by the integration's own rule (IoU threshold, class). Ignored on unlabeled / additional.
183
187
  matched_gt: Optional[bool] = None
184
188
 
185
189
  SectionCallableInterface = Callable[[Union[int, str], PreprocessResponse], npt.NDArray[np.float32]]
@@ -339,7 +343,6 @@ class FalsePositiveInstancesHandler:
339
343
  function: Callable[..., Any]
340
344
  operating_threshold: Optional[float] = None
341
345
  candidate_floor: Optional[float] = None
342
- max_candidates_per_image: int = 30
343
346
 
344
347
  @dataclass
345
348
  class GroundTruthHandler(DatasetBaseHandler):
@@ -175,7 +175,6 @@ class LeapAnalysisConfiguration:
175
175
  class FalsePositiveConfidenceConfig:
176
176
  operating_threshold: float
177
177
  candidate_floor: float
178
- max_candidates_per_image: int
179
178
 
180
179
 
181
180
  @dataclass
@@ -18,11 +18,10 @@ def _is_finite_number(value: object) -> bool:
18
18
  return math.isfinite(float(value))
19
19
 
20
20
 
21
- def validate_confidence_args(operating_threshold: Optional[float], candidate_floor: Optional[float],
22
- max_candidates_per_image: int) -> None:
21
+ def validate_confidence_args(operating_threshold: Optional[float], candidate_floor: Optional[float]) -> None:
23
22
  if operating_threshold is None:
24
- if candidate_floor is not None or max_candidates_per_image != 30:
25
- raise ValueError(_PREFIX + "candidate_floor and max_candidates_per_image require operating_threshold.")
23
+ if candidate_floor is not None:
24
+ raise ValueError(_PREFIX + "candidate_floor requires operating_threshold.")
26
25
  return
27
26
  if not _is_finite_number(operating_threshold):
28
27
  raise ValueError(_PREFIX + f"operating_threshold should be a finite float. Got {operating_threshold!r}.")
@@ -31,10 +30,6 @@ def validate_confidence_args(operating_threshold: Optional[float], candidate_flo
31
30
  if not _is_finite_number(candidate_floor) or candidate_floor >= operating_threshold:
32
31
  raise ValueError(_PREFIX + f"candidate_floor should be a finite float below operating_threshold "
33
32
  f"({operating_threshold}). Got {candidate_floor!r}.")
34
- if not isinstance(max_candidates_per_image, (int, np.integer)) or isinstance(max_candidates_per_image, bool) \
35
- or max_candidates_per_image < 1:
36
- raise ValueError(_PREFIX + f"max_candidates_per_image should be an int >= 1. "
37
- f"Got {max_candidates_per_image!r}.")
38
33
 
39
34
 
40
35
  def declare_confidence_metadata_types(setup_container: DatasetIntegrationSetup) -> None:
@@ -69,7 +64,7 @@ def validate_confidence_contract(instances: List[ElementInstance], state: Option
69
64
  for j, instance in enumerate(instances):
70
65
  if instance.score is None or not _is_finite_number(instance.score):
71
66
  raise Exception(f"{_PREFIX}operating_threshold is declared, so element {j} of the returned list "
72
- f"should have a finite float score. Got {instance.score!r}.")
67
+ f"should have a finite float score (call .item() on a tensor). Got {instance.score!r}.")
73
68
  scores.append(float(instance.score))
74
69
  if handler.candidate_floor is not None and \
75
70
  not np.float32(instance.score) >= np.float32(handler.candidate_floor):
@@ -80,8 +75,8 @@ def validate_confidence_contract(instances: List[ElementInstance], state: Option
80
75
  for j, instance in enumerate(instances):
81
76
  if not isinstance(instance.matched_gt, (bool, np.bool_)):
82
77
  raise Exception(f"{_PREFIX}matched_gt of element {j} should be a bool on the {state.value} state "
83
- f"(True when the candidate matches a ground-truth instance). "
84
- f"Got {instance.matched_gt!r}.")
78
+ f"(True when the candidate matches a ground-truth instance by the integration's "
79
+ f"own IoU / class rule). Got {instance.matched_gt!r}.")
85
80
  is_row = not instance.matched_gt and \
86
81
  np.float32(scores[j]) >= np.float32(handler.operating_threshold)
87
82
  if instance.mask is None and is_row:
@@ -345,21 +345,22 @@ class LeapBinder:
345
345
 
346
346
  def set_false_positive_instances(self, function: Callable[..., Any], name: str,
347
347
  operating_threshold: Optional[float] = None,
348
- candidate_floor: Optional[float] = None,
349
- max_candidates_per_image: int = 30) -> None:
348
+ candidate_floor: Optional[float] = None) -> None:
350
349
  """
351
350
  Set the false-positive instances handler. It receives (sample_id, preprocess, predictions)
352
- and returns a list of ElementInstance, one per false-positive prediction.
351
+ and returns a list of ElementInstance: one per false-positive prediction, or, when
352
+ `operating_threshold` is declared, one per candidate down to `candidate_floor` (matched ones
353
+ included), each with a score. The full contract is in the docstring of
354
+ `tensorleap_false_positive_instances_encoder`.
353
355
  """
354
356
  if self.setup_container.false_positive_instances is not None:
355
357
  raise Exception("only one tensorleap_false_positive_instances_encoder can be defined")
356
- validate_confidence_args(operating_threshold, candidate_floor, max_candidates_per_image)
358
+ validate_confidence_args(operating_threshold, candidate_floor)
357
359
  function = to_numpy_return_fp_masks_wrapper(function)
358
360
  self.setup_container.false_positive_instances = FalsePositiveInstancesHandler(
359
361
  name, function,
360
362
  float(operating_threshold) if operating_threshold is not None else None,
361
- float(candidate_floor) if candidate_floor is not None else None,
362
- int(max_candidates_per_image))
363
+ float(candidate_floor) if candidate_floor is not None else None)
363
364
  declare_confidence_metadata_types(self.setup_container)
364
365
 
365
366
  def set_false_positive_empty_gt(self, function: Callable[..., Any], gt_name: str) -> None:
@@ -1145,7 +1146,6 @@ class LeapBinder:
1145
1146
  self.check_simulations()
1146
1147
  self.validate_ignore_latent_spaces()
1147
1148
  self.validate_use_additional_set_as_unlabeled_candidate()
1148
- print("Successful!")
1149
1149
 
1150
1150
  def validate_autoregressive_setup(self) -> None:
1151
1151
  """Structural rules for autoregressive integrations (no-op when the hook is absent).
@@ -52,6 +52,12 @@ _integration_test_started = False
52
52
  _mapping_dataset_is_grouped = False
53
53
  _call_from_tl_platform = os.environ.get('IS_TENSORLEAP_PLATFORM') == 'true'
54
54
 
55
+ # Verdicts of the local status table, and the exit status of a run that was clean but left a
56
+ # mandatory part out of the integration test (0 = ready to push, 1 = crash, as Python reports it).
57
+ INTEGRATION_READY = "ready"
58
+ INTEGRATION_INCOMPLETE = "incomplete"
59
+ EXIT_CODE_INTEGRATION_INCOMPLETE = 3
60
+
55
61
  # ---- warnings store (module-level) ----
56
62
  _UNSET = object()
57
63
  _STORED_WARNINGS: List[Dict[str, Any]] = []
@@ -3511,16 +3517,47 @@ def tensorleap_instances_masks_encoder(name: str):
3511
3517
 
3512
3518
  def tensorleap_false_positive_instances_encoder(
3513
3519
  name: str, instance_metadata_types: Optional[Dict[str, DatasetMetadataType]] = None,
3514
- operating_threshold: Optional[float] = None, candidate_floor: Optional[float] = None,
3515
- max_candidates_per_image: int = 30):
3520
+ operating_threshold: Optional[float] = None, candidate_floor: Optional[float] = None):
3516
3521
  """Register the false-positive instances encoder.
3517
3522
 
3523
+ The decorated function receives (sample_id, preprocess_response, predictions) and returns a list of
3524
+ ElementInstance.
3525
+
3518
3526
  `instance_metadata_types` declares the keys (and types) of the `instance_metadata` the returned
3519
3527
  ElementInstances may carry. They become `builtin_instance_extra_metadata_<key>` columns, merged
3520
3528
  with any keys the element-instance preprocess declares; a key not declared here (or by the
3521
3529
  GT instances) is dropped from false-positive rows by the engine.
3530
+
3531
+ Without `operating_threshold`, return one ElementInstance per false-positive prediction (a prediction
3532
+ that matches no ground-truth instance), as the model is used.
3533
+
3534
+ Confidence mode: declaring `operating_threshold` lets Tensorleap add likely missed objects (predictions
3535
+ just below the threshold) to the unlabeled pool as labeling candidates.
3536
+
3537
+ - `operating_threshold`: the score the model is used at.
3538
+ - `candidate_floor`: required with `operating_threshold`, and strictly below it: the lowest score worth
3539
+ considering.
3540
+ - Return every candidate with score >= `candidate_floor`, on every state (training, validation and test
3541
+ included), matched ones too: not only the false positives, and not only those above the threshold.
3542
+ - Apply the floor after the model's usual post-processing (NMS, top-k / max_det caps): the candidates at
3543
+ or above `operating_threshold` must be exactly what the model produces at `operating_threshold`, and
3544
+ the ones below it are added to them. Lowering the confidence filter in front of NMS changes the
3545
+ candidates above the threshold unless the post-processing is plain greedy NMS without caps.
3546
+ - Each ElementInstance needs a finite `score`. On training, validation and test it also needs a bool
3547
+ `matched_gt`: whether it matches a ground-truth instance, by the integration's own rule (IoU threshold,
3548
+ class).
3549
+ - `mask` may be None only for a calibration-only candidate on training, validation or test (matched, or
3550
+ below `operating_threshold`). Every other candidate, and every candidate on unlabeled and additional,
3551
+ needs a mask.
3552
+ - Any order: Tensorleap sorts by score.
3553
+
3554
+ What Tensorleap does with them: on training, validation and test the unmatched candidates at or above
3555
+ `operating_threshold` become false-positive rows (as without confidence mode), and every candidate's
3556
+ (score, matched_gt) calibrates how far below the threshold to look. On unlabeled and additional the
3557
+ candidates at or above the threshold become rows, and so do the ones below it down to a cut chosen from
3558
+ that calibration.
3522
3559
  """
3523
- validate_confidence_args(operating_threshold, candidate_floor, max_candidates_per_image)
3560
+ validate_confidence_args(operating_threshold, candidate_floor)
3524
3561
 
3525
3562
  def decorating_function(user_function: Callable):
3526
3563
  def _validate_input_args(sample_id, preprocess_response, predictions):
@@ -3554,8 +3591,7 @@ def tensorleap_false_positive_instances_encoder(
3554
3591
 
3555
3592
  return result
3556
3593
 
3557
- leap_binder.set_false_positive_instances(inner_without_validate, name, operating_threshold, candidate_floor,
3558
- max_candidates_per_image)
3594
+ leap_binder.set_false_positive_instances(inner_without_validate, name, operating_threshold, candidate_floor)
3559
3595
  _register_builtin_instance_metadata()
3560
3596
  if instance_metadata_types:
3561
3597
  _register_builtin_instance_extra_metadata(instance_metadata_types)
@@ -4203,9 +4239,6 @@ def tensorleap_status_table():
4203
4239
  # printed, gate readiness, or be recommended as a next step.
4204
4240
  table[:] = [row for row in table if row["name"] != "tensorleap_input_encoder"]
4205
4241
 
4206
- ready_mess = "\nAll parts have been successfully set. If no errors accured, you can now push the project to the Tensorleap system."
4207
- not_ready_mess = "\nSome mandatory components have not yet been added to the Integration test. Recommended next interface to add is: "
4208
- mandatory_ready_mess = "\nAll mandatory parts have been successfully set. If no errors accured, you can now push the project to the Tensorleap system or continue to the next optional reccomeded interface,adding: "
4209
4242
  code_mapping_failure_mes = "Tensorleap_integration_test code flow failed, check raised exception."
4210
4243
 
4211
4244
  name_width = max(len(row["name"]) for row in table)
@@ -4220,18 +4253,9 @@ def tensorleap_status_table():
4220
4253
  for row in table:
4221
4254
  print(f"{row['name'].ljust(name_width)} | {row['Added to integration'].ljust(status_width)}")
4222
4255
 
4223
- # Determine next_step based on original table order (recommended integration order)
4224
- ready = True
4225
- next_step = None
4226
- for row in table:
4227
- if not _crashed["value"] and ready:
4228
- if row["Added to integration"] != CHECK:
4229
- ready = False
4230
- next_step = row["name"]
4231
-
4232
4256
  if code_mapping_failure[0]:
4233
4257
  print(f"\n{CROSS} {code_mapping_failure_mes}")
4234
- return
4258
+ return None
4235
4259
 
4236
4260
  if _crashed["value"]:
4237
4261
  crashed_at = _current_func['name']
@@ -4239,11 +4263,24 @@ def tensorleap_status_table():
4239
4263
  print(f"\nScript crashed before completing all steps. crashed at function '{crashed_at}'.")
4240
4264
  else:
4241
4265
  print("\nScript crashed before completing all steps.")
4242
- return
4266
+ return None
4243
4267
 
4244
- print(ready_mess) if ready else print(
4245
- mandatory_ready_mess + next_step
4246
- ) if (next_step and "optional" in next_step) else print(not_ready_mess + (next_step or ""))
4268
+ # The next step follows the table order (the recommended integration order), but every
4269
+ # mandatory row comes before any optional one: rows appended at registration time (e.g. the
4270
+ # autoregressive step) sit after the optional rows and must still gate readiness.
4271
+ missing = [row["name"] for row in table if row["Added to integration"] != CHECK]
4272
+ missing_mandatory = [name for name in missing if "optional" not in name]
4273
+ if missing_mandatory:
4274
+ next_step = missing_mandatory[0]
4275
+ what = "has not run yet" if next_step == "tensorleap_integration_test" \
4276
+ else "is not used in the integration test yet"
4277
+ print(f"\nThis integration is not ready to push: `{next_step}` {what}. Add it next.")
4278
+ return INTEGRATION_INCOMPLETE
4279
+
4280
+ print("\nReady to push: all mandatory parts are in the integration test.")
4281
+ if missing:
4282
+ print(f"Optional next: `{_remove_suffix(missing[0], ' (optional)')}`.")
4283
+ return INTEGRATION_READY
4247
4284
 
4248
4285
  def set_current(name: str):
4249
4286
  _current_func["name"] = name
@@ -4304,7 +4341,18 @@ def tensorleap_status_table():
4304
4341
  _mark_unknowns_as_cross()
4305
4342
  _resolve_sim_row()
4306
4343
 
4307
- _print_table()
4344
+ verdict = _print_table()
4345
+ if verdict == INTEGRATION_INCOMPLETE and not _crashed["value"]:
4346
+ # A clean run that leaves a mandatory row unexercised must not exit 0: helpers and
4347
+ # scripts read exit 0 as "ready to push". An atexit handler cannot change the exit
4348
+ # status with sys.exit (Python ignores SystemExit there), so flush and leave directly.
4349
+ # Exit handlers registered before code-loader was imported are skipped; logging, the
4350
+ # one that matters, is shut down explicitly.
4351
+ import logging
4352
+ sys.stdout.flush()
4353
+ sys.stderr.flush()
4354
+ logging.shutdown()
4355
+ os._exit(EXIT_CODE_INTEGRATION_INCOMPLETE)
4308
4356
 
4309
4357
  def handle_exception(exc_type, exc_value, exc_traceback):
4310
4358
  _crashed["value"] = True
@@ -477,8 +477,7 @@ class LeapLoader(LeapLoaderBase):
477
477
  handler = global_leap_binder.setup_container.false_positive_instances
478
478
  if handler is None or handler.operating_threshold is None or handler.candidate_floor is None:
479
479
  return None
480
- return FalsePositiveConfidenceConfig(handler.operating_threshold, handler.candidate_floor,
481
- handler.max_candidates_per_image)
480
+ return FalsePositiveConfidenceConfig(handler.operating_threshold, handler.candidate_floor)
482
481
 
483
482
  def _check_integration_test_exists(self) -> DatasetTestResultPayload:
484
483
  test_result = DatasetTestResultPayload('integration_test')
@@ -7,8 +7,10 @@ import getpass
7
7
  import uuid
8
8
  import logging
9
9
  from enum import Enum
10
+ from pathlib import Path
10
11
  from typing import Optional, Dict, Any, Set, Union, TypedDict
11
12
  import mixpanel # type: ignore[import]
13
+ import requests
12
14
 
13
15
  logger = logging.getLogger(__name__)
14
16
 
@@ -17,6 +19,17 @@ TL_DISABLE_ANALYTICS_ENV_VAR = 'TL_DISABLE_ANALYTICS'
17
19
  # Every code-loader event is sent under this one name; `event_type` says which one it is.
18
20
  CODE_LOADER_EVENT_NAME = 'code_loader_event'
19
21
 
22
+ # Events that could not be sent (no network, e.g. inside an AI assistant's sandbox) are appended to
23
+ # <dir containing leap.yaml>/.tensorleap/pending_events.jsonl; leap-cli sends them on the next `leap push`.
24
+ # Each line is exactly the JSON message the Mixpanel consumer would have POSTed to /track.
25
+ PENDING_EVENTS_DIR_NAME = '.tensorleap'
26
+ PENDING_EVENTS_FILE_NAME = 'pending_events.jsonl'
27
+ MAX_PENDING_EVENTS = 1000
28
+ MAX_PENDING_EVENTS_BYTES = 1024 * 1024
29
+ # Set after the first send that fails for lack of network: later events in this process are buffered
30
+ # without trying, since each failed try costs a few seconds of retries.
31
+ _mixpanel_unreachable = False
32
+
20
33
 
21
34
  class AnalyticsEvent(str, Enum):
22
35
  """Enumeration of all tracked analytics events, sent as the `event_type` of a code_loader_event."""
@@ -56,12 +69,79 @@ class GtEncoderEventProps(TypedDict, total=False):
56
69
  encoder_name: str
57
70
 
58
71
 
72
+ def _find_project_dir() -> Optional[Path]:
73
+ """The directory holding leap.yaml: searched up from the working directory, then from the entry script."""
74
+ import __main__
75
+ start_dirs = [Path.cwd()]
76
+ main_file = getattr(__main__, '__file__', None)
77
+ if main_file:
78
+ start_dirs.append(Path(main_file).resolve().parent)
79
+ for start_dir in start_dirs:
80
+ for candidate in [start_dir, *start_dir.parents]:
81
+ if (candidate / 'leap.yaml').is_file():
82
+ return candidate
83
+ return None
84
+
85
+
86
+ def _append_pending_event(json_message: str) -> None:
87
+ """Append an unsent Mixpanel message to the project's pending-events file. Never raises."""
88
+ try:
89
+ project_dir = _find_project_dir()
90
+ if project_dir is None:
91
+ return
92
+ events_dir = project_dir / PENDING_EVENTS_DIR_NAME
93
+ events_dir.mkdir(exist_ok=True)
94
+ gitignore_path = events_dir / '.gitignore'
95
+ if not gitignore_path.exists():
96
+ gitignore_path.write_text('*\n')
97
+
98
+ line = (json_message + '\n').encode('utf-8')
99
+ events_path = events_dir / PENDING_EVENTS_FILE_NAME
100
+ if events_path.exists():
101
+ if events_path.stat().st_size + len(line) > MAX_PENDING_EVENTS_BYTES:
102
+ return
103
+ with open(events_path, 'rb') as f:
104
+ if sum(1 for _ in f) >= MAX_PENDING_EVENTS:
105
+ return
106
+ # One O_APPEND write per line, so a line is never interleaved with another writer's.
107
+ fd = os.open(events_path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o644)
108
+ try:
109
+ os.write(fd, line)
110
+ finally:
111
+ os.close(fd)
112
+ except Exception as e:
113
+ logger.debug(f"Failed to buffer unsent analytics event: {e}")
114
+
115
+
116
+ class _BufferingConsumer:
117
+ """A Mixpanel consumer that buffers an event to disk when it can't reach Mixpanel."""
118
+
119
+ def __init__(self) -> None:
120
+ self._consumer = mixpanel.Consumer()
121
+
122
+ def send(self, endpoint: str, json_message: str, api_key: Optional[str] = None,
123
+ api_secret: Optional[str] = None) -> None:
124
+ global _mixpanel_unreachable
125
+ if endpoint == 'events' and _mixpanel_unreachable:
126
+ _append_pending_event(json_message)
127
+ return
128
+ try:
129
+ self._consumer.send(endpoint, json_message, api_key, api_secret)
130
+ except mixpanel.MixpanelException as e:
131
+ # Network failures arrive as a MixpanelException raised from a requests exception;
132
+ # an event Mixpanel received and rejected has no such cause and is not retried.
133
+ if endpoint == 'events' and isinstance(e.__cause__, requests.exceptions.RequestException):
134
+ _mixpanel_unreachable = True
135
+ _append_pending_event(json_message)
136
+ raise
137
+
138
+
59
139
  class MixpanelTracker:
60
140
  """Handles Mixpanel event tracking for code-loader."""
61
141
 
62
142
  def __init__(self, token: str = "0c1710c9656bbfb1056bb46093e23ca1"):
63
143
  self.token = token
64
- self.mp = mixpanel.Mixpanel(token)
144
+ self.mp = mixpanel.Mixpanel(token, consumer=_BufferingConsumer())
65
145
  self._user_id: Optional[str] = None
66
146
 
67
147
  def _get_whoami(self) -> str:
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "code-loader"
3
- version = "1.0.218.dev1"
3
+ version = "1.0.219.dev1"
4
4
  description = ""
5
5
  authors = ["dorhar <doron.harnoy@tensorleap.ai>"]
6
6
  license = "MIT"