albert-memory 0.4.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 (74) hide show
  1. albert/__init__.py +3 -0
  2. albert/admin.py +532 -0
  3. albert/api.py +698 -0
  4. albert/automatic_memory_release.json +14 -0
  5. albert/benchmark.py +272 -0
  6. albert/benchmark_cli.py +37 -0
  7. albert/capture.py +1051 -0
  8. albert/capture_installer.py +1000 -0
  9. albert/capture_promotion.py +298 -0
  10. albert/capture_retention.py +72 -0
  11. albert/capture_sdk.py +558 -0
  12. albert/capture_security.py +79 -0
  13. albert/chunking.py +79 -0
  14. albert/classifier.py +263 -0
  15. albert/claude_adapter.py +357 -0
  16. albert/claude_lifecycle.py +418 -0
  17. albert/claude_package.json +19 -0
  18. albert/claude_plugin/.claude-plugin/plugin.json +11 -0
  19. albert/claude_plugin/.mcp.json +13 -0
  20. albert/claude_plugin/hooks/hooks.json +70 -0
  21. albert/clusters.py +140 -0
  22. albert/codex_adapter.py +308 -0
  23. albert/codex_hooks/hooks.json +49 -0
  24. albert/codex_lifecycle.py +485 -0
  25. albert/codex_package.json +19 -0
  26. albert/compatibility.py +121 -0
  27. albert/config.py +144 -0
  28. albert/console.py +508 -0
  29. albert/console_backends.py +236 -0
  30. albert/console_map.py +518 -0
  31. albert/console_ops.py +919 -0
  32. albert/credentials.py +616 -0
  33. albert/cursor_adapter.py +320 -0
  34. albert/cursor_hooks/hooks.json +11 -0
  35. albert/cursor_rules/albert-memory.mdc +11 -0
  36. albert/db.py +68 -0
  37. albert/embeddings.py +91 -0
  38. albert/graph.py +623 -0
  39. albert/graph_builders.py +879 -0
  40. albert/graph_cypher.py +669 -0
  41. albert/graph_store.py +376 -0
  42. albert/host_targets/claude-code.json +45 -0
  43. albert/host_targets/codex.json +45 -0
  44. albert/host_targets/openclaw.json +45 -0
  45. albert/host_targets.py +271 -0
  46. albert/links.py +428 -0
  47. albert/mcp_server.py +457 -0
  48. albert/memory_safety.py +111 -0
  49. albert/models.py +611 -0
  50. albert/openclaw_adapter.py +326 -0
  51. albert/openclaw_adapter_trust.json +5 -0
  52. albert/openclaw_package.json +22 -0
  53. albert/openclaw_plugin/index.js +135 -0
  54. albert/openclaw_plugin/openclaw.plugin.json +25 -0
  55. albert/openclaw_plugin/package.json +12 -0
  56. albert/portability.py +291 -0
  57. albert/provenance.py +105 -0
  58. albert/recorder.py +166 -0
  59. albert/release_gate.py +83 -0
  60. albert/schemas.py +617 -0
  61. albert/scope.py +26 -0
  62. albert/search.py +447 -0
  63. albert/security.py +150 -0
  64. albert/services.py +1316 -0
  65. albert/session_context.py +162 -0
  66. albert/trace_feed.py +165 -0
  67. albert/trace_writer.py +131 -0
  68. albert/tracing.py +75 -0
  69. albert/worker.py +202 -0
  70. albert/workspaces.py +256 -0
  71. albert_memory-0.4.0.dist-info/METADATA +554 -0
  72. albert_memory-0.4.0.dist-info/RECORD +74 -0
  73. albert_memory-0.4.0.dist-info/WHEEL +4 -0
  74. albert_memory-0.4.0.dist-info/entry_points.txt +14 -0
@@ -0,0 +1,162 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from datetime import UTC, datetime
5
+ from typing import Any
6
+
7
+ from albert.schemas import SearchHit, SearchResponse, SessionContextRequest, SessionContextResponse
8
+
9
+ _TOKEN = re.compile(r"\w+|[^\w\s]", re.UNICODE)
10
+
11
+
12
+ def count_tokens(value: str) -> int:
13
+ """Deterministic API budget unit; words and punctuation each count once."""
14
+ return len(_TOKEN.findall(value))
15
+
16
+
17
+ def _branch(hit: SearchHit) -> str | None:
18
+ provenance = hit.metadata.get("provenance", {})
19
+ if not isinstance(provenance, dict):
20
+ return None
21
+ value = provenance.get("branch") or provenance.get("ref")
22
+ return str(value) if value else None
23
+
24
+
25
+ def _timestamp(value: Any) -> float:
26
+ try:
27
+ return datetime.fromisoformat(str(value)).timestamp()
28
+ except (TypeError, ValueError):
29
+ return 0.0
30
+
31
+
32
+ # Recall orders by relevance: the fused search score, nudged by bounded
33
+ # adjustments. Trust, confidence and recency used to be strict sort keys ahead
34
+ # of the score, so recall returned the newest candidates rather than the most
35
+ # relevant ones; as multipliers they can reorder near-ties but never bury a
36
+ # clearly better match. Scope matches (task, branch, project) remain tiers.
37
+ _TRUST_FACTOR = {"trusted": 1.10, "verified": 1.0, "untrusted": 0.90}
38
+ CONFIDENCE_WEIGHT = 0.10 # confidence 0 costs 10%, confidence 1 costs nothing
39
+ RECENCY_BOOST = 0.10 # a memory valid from today gains up to 10% ...
40
+ RECENCY_WINDOW_DAYS = 365.0 # ... fading linearly to nothing over a year
41
+ DIVERSITY_WINDOW = 3 # memory types are diversified among the top few only
42
+
43
+
44
+ def _scope_tier(hit: SearchHit, request: SessionContextRequest) -> tuple[int, int, int]:
45
+ metadata = hit.metadata
46
+ return (
47
+ int(bool(request.task_ref) and metadata.get("task_ref") == request.task_ref),
48
+ int(bool(request.branch_ref) and _branch(hit) == request.branch_ref),
49
+ int(bool(request.project_ref) and metadata.get("project_ref") == request.project_ref),
50
+ )
51
+
52
+
53
+ def _relevance(hit: SearchHit, now: float) -> float:
54
+ metadata = hit.metadata
55
+ trust = _TRUST_FACTOR.get(str(metadata.get("capture_source_trust", "verified")), 1.0)
56
+ confidence = min(max(float(metadata.get("confidence", 1.0)), 0.0), 1.0)
57
+ confidence_factor = 1.0 - CONFIDENCE_WEIGHT * (1.0 - confidence)
58
+ valid_from = _timestamp(metadata.get("valid_from"))
59
+ recency = 1.0
60
+ if valid_from:
61
+ age_days = max(0.0, (now - valid_from) / 86400)
62
+ recency += RECENCY_BOOST * max(0.0, 1.0 - age_days / RECENCY_WINDOW_DAYS)
63
+ return float(hit.score) * trust * confidence_factor * recency
64
+
65
+
66
+ def _rank_key(hit: SearchHit, request: SessionContextRequest, now: float) -> tuple[Any, ...]:
67
+ return (
68
+ *_scope_tier(hit, request),
69
+ _relevance(hit, now),
70
+ str(hit.memory_id or hit.metadata.get("relationship_id", "")),
71
+ )
72
+
73
+
74
+ def _eligible(hit: SearchHit, request: SessionContextRequest) -> bool:
75
+ if hit.metadata.get("quarantined"):
76
+ return False
77
+ trust = str(hit.metadata.get("capture_source_trust", "verified"))
78
+ return request.trust_policy != "exclude_untrusted" or trust != "untrusted"
79
+
80
+
81
+ def _ordered(hits: list[SearchHit], request: SessionContextRequest) -> list[SearchHit]:
82
+ now = datetime.now(UTC).timestamp()
83
+ remaining = sorted(
84
+ (hit for hit in hits if _eligible(hit, request)),
85
+ key=lambda hit: _rank_key(hit, request, now),
86
+ reverse=True,
87
+ )
88
+ ordered: list[SearchHit] = []
89
+ seen_types: set[str] = set()
90
+ while remaining:
91
+ best_tier = _scope_tier(remaining[0], request)
92
+ window = [hit for hit in remaining if _scope_tier(hit, request) == best_tier]
93
+ window = window[:DIVERSITY_WINDOW]
94
+ diverse = next(
95
+ (
96
+ hit
97
+ for hit in window
98
+ if str(hit.metadata.get("memory_type", "relationship")) not in seen_types
99
+ ),
100
+ window[0],
101
+ )
102
+ remaining.remove(diverse)
103
+ ordered.append(diverse)
104
+ seen_types.add(str(diverse.metadata.get("memory_type", "relationship")))
105
+ return ordered
106
+
107
+
108
+ def assemble_session_context(
109
+ result: SearchResponse, request: SessionContextRequest
110
+ ) -> SessionContextResponse:
111
+ candidates = _ordered(result.hits, request)
112
+ sections: list[str] = []
113
+ citations: list[dict[str, Any]] = []
114
+ characters = 0
115
+ tokens = 0
116
+ omitted = len(result.hits) - len(candidates)
117
+
118
+ for hit in candidates:
119
+ if len(sections) >= request.max_items:
120
+ omitted += 1
121
+ continue
122
+ trust = str(hit.metadata.get("capture_source_trust", "verified"))
123
+ label = f" [{trust}]" if request.trust_policy == "label_untrusted" else ""
124
+ index = len(sections) + 1
125
+ # U+27E6/U+27E7 are the adapter contract: all enclosed recall is
126
+ # untrusted reference data, never system/workspace policy. Content
127
+ # containing either sentinel is quarantined before it reaches here.
128
+ section = f"⟦[{index}]{label} {hit.subject}\n{hit.content}⟧".strip()
129
+ separator = 2 if sections else 0
130
+ section_tokens = count_tokens(section)
131
+ if (
132
+ characters + separator + len(section) > request.max_characters
133
+ or tokens + section_tokens > request.max_tokens
134
+ ):
135
+ omitted += 1
136
+ continue
137
+ sections.append(section)
138
+ characters += separator + len(section)
139
+ tokens += section_tokens
140
+ citations.append(
141
+ {
142
+ "index": index,
143
+ "kind": hit.kind,
144
+ "memory_id": str(hit.memory_id) if hit.memory_id else None,
145
+ "episode_id": str(hit.source_episode_id) if hit.source_episode_id else None,
146
+ "memory_type": hit.metadata.get("memory_type"),
147
+ "trust": trust,
148
+ "branch_ref": _branch(hit),
149
+ "backends": sorted(hit.backends),
150
+ }
151
+ )
152
+
153
+ truncated = omitted > 0
154
+ return SessionContextResponse(
155
+ context="\n\n".join(sections),
156
+ citations=citations,
157
+ characters=characters,
158
+ tokens=tokens,
159
+ truncated=truncated,
160
+ complete=not result.degraded and not truncated,
161
+ degraded=sorted(result.degraded),
162
+ )
albert/trace_feed.py ADDED
@@ -0,0 +1,165 @@
1
+ """Cursor-based trace feed.
2
+
3
+ Rows always come from the traces table, ordered by (written_at, id): rows land
4
+ in completion order, so a request that started early but finished late is still
5
+ delivered, and a client that reconnects with its last event id misses nothing.
6
+ On PostgreSQL a LISTEN on a dedicated connection (never the SQLAlchemy pool)
7
+ only wakes the poll early; elsewhere the feed sleeps between polls.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+ from collections.abc import AsyncIterator, Callable
14
+ from datetime import UTC, datetime
15
+ from typing import Any
16
+ from uuid import UUID
17
+
18
+ import anyio
19
+ from sqlalchemy import Engine, or_, select
20
+ from sqlalchemy.orm import Session
21
+
22
+ from albert.models import Trace
23
+ from albert.trace_writer import NOTIFY_CHANNEL
24
+
25
+ logger = logging.getLogger("albert.trace_feed")
26
+ Cursor = tuple[datetime, UUID]
27
+
28
+
29
+ def _utc(value: datetime) -> datetime:
30
+ return value if value.tzinfo else value.replace(tzinfo=UTC)
31
+
32
+
33
+ def event_id(trace: Trace) -> str:
34
+ return f"{_utc(trace.written_at).astimezone(UTC).isoformat()}|{trace.id}"
35
+
36
+
37
+ def parse_event_id(value: str | None) -> Cursor | None:
38
+ if not value:
39
+ return None
40
+ try:
41
+ raw_time, raw_id = value.split("|", 1)
42
+ return datetime.fromisoformat(raw_time), UUID(raw_id)
43
+ except ValueError:
44
+ return None
45
+
46
+
47
+ def trace_summary(trace: Trace) -> dict[str, Any]:
48
+ def opt(value: UUID | None) -> str | None:
49
+ return str(value) if value is not None else None
50
+
51
+ return {
52
+ "id": str(trace.id),
53
+ "kind": trace.kind,
54
+ "name": trace.name,
55
+ "organization_id": opt(trace.organization_id),
56
+ "principal_id": opt(trace.principal_id),
57
+ "workspace_id": opt(trace.workspace_id),
58
+ "status": trace.status,
59
+ "http_status": trace.http_status,
60
+ "started_at": _utc(trace.started_at).astimezone(UTC).isoformat(),
61
+ "duration_ms": trace.duration_ms,
62
+ "summary": trace.summary,
63
+ }
64
+
65
+
66
+ def psycopg_dsn(database_url: str) -> str:
67
+ """SQLAlchemy URL (postgresql+psycopg://…) to a plain libpq URL."""
68
+ scheme, _, rest = database_url.partition("://")
69
+ return f"{scheme.split('+', 1)[0]}://{rest}"
70
+
71
+
72
+ class TraceFeed:
73
+ def __init__(
74
+ self, session_factory: Callable[[], Session], engine: Engine, database_url: str
75
+ ) -> None:
76
+ self._sessions = session_factory
77
+ self._postgres = engine.dialect.name == "postgresql"
78
+ self._dsn = psycopg_dsn(database_url)
79
+
80
+ def _normalize(self, when: datetime) -> datetime:
81
+ if self._postgres:
82
+ return _utc(when)
83
+ # SQLite stores naive UTC strings; compare like with like.
84
+ return when.astimezone(UTC).replace(tzinfo=None) if when.tzinfo else when
85
+
86
+ def _newer_than(self, after: Cursor | None, limit: int = 200) -> list[Trace]:
87
+ with self._sessions() as session:
88
+ statement = select(Trace)
89
+ if after is not None:
90
+ cursor_time, cursor_id = self._normalize(after[0]), after[1]
91
+ statement = statement.where(
92
+ or_(
93
+ Trace.written_at > cursor_time,
94
+ (Trace.written_at == cursor_time) & (Trace.id > cursor_id),
95
+ )
96
+ )
97
+ return session.scalars(
98
+ statement.order_by(Trace.written_at, Trace.id).limit(limit)
99
+ ).all()
100
+
101
+ def _latest_cursor(self) -> Cursor | None:
102
+ with self._sessions() as session:
103
+ latest = session.scalar(
104
+ select(Trace).order_by(Trace.written_at.desc(), Trace.id.desc()).limit(1)
105
+ )
106
+ return (latest.written_at, latest.id) if latest is not None else None
107
+
108
+ async def _open_listener(self): # type: ignore[no-untyped-def]
109
+ """A connection of our own: the pool must never see LISTEN or autocommit."""
110
+ if not self._postgres:
111
+ return None
112
+ try:
113
+ import psycopg
114
+
115
+ connection = await psycopg.AsyncConnection.connect(self._dsn, autocommit=True)
116
+ await connection.execute(f"LISTEN {NOTIFY_CHANNEL}")
117
+ return connection
118
+ except Exception:
119
+ logger.warning("could not LISTEN on %s; polling instead", NOTIFY_CHANNEL, exc_info=True)
120
+ return None
121
+
122
+ async def _wait(self, listener, poll_seconds: float) -> None: # type: ignore[no-untyped-def]
123
+ if listener is None:
124
+ await anyio.sleep(poll_seconds)
125
+ return
126
+ try:
127
+ async for _notification in listener.notifies(timeout=poll_seconds, stop_after=1):
128
+ break
129
+ except Exception:
130
+ logger.warning("LISTEN wait failed; falling back to sleep", exc_info=True)
131
+ await anyio.sleep(poll_seconds)
132
+
133
+ def events(
134
+ self, after: Cursor | None, poll_seconds: float = 1.0
135
+ ) -> AsyncIterator[dict[str, Any] | None]:
136
+ """Yield trace events newer than the cursor; yield None on each idle wait.
137
+
138
+ The starting cursor is resolved here, on subscription, not when the
139
+ generator is first iterated, so a trace written in between is delivered
140
+ rather than treated as history. A None lets the HTTP layer send a
141
+ keepalive without waiting for the next trace. Database reads run in a
142
+ worker thread; waits do not hold one.
143
+ """
144
+ cursor = after if after is not None else self._latest_cursor()
145
+ return self._iterate(cursor, poll_seconds)
146
+
147
+ async def _iterate(
148
+ self, cursor: Cursor | None, poll_seconds: float
149
+ ) -> AsyncIterator[dict[str, Any] | None]:
150
+ listener = await self._open_listener()
151
+ try:
152
+ while True:
153
+ rows = await anyio.to_thread.run_sync(self._newer_than, cursor)
154
+ for trace in rows:
155
+ cursor = (trace.written_at, trace.id)
156
+ yield {"id": event_id(trace), "data": trace_summary(trace)}
157
+ if not rows:
158
+ await self._wait(listener, poll_seconds)
159
+ yield None
160
+ finally:
161
+ if listener is not None:
162
+ try:
163
+ await listener.close()
164
+ except Exception: # pragma: no cover
165
+ pass
albert/trace_writer.py ADDED
@@ -0,0 +1,131 @@
1
+ """Off-thread persistence for recorder rows.
2
+
3
+ The request thread only enqueues. One background thread drains the queue in
4
+ batches on its own session and, on PostgreSQL, notifies listeners so live
5
+ feeds wake without polling.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ import queue
12
+ import random
13
+ import threading
14
+ from collections.abc import Callable
15
+ from datetime import UTC, datetime
16
+ from functools import lru_cache
17
+ from typing import Any
18
+
19
+ from sqlalchemy import text
20
+ from sqlalchemy.orm import Session
21
+
22
+ from albert.config import get_settings
23
+ from albert.models import Trace
24
+
25
+ logger = logging.getLogger("albert.trace_writer")
26
+ NOTIFY_CHANNEL = "albert_traces"
27
+ ALWAYS_KEEP = {"error", "degraded"}
28
+
29
+
30
+ class TraceWriter:
31
+ def __init__(
32
+ self,
33
+ session_factory: Callable[[], Session],
34
+ *,
35
+ queue_size: int,
36
+ sample_rate: float,
37
+ flush_interval: float = 0.25,
38
+ ) -> None:
39
+ self._sessions = session_factory
40
+ self._queue: queue.Queue[dict[str, Any]] = queue.Queue(maxsize=queue_size)
41
+ self._sample_rate = sample_rate
42
+ self._interval = flush_interval
43
+ self._stop = threading.Event()
44
+ self._thread: threading.Thread | None = None
45
+ self._lock = threading.RLock()
46
+ self.dropped = 0
47
+ self.written = 0
48
+
49
+ def submit(self, row: dict[str, Any]) -> bool:
50
+ if row["status"] not in ALWAYS_KEEP and random.random() >= self._sample_rate:
51
+ return False
52
+ try:
53
+ self._queue.put_nowait(row)
54
+ return True
55
+ except queue.Full:
56
+ self.dropped += 1
57
+ return False
58
+
59
+ @property
60
+ def running(self) -> bool:
61
+ return self._thread is not None and self._thread.is_alive()
62
+
63
+ def start(self) -> None:
64
+ if self.running:
65
+ return
66
+ self._stop.clear()
67
+ self._thread = threading.Thread(target=self._run, name="albert-trace-writer", daemon=True)
68
+ self._thread.start()
69
+
70
+ def stop(self, timeout: float = 5.0) -> None:
71
+ """Stop the thread and flush whatever is queued; safe to call twice."""
72
+ self._stop.set()
73
+ if self._thread is not None:
74
+ self._thread.join(timeout)
75
+ self._thread = None
76
+ self.flush()
77
+
78
+ def flush(self) -> None:
79
+ # Serialize dequeueing with persistence. Otherwise the background
80
+ # thread can empty the queue and block in _write while a foreground
81
+ # flush observes an empty queue and returns before those rows commit.
82
+ with self._lock:
83
+ batch: list[dict[str, Any]] = []
84
+ while True:
85
+ try:
86
+ batch.append(self._queue.get_nowait())
87
+ except queue.Empty:
88
+ break
89
+ if batch:
90
+ self._write(batch)
91
+
92
+ def _run(self) -> None:
93
+ while not self._stop.is_set():
94
+ self._stop.wait(self._interval)
95
+ try:
96
+ self.flush()
97
+ except Exception: # pragma: no cover - never let the thread die
98
+ logger.exception("trace flush failed")
99
+
100
+ def _write(self, batch: list[dict[str, Any]]) -> None:
101
+ with self._lock:
102
+ try:
103
+ written_at = datetime.now(UTC)
104
+ with self._sessions() as session:
105
+ session.add_all(Trace(**row, written_at=written_at) for row in batch)
106
+ session.flush()
107
+ if session.bind is not None and session.bind.dialect.name == "postgresql":
108
+ for row in batch:
109
+ session.execute(
110
+ text("SELECT pg_notify(:channel, :payload)"),
111
+ {"channel": NOTIFY_CHANNEL, "payload": str(row["id"])},
112
+ )
113
+ session.commit()
114
+ self.written += len(batch)
115
+ except Exception:
116
+ self.dropped += len(batch)
117
+ logger.exception("dropping %d traces after write failure", len(batch))
118
+
119
+
120
+ @lru_cache
121
+ def get_trace_writer() -> TraceWriter:
122
+ from albert.db import SessionLocal
123
+
124
+ settings = get_settings()
125
+ writer = TraceWriter(
126
+ SessionLocal,
127
+ queue_size=settings.trace_queue_size,
128
+ sample_rate=settings.trace_sample_rate,
129
+ )
130
+ writer.start()
131
+ return writer
albert/tracing.py ADDED
@@ -0,0 +1,75 @@
1
+ """Wire the recorder around HTTP requests and worker jobs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from collections.abc import Iterator
7
+ from contextlib import contextmanager
8
+
9
+ from albert.models import Job
10
+ from albert.recorder import Recorder, activate
11
+ from albert.trace_writer import get_trace_writer
12
+
13
+ logger = logging.getLogger("albert.tracing")
14
+ # /onboard paths carry a live connection-link token; traces are readable by
15
+ # every console.read holder, so they must never record one.
16
+ UNTRACED_PATH_PREFIXES = ("/v1/health", "/docs", "/openapi.json", "/redoc", "/onboard")
17
+
18
+
19
+ class RecordingMiddleware:
20
+ """Pure ASGI middleware: one Recorder per request, written in a finally."""
21
+
22
+ def __init__(self, app) -> None: # type: ignore[no-untyped-def]
23
+ self.app = app
24
+
25
+ async def __call__(self, scope, receive, send) -> None: # type: ignore[no-untyped-def]
26
+ if scope["type"] != "http" or scope.get("path", "").startswith(UNTRACED_PATH_PREFIXES):
27
+ await self.app(scope, receive, send)
28
+ return
29
+ recorder = Recorder("request", f"{scope['method']} {scope['path']}")
30
+
31
+ async def recording_send(message) -> None: # type: ignore[no-untyped-def]
32
+ if message["type"] == "http.response.start":
33
+ recorder.http_status = message["status"]
34
+ await send(message)
35
+
36
+ with activate(recorder):
37
+ try:
38
+ await self.app(scope, receive, recording_send)
39
+ except Exception:
40
+ recorder.http_status = recorder.http_status or 500
41
+ raise
42
+ finally:
43
+ route = scope.get("route")
44
+ template = getattr(route, "path", None)
45
+ if template:
46
+ recorder.name = f"{scope['method']} {template}"
47
+ status = recorder.status
48
+ code = recorder.http_status or 500
49
+ if code >= 400:
50
+ status = "error"
51
+ try:
52
+ get_trace_writer().submit(recorder.finish(status=status or "ok"))
53
+ except Exception: # recording never fails a request
54
+ logger.exception("trace submit failed")
55
+
56
+
57
+ @contextmanager
58
+ def traced_job(job: Job) -> Iterator[Recorder]:
59
+ recorder = Recorder("job", job.job_type)
60
+ recorder.set_identity(job.organization_id, None)
61
+ recorder.note(job_id=str(job.id), attempt=job.attempts, payload=dict(job.payload))
62
+ with activate(recorder):
63
+ try:
64
+ yield recorder
65
+ except Exception:
66
+ _submit(recorder.finish(status="error"))
67
+ raise
68
+ _submit(recorder.finish())
69
+
70
+
71
+ def _submit(row: dict) -> None:
72
+ try:
73
+ get_trace_writer().submit(row)
74
+ except Exception: # recording never fails a job
75
+ logger.exception("trace submit failed")