fafo 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fafo/__init__.py +3 -0
- fafo/activity.py +165 -0
- fafo/adapters/__init__.py +1 -0
- fafo/adapters/base.py +39 -0
- fafo/adapters/safo.py +200 -0
- fafo/attention.py +405 -0
- fafo/attribution.py +324 -0
- fafo/cli.py +295 -0
- fafo/collector.py +461 -0
- fafo/config.py +655 -0
- fafo/filemodes.py +206 -0
- fafo/ghapi.py +416 -0
- fafo/history.py +356 -0
- fafo/hostzombies.py +77 -0
- fafo/jsonsafe.py +149 -0
- fafo/links.py +189 -0
- fafo/metrics.py +307 -0
- fafo/metrics_server.py +559 -0
- fafo/model.py +223 -0
- fafo/pace.py +156 -0
- fafo/proccache.py +92 -0
- fafo/procutil.py +91 -0
- fafo/redact.py +683 -0
- fafo/registry.py +346 -0
- fafo/render/__init__.py +0 -0
- fafo/render/commands.py +357 -0
- fafo/render/events.py +257 -0
- fafo/render/export.py +285 -0
- fafo/render/line.py +135 -0
- fafo/render/table.py +522 -0
- fafo/render/tui.py +1421 -0
- fafo/render/view.py +1529 -0
- fafo/repospec.py +14 -0
- fafo/source.py +43 -0
- fafo/sources/__init__.py +0 -0
- fafo/sources/claude.py +531 -0
- fafo/sources/codex.py +599 -0
- fafo/sources/codex_jobs.py +397 -0
- fafo/sources/codex_sessions.py +675 -0
- fafo/sources/copilot.py +264 -0
- fafo/sources/gemini.py +42 -0
- fafo/sources/host.py +344 -0
- fafo/sources/ledger.py +207 -0
- fafo/sources/llm_leases.py +212 -0
- fafo/sources/ollama.py +435 -0
- fafo/sources/quota_claude.py +255 -0
- fafo/sources/quota_codex.py +357 -0
- fafo/sources/runners.py +566 -0
- fafo/sshro.py +240 -0
- fafo/store.py +800 -0
- fafo/transcript.py +773 -0
- fafo/usage.py +869 -0
- fafo/zombie.py +44 -0
- fafo-0.1.0.dist-info/METADATA +715 -0
- fafo-0.1.0.dist-info/RECORD +59 -0
- fafo-0.1.0.dist-info/WHEEL +5 -0
- fafo-0.1.0.dist-info/entry_points.txt +2 -0
- fafo-0.1.0.dist-info/licenses/LICENSE +201 -0
- fafo-0.1.0.dist-info/top_level.txt +1 -0
fafo/__init__.py
ADDED
fafo/activity.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Active or idle for a worker, from how its cumulative CPU time moved over a few samples.
|
|
2
|
+
|
|
3
|
+
Pure: no I/O, and the clock is injected. One sample per collect cycle per process goes in; the
|
|
4
|
+
tracker keeps the last few for each (pid, create_time) and classifies from the oldest and newest
|
|
5
|
+
of them. A pid reused by a new process has a different create_time, so it starts a new series.
|
|
6
|
+
|
|
7
|
+
Never guesses: with fewer than two usable samples, or when a value cannot be trusted, the answer
|
|
8
|
+
is `unknown`.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import math
|
|
14
|
+
import threading
|
|
15
|
+
import time
|
|
16
|
+
from collections import OrderedDict
|
|
17
|
+
from collections.abc import Callable, Iterable
|
|
18
|
+
from typing import Any, Literal, get_args
|
|
19
|
+
|
|
20
|
+
Activity = Literal["active", "idle", "unknown"]
|
|
21
|
+
ACTIVITIES: tuple[str, ...] = get_args(Activity)
|
|
22
|
+
|
|
23
|
+
WINDOW = 4 # samples kept per process
|
|
24
|
+
MAX_ENTRIES = 2048 # processes tracked at once
|
|
25
|
+
EXPIRY_S = 60.0 # an entry not seen for this long is dropped
|
|
26
|
+
# The old ai-status tool used 1.0 (percent of one core, sampled over 250 ms). CPU time comes in
|
|
27
|
+
# ticks of 10 ms, so a window shorter than MIN_SPAN_S is too coarse to judge and stays unknown.
|
|
28
|
+
DEFAULT_ACTIVE_PCT = 1.0
|
|
29
|
+
MIN_ACTIVE_PCT = 0.5
|
|
30
|
+
MAX_ACTIVE_PCT = 100.0
|
|
31
|
+
MIN_SPAN_S = 0.5
|
|
32
|
+
MAX_CPU_TIME_S = 1e9 # about 31 years of CPU time; anything above is not a real reading
|
|
33
|
+
MAX_EPOCH_S = 4e9 # epoch seconds (year 2096): the bound for process start times and the clock
|
|
34
|
+
|
|
35
|
+
Key = tuple[int, float]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _in_range(value: object, low: float, high: float) -> bool:
|
|
39
|
+
"""True for an int or a float (never bool) from low to high inclusive. An int is compared as
|
|
40
|
+
an int, so a huge one is never converted to float and cannot overflow; NaN and inf fail."""
|
|
41
|
+
if type(value) is int:
|
|
42
|
+
return low <= value <= high
|
|
43
|
+
if type(value) is float:
|
|
44
|
+
return math.isfinite(value) and low <= value <= high
|
|
45
|
+
return False
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def valid_pct(value: object) -> bool:
|
|
49
|
+
"""True for a real number (not bool) from MIN_ACTIVE_PCT to MAX_ACTIVE_PCT."""
|
|
50
|
+
return _in_range(value, MIN_ACTIVE_PCT, MAX_ACTIVE_PCT)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def clean_activity(value: object) -> str:
|
|
54
|
+
"""The value if it is one of the three words, else `unknown`."""
|
|
55
|
+
return value if type(value) is str and value in ACTIVITIES else "unknown"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _good_cpu_time(value: object) -> bool:
|
|
59
|
+
return _in_range(value, 0.0, MAX_CPU_TIME_S)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _good_start(value: object) -> bool:
|
|
63
|
+
"""A process start time is epoch seconds (psutil create_time), not CPU seconds."""
|
|
64
|
+
return _in_range(value, 0.0, MAX_EPOCH_S)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class ActivityTracker:
|
|
68
|
+
def __init__(
|
|
69
|
+
self,
|
|
70
|
+
active_pct: float = DEFAULT_ACTIVE_PCT,
|
|
71
|
+
*,
|
|
72
|
+
clock: Callable[[], float] = time.monotonic,
|
|
73
|
+
window: int = WINDOW,
|
|
74
|
+
max_entries: int = MAX_ENTRIES,
|
|
75
|
+
expiry_s: float = EXPIRY_S,
|
|
76
|
+
) -> None:
|
|
77
|
+
if not valid_pct(active_pct):
|
|
78
|
+
raise ValueError("active_pct out of range")
|
|
79
|
+
self._pct = float(active_pct)
|
|
80
|
+
self._clock = clock
|
|
81
|
+
self._window = max(2, min(int(window), 64))
|
|
82
|
+
self._max = max(1, min(int(max_entries), MAX_ENTRIES))
|
|
83
|
+
self._expiry = float(expiry_s)
|
|
84
|
+
# key -> (last seen, [(time, cpu_time), ...]); least recently seen first
|
|
85
|
+
self._items: OrderedDict[Key, tuple[float, list[tuple[float, float]]]] = OrderedDict()
|
|
86
|
+
self._lock = threading.Lock()
|
|
87
|
+
|
|
88
|
+
def __len__(self) -> int:
|
|
89
|
+
with self._lock:
|
|
90
|
+
return len(self._items)
|
|
91
|
+
|
|
92
|
+
def _purge(self, now: float) -> None:
|
|
93
|
+
while self._items:
|
|
94
|
+
key = next(iter(self._items))
|
|
95
|
+
if now - self._items[key][0] > self._expiry:
|
|
96
|
+
del self._items[key]
|
|
97
|
+
else:
|
|
98
|
+
break
|
|
99
|
+
|
|
100
|
+
def observe(self, pid: object, create_time: object, cpu_time: object) -> Activity:
|
|
101
|
+
"""Record one reading of cumulative CPU seconds and return the classification."""
|
|
102
|
+
if type(pid) is not int or not _good_start(create_time):
|
|
103
|
+
return "unknown"
|
|
104
|
+
try:
|
|
105
|
+
raw_now = self._clock()
|
|
106
|
+
except Exception: # noqa: BLE001 - a broken injected clock must not break a cycle
|
|
107
|
+
return "unknown"
|
|
108
|
+
if not _in_range(raw_now, 0.0, MAX_EPOCH_S):
|
|
109
|
+
return "unknown"
|
|
110
|
+
now = float(raw_now)
|
|
111
|
+
key: Key = (pid, float(create_time)) # type: ignore[arg-type]
|
|
112
|
+
with self._lock:
|
|
113
|
+
self._purge(now)
|
|
114
|
+
if not _good_cpu_time(cpu_time):
|
|
115
|
+
self._items.pop(key, None) # an untrusted reading ends the series
|
|
116
|
+
return "unknown"
|
|
117
|
+
cpu = float(cpu_time) # type: ignore[arg-type]
|
|
118
|
+
entry = self._items.get(key)
|
|
119
|
+
samples = entry[1] if entry is not None else []
|
|
120
|
+
if samples and (now < samples[-1][0] or cpu < samples[-1][1]):
|
|
121
|
+
samples = [] # the clock or the counter went backwards: start again
|
|
122
|
+
if samples and now == samples[-1][0]:
|
|
123
|
+
samples[-1] = (now, cpu)
|
|
124
|
+
else:
|
|
125
|
+
samples.append((now, cpu))
|
|
126
|
+
del samples[: -self._window]
|
|
127
|
+
self._items[key] = (now, samples)
|
|
128
|
+
self._items.move_to_end(key)
|
|
129
|
+
while len(self._items) > self._max:
|
|
130
|
+
self._items.popitem(last=False)
|
|
131
|
+
return self._classify(samples)
|
|
132
|
+
|
|
133
|
+
def _classify(self, samples: list[tuple[float, float]]) -> Activity:
|
|
134
|
+
if len(samples) < 2:
|
|
135
|
+
return "unknown"
|
|
136
|
+
(t0, c0), (t1, c1) = samples[0], samples[-1]
|
|
137
|
+
span = t1 - t0
|
|
138
|
+
if not span >= MIN_SPAN_S:
|
|
139
|
+
return "unknown"
|
|
140
|
+
return "active" if (c1 - c0) / span * 100.0 >= self._pct else "idle"
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def observe_activity(tracker: ActivityTracker | None, pid: int, entry: Any) -> Activity:
|
|
144
|
+
"""Read user plus system CPU seconds from entry.handle and record them. Any failure to read
|
|
145
|
+
(a vanished process, a handle without cpu_times, odd values) is `unknown`, never an error."""
|
|
146
|
+
if tracker is None:
|
|
147
|
+
return "unknown"
|
|
148
|
+
try:
|
|
149
|
+
t = entry.handle.cpu_times()
|
|
150
|
+
total = t.user + t.system
|
|
151
|
+
return tracker.observe(pid, entry.started, total)
|
|
152
|
+
except Exception: # noqa: BLE001 - psutil errors, missing method, odd types, overflow
|
|
153
|
+
return "unknown"
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def counts(states: Iterable[object], fallback_active: Iterable[bool]) -> tuple[int, int]:
|
|
157
|
+
"""(active, total) for workers: the activity word when known, else the fallback flag (the
|
|
158
|
+
older CPU rule) for that worker. Both iterables are in the same order."""
|
|
159
|
+
active = total = 0
|
|
160
|
+
for state, fb in zip(states, fallback_active):
|
|
161
|
+
total += 1
|
|
162
|
+
word = clean_activity(state)
|
|
163
|
+
if word == "active" or (word == "unknown" and fb):
|
|
164
|
+
active += 1
|
|
165
|
+
return active, total
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Optional work-tracker adapters. They enrich sessions; they never alter them."""
|
fafo/adapters/base.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Adapter protocol and the enrichment row. Plain data, no I/O."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from collections.abc import Mapping, Sequence
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Protocol
|
|
9
|
+
|
|
10
|
+
MAX_FIELD = 120
|
|
11
|
+
_CONTROL = re.compile("[\u0000-\u001f\u007f-\u009f]")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def clean(value: object) -> str | None:
|
|
15
|
+
"""Strip control characters and cap at 120 chars; non-strings and empties become None."""
|
|
16
|
+
if not isinstance(value, str):
|
|
17
|
+
return None
|
|
18
|
+
out = _CONTROL.sub("", value[: MAX_FIELD * 4])[:MAX_FIELD].strip()
|
|
19
|
+
return out or None
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class Enrichment:
|
|
24
|
+
issue: str | None = None
|
|
25
|
+
card_status: str | None = None
|
|
26
|
+
epic: str | None = None
|
|
27
|
+
effort: str | None = None
|
|
28
|
+
|
|
29
|
+
def __post_init__(self) -> None:
|
|
30
|
+
for name in ("issue", "card_status", "epic", "effort"):
|
|
31
|
+
object.__setattr__(self, name, clean(getattr(self, name)))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Adapter(Protocol):
|
|
35
|
+
name: str
|
|
36
|
+
|
|
37
|
+
def enrich(
|
|
38
|
+
self, session_ids: Sequence[str], text_by_session: Mapping[str, str]
|
|
39
|
+
) -> dict[str, Enrichment]: ...
|
fafo/adapters/safo.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
"""SAFO adapter; SHIT is the same class built with another command and field names.
|
|
2
|
+
|
|
3
|
+
Finding (checked 2026-11-27 against `safo --help` and docs/agents-status.md): SAFO offers
|
|
4
|
+
no machine-readable per-session source. `safo agents-status` is human text with no --json and
|
|
5
|
+
reads the board over the network; `safo usage --json` and `safo local report --json` carry
|
|
6
|
+
usage, not issue or card data. So this adapter reads a documented JSON shape from a
|
|
7
|
+
configured command, and reports `absent` when the command is missing or its output does not
|
|
8
|
+
match, strictly and all or nothing (exact top-level key, at most 1000 rows, every row an
|
|
9
|
+
object with only the five keys, unique non-empty session ids, string or null values). Shape (see tests/fixtures/safo_agents_status.json):
|
|
10
|
+
|
|
11
|
+
{"sessions": [{"session_id": "s1", "issue": "owner/repo#12", "card_status": "In progress",
|
|
12
|
+
"epic": "Epic name", "effort": "M"}]}
|
|
13
|
+
|
|
14
|
+
`field_names` maps our names (session_id, issue, card_status, epic, effort) to the keys the
|
|
15
|
+
command emits. If the command gives no issue for a session, a brief line `issue: owner/repo#N`
|
|
16
|
+
in that session's text is used.
|
|
17
|
+
|
|
18
|
+
The command runs as an argument list (never a shell), with a timeout, a minimal environment,
|
|
19
|
+
stdin closed and output capped at 256 KB. After `enrich`, `health` is ok, stale or absent.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import json
|
|
25
|
+
import os
|
|
26
|
+
import re
|
|
27
|
+
import selectors
|
|
28
|
+
import subprocess
|
|
29
|
+
import time
|
|
30
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
31
|
+
|
|
32
|
+
from fafo.adapters.base import Enrichment, clean
|
|
33
|
+
from fafo.procutil import kill_and_reap, wait_exited_unreaped
|
|
34
|
+
|
|
35
|
+
MAX_OUTPUT = 256 * 1024
|
|
36
|
+
MAX_DEPTH = 8
|
|
37
|
+
MAX_ROWS = 1000
|
|
38
|
+
_SESSION_ID = re.compile(r"[A-Za-z0-9._:-]{1,128}")
|
|
39
|
+
_ISSUE_LINE = re.compile(r"issue: ([A-Za-z0-9._-]{1,100})/([A-Za-z0-9._-]{1,100})#([0-9]{1,7})")
|
|
40
|
+
_DEFAULT_FIELDS = {
|
|
41
|
+
"session_id": "session_id",
|
|
42
|
+
"issue": "issue",
|
|
43
|
+
"card_status": "card_status",
|
|
44
|
+
"epic": "epic",
|
|
45
|
+
"effort": "effort",
|
|
46
|
+
}
|
|
47
|
+
_VALUE_KEYS = ("issue", "card_status", "epic", "effort")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def parse_issue_line(text: str) -> str | None:
|
|
51
|
+
"""Return `owner/repo#N` from the first `issue:` line, or None. First match only."""
|
|
52
|
+
for line in text.split("\n"):
|
|
53
|
+
if line.startswith("issue:"):
|
|
54
|
+
m = _ISSUE_LINE.fullmatch(line)
|
|
55
|
+
return f"{m[1]}/{m[2]}#{m[3]}" if m else None
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _depth_ok(obj: object) -> bool:
|
|
60
|
+
stack = [(obj, 1)]
|
|
61
|
+
while stack:
|
|
62
|
+
cur, d = stack.pop()
|
|
63
|
+
if d > MAX_DEPTH:
|
|
64
|
+
return False
|
|
65
|
+
if isinstance(cur, dict):
|
|
66
|
+
stack.extend((v, d + 1) for v in cur.values())
|
|
67
|
+
elif isinstance(cur, list):
|
|
68
|
+
stack.extend((v, d + 1) for v in cur)
|
|
69
|
+
return True
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _default_runner(argv: Sequence[str], timeout_s: float, env: Mapping[str, str]) -> bytes:
|
|
73
|
+
"""Run argv; return at most MAX_OUTPUT + 1 bytes of stdout.
|
|
74
|
+
|
|
75
|
+
One monotonic deadline covers the whole call (reads and exit). On deadline or oversize
|
|
76
|
+
the child's whole process group is killed. Raises FileNotFoundError or
|
|
77
|
+
subprocess.TimeoutExpired.
|
|
78
|
+
"""
|
|
79
|
+
proc = subprocess.Popen(
|
|
80
|
+
list(argv),
|
|
81
|
+
stdin=subprocess.DEVNULL,
|
|
82
|
+
stdout=subprocess.PIPE,
|
|
83
|
+
stderr=subprocess.DEVNULL,
|
|
84
|
+
env=dict(env),
|
|
85
|
+
shell=False,
|
|
86
|
+
start_new_session=True,
|
|
87
|
+
bufsize=0,
|
|
88
|
+
)
|
|
89
|
+
deadline = time.monotonic() + timeout_s
|
|
90
|
+
buf = bytearray()
|
|
91
|
+
try:
|
|
92
|
+
assert proc.stdout is not None
|
|
93
|
+
fd = proc.stdout.fileno()
|
|
94
|
+
with selectors.DefaultSelector() as sel:
|
|
95
|
+
sel.register(fd, selectors.EVENT_READ)
|
|
96
|
+
while len(buf) <= MAX_OUTPUT:
|
|
97
|
+
remaining = deadline - time.monotonic()
|
|
98
|
+
if remaining <= 0 or not sel.select(remaining):
|
|
99
|
+
raise subprocess.TimeoutExpired(list(argv), timeout_s)
|
|
100
|
+
chunk = os.read(fd, min(65536, MAX_OUTPUT + 1 - len(buf)))
|
|
101
|
+
if not chunk:
|
|
102
|
+
break
|
|
103
|
+
buf += chunk
|
|
104
|
+
if len(buf) <= MAX_OUTPUT:
|
|
105
|
+
if not wait_exited_unreaped(proc, deadline - time.monotonic()):
|
|
106
|
+
raise subprocess.TimeoutExpired(list(argv), timeout_s)
|
|
107
|
+
kill_and_reap(proc) # exited: kill any grandchild, then reap
|
|
108
|
+
return bytes(buf)
|
|
109
|
+
finally:
|
|
110
|
+
kill_and_reap(proc) # kill the group before the reap, never after
|
|
111
|
+
if proc.stdout is not None:
|
|
112
|
+
proc.stdout.close()
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class SafoAdapter:
|
|
116
|
+
def __init__(
|
|
117
|
+
self,
|
|
118
|
+
command: Sequence[str],
|
|
119
|
+
timeout_s: float = 5.0,
|
|
120
|
+
field_names: Mapping[str, str] | None = None,
|
|
121
|
+
runner: Callable[[Sequence[str], float, Mapping[str, str]], bytes] | None = None,
|
|
122
|
+
name: str = "safo",
|
|
123
|
+
) -> None:
|
|
124
|
+
self.name = name
|
|
125
|
+
self.command = list(command)
|
|
126
|
+
self.timeout_s = timeout_s
|
|
127
|
+
self.fields = {**_DEFAULT_FIELDS, **(field_names or {})}
|
|
128
|
+
self._runner = runner or _default_runner
|
|
129
|
+
self.health = "absent"
|
|
130
|
+
|
|
131
|
+
def _env(self) -> dict[str, str]:
|
|
132
|
+
env = {"LANG": "C"}
|
|
133
|
+
for key in ("PATH", "HOME"):
|
|
134
|
+
if key in os.environ:
|
|
135
|
+
env[key] = os.environ[key]
|
|
136
|
+
return env
|
|
137
|
+
|
|
138
|
+
def _fetch(self) -> list[dict[str, object]] | None:
|
|
139
|
+
try:
|
|
140
|
+
raw = self._runner(self.command, self.timeout_s, self._env())
|
|
141
|
+
except (subprocess.TimeoutExpired, TimeoutError):
|
|
142
|
+
self.health = "stale"
|
|
143
|
+
return None
|
|
144
|
+
except OSError:
|
|
145
|
+
self.health = "absent"
|
|
146
|
+
return None
|
|
147
|
+
if len(raw) > MAX_OUTPUT:
|
|
148
|
+
self.health = "absent"
|
|
149
|
+
return None
|
|
150
|
+
try:
|
|
151
|
+
data = json.loads(raw)
|
|
152
|
+
except (ValueError, RecursionError):
|
|
153
|
+
self.health = "absent"
|
|
154
|
+
return None
|
|
155
|
+
rows = self._validate(data)
|
|
156
|
+
if rows is None:
|
|
157
|
+
self.health = "absent"
|
|
158
|
+
return None
|
|
159
|
+
self.health = "ok"
|
|
160
|
+
return rows
|
|
161
|
+
|
|
162
|
+
def _validate(self, data: object) -> list[dict[str, object]] | None:
|
|
163
|
+
"""All-or-nothing: any violation of the documented shape rejects the whole output."""
|
|
164
|
+
if not isinstance(data, dict) or set(data) != {"sessions"} or not _depth_ok(data):
|
|
165
|
+
return None
|
|
166
|
+
rows = data["sessions"]
|
|
167
|
+
if not isinstance(rows, list) or len(rows) > MAX_ROWS:
|
|
168
|
+
return None
|
|
169
|
+
id_key = self.fields["session_id"]
|
|
170
|
+
allowed = {self.fields[k] for k in _DEFAULT_FIELDS}
|
|
171
|
+
seen: set[str] = set()
|
|
172
|
+
for row in rows:
|
|
173
|
+
if not isinstance(row, dict) or not set(row) <= allowed:
|
|
174
|
+
return None
|
|
175
|
+
sid = row.get(id_key)
|
|
176
|
+
if not isinstance(sid, str) or not _SESSION_ID.fullmatch(sid) or sid in seen:
|
|
177
|
+
return None
|
|
178
|
+
seen.add(sid)
|
|
179
|
+
if any(k != id_key and v is not None and not isinstance(v, str)
|
|
180
|
+
for k, v in row.items()):
|
|
181
|
+
return None
|
|
182
|
+
return rows
|
|
183
|
+
|
|
184
|
+
def enrich(
|
|
185
|
+
self, session_ids: Sequence[str], text_by_session: Mapping[str, str]
|
|
186
|
+
) -> dict[str, Enrichment]:
|
|
187
|
+
rows = self._fetch()
|
|
188
|
+
if rows is None:
|
|
189
|
+
return {}
|
|
190
|
+
wanted = set(session_ids)
|
|
191
|
+
out: dict[str, Enrichment] = {}
|
|
192
|
+
for row in rows:
|
|
193
|
+
sid = row[self.fields["session_id"]]
|
|
194
|
+
if sid not in wanted:
|
|
195
|
+
continue
|
|
196
|
+
vals = {k: clean(row.get(self.fields[k])) for k in _VALUE_KEYS}
|
|
197
|
+
if vals["issue"] is None:
|
|
198
|
+
vals["issue"] = parse_issue_line(text_by_session.get(sid, ""))
|
|
199
|
+
out[sid] = Enrichment(**vals)
|
|
200
|
+
return out
|