clarent-methods 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.
- clarent/__init__.py +2 -0
- clarent/__main__.py +5 -0
- clarent/_methods/ach/CARD.md +46 -0
- clarent/_methods/ach/clarent_ach/__init__.py +6 -0
- clarent/_methods/ach/clarent_ach/__main__.py +5 -0
- clarent/_methods/ach/clarent_ach/cli.py +123 -0
- clarent/_methods/ach/clarent_ach/engine.py +214 -0
- clarent/_methods/ach/clarent_ach/i18n.py +160 -0
- clarent/_methods/ach/clarent_ach/model.py +174 -0
- clarent/_methods/ach/clarent_ach/render.py +72 -0
- clarent/_methods/ach/examples/flaky-test.es.json +156 -0
- clarent/_methods/ach/examples/flaky-test.json +156 -0
- clarent/_methods/ach/method.toml +43 -0
- clarent/_methods/ach/skill/SKILL.md +58 -0
- clarent/_methods/ach/tests/test_ach.py +231 -0
- clarent/_methods/redteam/CARD.md +66 -0
- clarent/_methods/redteam/clarent_redteam/__init__.py +6 -0
- clarent/_methods/redteam/clarent_redteam/__main__.py +5 -0
- clarent/_methods/redteam/clarent_redteam/catalog.py +192 -0
- clarent/_methods/redteam/clarent_redteam/cli.py +189 -0
- clarent/_methods/redteam/clarent_redteam/engine.py +281 -0
- clarent/_methods/redteam/clarent_redteam/i18n.py +199 -0
- clarent/_methods/redteam/clarent_redteam/model.py +320 -0
- clarent/_methods/redteam/clarent_redteam/render.py +103 -0
- clarent/_methods/redteam/examples/design-doc/design.es.md +27 -0
- clarent/_methods/redteam/examples/design-doc/design.md +27 -0
- clarent/_methods/redteam/examples/design-doc/findings.es.json +132 -0
- clarent/_methods/redteam/examples/design-doc/findings.json +132 -0
- clarent/_methods/redteam/examples/design-doc/findings.rejected.json +130 -0
- clarent/_methods/redteam/examples/pr/change.diff +34 -0
- clarent/_methods/redteam/examples/pr/description.md +13 -0
- clarent/_methods/redteam/examples/pr/findings.json +114 -0
- clarent/_methods/redteam/method.toml +43 -0
- clarent/_methods/redteam/skill/SKILL.md +52 -0
- clarent/_methods/redteam/tests/test_redteam.py +640 -0
- clarent/_methods/triz-matrix/CARD.md +50 -0
- clarent/_methods/triz-matrix/clarent_triz/__init__.py +6 -0
- clarent/_methods/triz-matrix/clarent_triz/__main__.py +5 -0
- clarent/_methods/triz-matrix/clarent_triz/cli.py +184 -0
- clarent/_methods/triz-matrix/clarent_triz/data/DATA_LICENSE.md +51 -0
- clarent/_methods/triz-matrix/clarent_triz/data/catalog.json +89 -0
- clarent/_methods/triz-matrix/clarent_triz/data/matrix.json +11920 -0
- clarent/_methods/triz-matrix/clarent_triz/engine.py +103 -0
- clarent/_methods/triz-matrix/clarent_triz/i18n.py +134 -0
- clarent/_methods/triz-matrix/clarent_triz/model.py +179 -0
- clarent/_methods/triz-matrix/clarent_triz/render.py +101 -0
- clarent/_methods/triz-matrix/examples/search-api.es.json +9 -0
- clarent/_methods/triz-matrix/examples/search-api.json +9 -0
- clarent/_methods/triz-matrix/method.toml +58 -0
- clarent/_methods/triz-matrix/skill/SKILL.md +50 -0
- clarent/_methods/triz-matrix/tests/test_triz.py +306 -0
- clarent/cli.py +95 -0
- clarent/registry.py +175 -0
- clarent_methods-0.1.0.dist-info/METADATA +227 -0
- clarent_methods-0.1.0.dist-info/RECORD +59 -0
- clarent_methods-0.1.0.dist-info/WHEEL +4 -0
- clarent_methods-0.1.0.dist-info/entry_points.txt +2 -0
- clarent_methods-0.1.0.dist-info/licenses/LICENSE +202 -0
- clarent_methods-0.1.0.dist-info/licenses/NOTICE +12 -0
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
"""Data model, input validation and target indexing for the red team method.
|
|
2
|
+
|
|
3
|
+
Stdlib only. Input: JSON (see examples/). Two kinds of problem are kept apart on purpose:
|
|
4
|
+
|
|
5
|
+
* **Malformed input** (not an object, unknown class, duplicate id, a rating of 9, an attack on an assumption that does
|
|
6
|
+
not exist, a target file that cannot be read) raises `RedTeamError`: the file cannot be analysed at all (exit 2).
|
|
7
|
+
* **A finding that cannot be backed** (a quote that is not in the target, evidence that points at a line that does not
|
|
8
|
+
exist, "verified" with nothing behind it) is not an error: the engine *rejects that finding*, says why, and goes on.
|
|
9
|
+
|
|
10
|
+
Everything the model writes about the target is checked against the target's own text: that is the point of the method.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import bisect
|
|
15
|
+
import re
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from .catalog import CLASSES
|
|
20
|
+
from .i18n import t
|
|
21
|
+
|
|
22
|
+
SCHEMA = "clarent.redteam/1"
|
|
23
|
+
KINDS = ("design", "pr")
|
|
24
|
+
STATUSES = ("verified", "unverified", "contradicted")
|
|
25
|
+
MIN_QUOTE_CHARS = 12 # Clarent's constant: shorter quotes anchor nothing ("the", "retry")
|
|
26
|
+
MAX_FILE_BYTES = 2 * 1024 * 1024
|
|
27
|
+
|
|
28
|
+
_REF_RE = re.compile(r"^(?P<path>[^\s:][^\s:]*\.[A-Za-z0-9_+-]+):(?P<a>\d+)(?:-(?P<b>\d+))?$")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class RedTeamError(ValueError):
|
|
32
|
+
"""Invalid input (reported to the user without a traceback)."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class Evidence:
|
|
37
|
+
ref: str
|
|
38
|
+
observation: str
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class Assumption:
|
|
43
|
+
id: str
|
|
44
|
+
text: str
|
|
45
|
+
status: str
|
|
46
|
+
quote: str
|
|
47
|
+
evidence: tuple[Evidence, ...]
|
|
48
|
+
check: str
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class Attack:
|
|
53
|
+
id: str
|
|
54
|
+
class_id: str
|
|
55
|
+
assumption: str
|
|
56
|
+
quote: str
|
|
57
|
+
text: str
|
|
58
|
+
impact: int
|
|
59
|
+
plausibility: int
|
|
60
|
+
check: str
|
|
61
|
+
evidence: tuple[Evidence, ...]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True)
|
|
65
|
+
class Skipped:
|
|
66
|
+
class_id: str
|
|
67
|
+
reason: str
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass(frozen=True)
|
|
71
|
+
class TargetFile:
|
|
72
|
+
name: str # as shown in reports (relative to the root when possible)
|
|
73
|
+
text: str
|
|
74
|
+
is_diff: bool
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def lines(self) -> list[str]:
|
|
78
|
+
return self.text.splitlines()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass(frozen=True)
|
|
82
|
+
class Findings:
|
|
83
|
+
title: str
|
|
84
|
+
kind: str
|
|
85
|
+
root: Path
|
|
86
|
+
files: tuple[TargetFile, ...]
|
|
87
|
+
assumptions: tuple[Assumption, ...]
|
|
88
|
+
attacks: tuple[Attack, ...]
|
|
89
|
+
skipped: tuple[Skipped, ...]
|
|
90
|
+
warnings: tuple[str, ...] = field(default_factory=tuple)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
# ------------------------------------------------------------------ helpers
|
|
94
|
+
def _need(d: dict, key: str, where: str):
|
|
95
|
+
if not isinstance(d, dict) or key not in d or d[key] in ("", None):
|
|
96
|
+
raise RedTeamError(t("missing_field", where=where, key=key))
|
|
97
|
+
return d[key]
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _rating(d: dict, key: str, where: str) -> int:
|
|
101
|
+
v = _need(d, key, where)
|
|
102
|
+
if isinstance(v, bool) or not isinstance(v, int) or not 1 <= v <= 5:
|
|
103
|
+
raise RedTeamError(t("bad_rating", where=where, key=key, v=v))
|
|
104
|
+
return v
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _evidence(d: dict, where: str) -> tuple[Evidence, ...]:
|
|
108
|
+
raw = d.get("evidence", [])
|
|
109
|
+
if not isinstance(raw, list):
|
|
110
|
+
raise RedTeamError(t("evidence_not_list", where=where))
|
|
111
|
+
out = []
|
|
112
|
+
for i, e in enumerate(raw):
|
|
113
|
+
if not isinstance(e, dict):
|
|
114
|
+
raise RedTeamError(t("not_object", where=f"{where}.evidence[{i}]"))
|
|
115
|
+
out.append(Evidence(str(e.get("ref", "")).strip(), str(e.get("observation", "")).strip()))
|
|
116
|
+
return tuple(out)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _inside(root: Path, rel: str) -> Path | None:
|
|
120
|
+
"""Resolve `rel` under `root`; None if it escapes (absolute paths and '..' are not allowed in the file)."""
|
|
121
|
+
p = (root / rel).resolve()
|
|
122
|
+
try:
|
|
123
|
+
p.relative_to(root.resolve())
|
|
124
|
+
except ValueError:
|
|
125
|
+
return None
|
|
126
|
+
return p
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _read(path: Path, shown: str) -> str:
|
|
130
|
+
try:
|
|
131
|
+
if path.stat().st_size > MAX_FILE_BYTES:
|
|
132
|
+
raise RedTeamError(t("target_big", path=shown, mb=MAX_FILE_BYTES // (1024 * 1024)))
|
|
133
|
+
return path.read_text(encoding="utf-8", errors="replace")
|
|
134
|
+
except FileNotFoundError:
|
|
135
|
+
raise RedTeamError(t("target_missing", path=shown))
|
|
136
|
+
except OSError as e:
|
|
137
|
+
raise RedTeamError(t("target_unreadable", path=shown, e=e))
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _looks_like_diff(name: str, text: str) -> bool:
|
|
141
|
+
if name.lower().endswith((".diff", ".patch")):
|
|
142
|
+
return True
|
|
143
|
+
return any(l.startswith("diff --git ") or l.startswith("@@ ") for l in text.splitlines()[:400])
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
# ------------------------------------------------------------------ parse
|
|
147
|
+
def parse(data: dict, base_dir: Path, *, root: Path | None = None, targets: list[str] | None = None) -> Findings:
|
|
148
|
+
"""Validate `data` and read the target. `base_dir` is the folder of the findings file.
|
|
149
|
+
|
|
150
|
+
The root is where target files and `file:line` refs are resolved: `root` if given, else the file's own `"root"`
|
|
151
|
+
(relative to `base_dir`, default "."). Paths written *inside the file* cannot leave the root; paths given with
|
|
152
|
+
`targets` (the --target option) are the user's own and are read as given.
|
|
153
|
+
"""
|
|
154
|
+
if not isinstance(data, dict):
|
|
155
|
+
raise RedTeamError(t("root_not_object"))
|
|
156
|
+
if "schema" in data and data["schema"] != SCHEMA:
|
|
157
|
+
raise RedTeamError(t("bad_schema", got=data["schema"]))
|
|
158
|
+
warnings: list[str] = []
|
|
159
|
+
|
|
160
|
+
root_dir = (root if root is not None else base_dir / str(data.get("root", "."))).resolve()
|
|
161
|
+
tgt = data.get("target", {})
|
|
162
|
+
if not isinstance(tgt, dict):
|
|
163
|
+
raise RedTeamError(t("not_object", where="target"))
|
|
164
|
+
kind = str(tgt.get("kind", "design")).lower()
|
|
165
|
+
if kind not in KINDS:
|
|
166
|
+
raise RedTeamError(t("bad_kind", v=kind))
|
|
167
|
+
|
|
168
|
+
files: list[TargetFile] = []
|
|
169
|
+
if targets:
|
|
170
|
+
for tp in targets:
|
|
171
|
+
p = Path(tp)
|
|
172
|
+
files.append(_make_file(tp, _read(p, tp)))
|
|
173
|
+
else:
|
|
174
|
+
raw = tgt.get("files")
|
|
175
|
+
if raw is None:
|
|
176
|
+
raise RedTeamError(t("no_target"))
|
|
177
|
+
if not isinstance(raw, list) or not raw or not all(isinstance(x, str) and x for x in raw):
|
|
178
|
+
raise RedTeamError(t("target_not_list"))
|
|
179
|
+
for rel in raw:
|
|
180
|
+
p = _inside(root_dir, rel)
|
|
181
|
+
if p is None:
|
|
182
|
+
raise RedTeamError(t("target_outside", path=rel, root=root_dir))
|
|
183
|
+
files.append(_make_file(rel.replace("\\", "/"), _read(p, rel)))
|
|
184
|
+
|
|
185
|
+
raw_a = data.get("assumptions")
|
|
186
|
+
if not isinstance(raw_a, list) or not raw_a:
|
|
187
|
+
raise RedTeamError(t("need_list", key="assumptions"))
|
|
188
|
+
assumptions: list[Assumption] = []
|
|
189
|
+
for i, a in enumerate(raw_a):
|
|
190
|
+
where = f"assumptions[{i}]"
|
|
191
|
+
if not isinstance(a, dict):
|
|
192
|
+
raise RedTeamError(t("not_object", where=where))
|
|
193
|
+
aid = str(_need(a, "id", where))
|
|
194
|
+
if any(x.id == aid for x in assumptions):
|
|
195
|
+
raise RedTeamError(t("dup_id", where=where, id=aid))
|
|
196
|
+
status = str(a.get("status", "unverified")).lower()
|
|
197
|
+
if status not in STATUSES:
|
|
198
|
+
raise RedTeamError(t("bad_status", where=where, allowed=STATUSES, v=status))
|
|
199
|
+
assumptions.append(Assumption(aid, str(_need(a, "text", where)), status, str(a.get("quote", "")).strip(),
|
|
200
|
+
_evidence(a, where), str(a.get("check", "")).strip()))
|
|
201
|
+
aids = {a.id for a in assumptions}
|
|
202
|
+
|
|
203
|
+
raw_x = data.get("attacks")
|
|
204
|
+
if not isinstance(raw_x, list) or not raw_x:
|
|
205
|
+
raise RedTeamError(t("need_list", key="attacks"))
|
|
206
|
+
attacks: list[Attack] = []
|
|
207
|
+
for i, x in enumerate(raw_x):
|
|
208
|
+
where = f"attacks[{i}]"
|
|
209
|
+
if not isinstance(x, dict):
|
|
210
|
+
raise RedTeamError(t("not_object", where=where))
|
|
211
|
+
xid = str(_need(x, "id", where))
|
|
212
|
+
if any(y.id == xid for y in attacks):
|
|
213
|
+
raise RedTeamError(t("dup_id", where=where, id=xid))
|
|
214
|
+
cls = str(_need(x, "class", where))
|
|
215
|
+
if cls not in CLASSES:
|
|
216
|
+
raise RedTeamError(t("bad_class", where=where, allowed=CLASSES, v=cls))
|
|
217
|
+
aref = str(_need(x, "assumption", where))
|
|
218
|
+
if aref not in aids:
|
|
219
|
+
raise RedTeamError(t("unknown_assumption", where=where, aid=aref))
|
|
220
|
+
attacks.append(Attack(xid, cls, aref, str(x.get("quote", "")).strip(), str(_need(x, "attack", where)),
|
|
221
|
+
_rating(x, "impact", where), _rating(x, "plausibility", where),
|
|
222
|
+
str(x.get("check", "")).strip(), _evidence(x, where)))
|
|
223
|
+
|
|
224
|
+
skipped: list[Skipped] = []
|
|
225
|
+
raw_s = data.get("skipped_classes", [])
|
|
226
|
+
if not isinstance(raw_s, list):
|
|
227
|
+
raise RedTeamError(t("need_list", key="skipped_classes"))
|
|
228
|
+
for i, s in enumerate(raw_s):
|
|
229
|
+
where = f"skipped_classes[{i}]"
|
|
230
|
+
if not isinstance(s, dict):
|
|
231
|
+
raise RedTeamError(t("not_object", where=where))
|
|
232
|
+
cls = str(_need(s, "class", where))
|
|
233
|
+
if cls not in CLASSES:
|
|
234
|
+
raise RedTeamError(t("bad_class", where=where, allowed=CLASSES, v=cls))
|
|
235
|
+
reason = str(s.get("reason", "")).strip()
|
|
236
|
+
if not reason:
|
|
237
|
+
warnings.append(t("w_skip_no_reason", name=cls))
|
|
238
|
+
continue
|
|
239
|
+
skipped.append(Skipped(cls, reason))
|
|
240
|
+
|
|
241
|
+
return Findings(str(data.get("title", "Red team")), kind, root_dir, tuple(files), tuple(assumptions),
|
|
242
|
+
tuple(attacks), tuple(skipped), tuple(warnings))
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _make_file(name: str, text: str) -> TargetFile:
|
|
246
|
+
return TargetFile(name, text, _looks_like_diff(name, text))
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
# ------------------------------------------------------------------ anchoring
|
|
250
|
+
def _views(f: TargetFile) -> list[list[tuple[str, int]]]:
|
|
251
|
+
"""Token streams (token, 1-based line) in which a quote may be found.
|
|
252
|
+
|
|
253
|
+
View 1 is the file as written. For a diff, view 2 drops the leading '+', '-' or ' ' of each hunk line, so a quote
|
|
254
|
+
copied from the code (without the diff markers) still anchors to the line it came from.
|
|
255
|
+
"""
|
|
256
|
+
raw = [(tok, n) for n, line in enumerate(f.lines, 1) for tok in line.split()]
|
|
257
|
+
views = [raw]
|
|
258
|
+
if f.is_diff:
|
|
259
|
+
body, in_hunk = [], False
|
|
260
|
+
for n, line in enumerate(f.lines, 1):
|
|
261
|
+
if line.startswith("@@"):
|
|
262
|
+
in_hunk = True
|
|
263
|
+
continue
|
|
264
|
+
if line.startswith("diff --git"):
|
|
265
|
+
in_hunk = False
|
|
266
|
+
continue
|
|
267
|
+
if in_hunk and line[:1] in ("+", "-", " ") and not line.startswith(("+++ ", "--- ")):
|
|
268
|
+
body.extend((tok, n) for tok in line[1:].split())
|
|
269
|
+
views.append(body)
|
|
270
|
+
return views
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def find_quote(files: tuple[TargetFile, ...], quote: str) -> tuple[str, int] | None:
|
|
274
|
+
"""Locate `quote` literally in the target. Returns (file name, first line) or None.
|
|
275
|
+
|
|
276
|
+
"Literally" means character by character, case included; the only normalization is that any run of whitespace
|
|
277
|
+
(spaces, tabs, line breaks) counts as one space, so a quote can span a line break of the original.
|
|
278
|
+
"""
|
|
279
|
+
q = " ".join(quote.split())
|
|
280
|
+
if not q:
|
|
281
|
+
return None
|
|
282
|
+
for f in files:
|
|
283
|
+
for view in _views(f):
|
|
284
|
+
if not view:
|
|
285
|
+
continue
|
|
286
|
+
text = " ".join(tok for tok, _ in view)
|
|
287
|
+
pos = text.find(q)
|
|
288
|
+
if pos < 0:
|
|
289
|
+
continue
|
|
290
|
+
starts, off = [], 0
|
|
291
|
+
for tok, _ in view:
|
|
292
|
+
starts.append(off)
|
|
293
|
+
off += len(tok) + 1
|
|
294
|
+
return f.name, view[bisect.bisect_right(starts, pos) - 1][1]
|
|
295
|
+
return None
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def check_ref(ref: str, root: Path) -> tuple[bool, str]:
|
|
299
|
+
"""Validate an evidence ref. `file:line` or `file:a-b` must exist under `root`; anything else is free text
|
|
300
|
+
(a command, a log excerpt) that the engine cannot check and therefore only requires to be non-empty.
|
|
301
|
+
Returns (ok, why) where `why` is an i18n key suffix when not ok."""
|
|
302
|
+
if not ref.strip():
|
|
303
|
+
return False, "why_empty"
|
|
304
|
+
m = _REF_RE.match(ref.strip())
|
|
305
|
+
if not m:
|
|
306
|
+
return True, ""
|
|
307
|
+
p = _inside(root, m.group("path"))
|
|
308
|
+
if p is None:
|
|
309
|
+
return False, "why_outside"
|
|
310
|
+
if not p.is_file():
|
|
311
|
+
return False, "why_not_found"
|
|
312
|
+
try:
|
|
313
|
+
n = len(_read(p, m.group("path")).splitlines())
|
|
314
|
+
except RedTeamError:
|
|
315
|
+
return False, "why_not_found"
|
|
316
|
+
a = int(m.group("a"))
|
|
317
|
+
b = int(m.group("b") or a)
|
|
318
|
+
if not 1 <= a <= b <= n:
|
|
319
|
+
return False, f"why_line:{n}"
|
|
320
|
+
return True, ""
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Markdown rendering of the red team report (meant to be pasted into a PR, an ADR or a review thread)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from .catalog import CATALOG, CLASSES
|
|
5
|
+
from .engine import TOP_N, Result
|
|
6
|
+
from .i18n import get_lang, t
|
|
7
|
+
from .model import Findings
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _c(s: str) -> str:
|
|
11
|
+
"""One table cell: no pipes, no newlines."""
|
|
12
|
+
return " ".join(str(s).split()).replace("|", "\\|")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _cls(class_id: str) -> str:
|
|
16
|
+
return CATALOG[class_id][get_lang()]["name"]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _plaus(a) -> str:
|
|
20
|
+
return str(a.plausibility) if a.plausibility == a.effective_plausibility else f"{a.plausibility}→{a.effective_plausibility}"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def markdown(f: Findings, res: Result) -> str:
|
|
24
|
+
L: list[str] = [f"# {t('h_title', title=f.title)}", ""]
|
|
25
|
+
L += [t("target_line", kind=f.kind, files=", ".join(f"`{x.name}`" for x in f.files)), ""]
|
|
26
|
+
|
|
27
|
+
n = res.status_counts()
|
|
28
|
+
L += [f"## {t('h_summary')}", "",
|
|
29
|
+
f"- {t('s_assumptions', n=len(res.assumptions), v=n['verified'], u=n['unverified'], c=n['contradicted'])}",
|
|
30
|
+
f"- {t('s_attacks', n=len(res.attacks))}",
|
|
31
|
+
f"- {t('s_severity', sev=res.worst_severity) if res.worst_severity else t('s_none_severity')}"]
|
|
32
|
+
if res.rejections:
|
|
33
|
+
L.append(f"- {t('s_rejected', n=len(res.rejections))}")
|
|
34
|
+
L += [f"- {t('not_probability')}", ""]
|
|
35
|
+
|
|
36
|
+
L += [f"## {t('h_top', n=TOP_N)}", ""]
|
|
37
|
+
if res.top:
|
|
38
|
+
L += [f"| {t('col_rank')} | {t('col_attack')} | {t('col_class')} | {t('col_assumption')} | {t('col_risk')} | "
|
|
39
|
+
f"{t('col_where')} | {t('col_check')} |", "|--:|---|---|---|---|---|---|"]
|
|
40
|
+
for a in res.top:
|
|
41
|
+
L.append(f"| {a.rank} | **{a.id}** {_c(a.text)} | {_cls(a.class_id)} | {a.assumption} "
|
|
42
|
+
f"({t('status_' + a.assumption_status)}) | {a.risk} ({a.severity}) | `{a.where}` | {_c(a.check)} |")
|
|
43
|
+
else:
|
|
44
|
+
L.append(f"- {t('s_none_severity')}")
|
|
45
|
+
L.append("")
|
|
46
|
+
|
|
47
|
+
L += [f"## {t('h_matrix')}", "",
|
|
48
|
+
f"| {t('col_assumption')} | {t('col_status')} | " + " | ".join(_cls(c) for c in CLASSES) + f" | {t('col_evidence')} |",
|
|
49
|
+
"|---|---|" + "|".join(":-:" for _ in CLASSES) + "|---|"]
|
|
50
|
+
for a in res.assumptions:
|
|
51
|
+
cells = " | ".join(", ".join(a.attacks_by_class[c]) or "·" for c in CLASSES)
|
|
52
|
+
ev = "; ".join(f"`{r}`" for r, _ in a.evidence) or "—"
|
|
53
|
+
L.append(f"| **{a.id}** {_c(a.text)} (`{a.where}`) | {t('status_' + a.status)} | {cells} | {ev} |")
|
|
54
|
+
L.append("")
|
|
55
|
+
for a in res.assumptions:
|
|
56
|
+
if a.evidence:
|
|
57
|
+
L += [f"- **{a.id}** ({t('status_' + a.status)}): " + " ".join(f"`{r}` — {_c(o)}" for r, o in a.evidence)]
|
|
58
|
+
if any(a.evidence for a in res.assumptions):
|
|
59
|
+
L.append("")
|
|
60
|
+
|
|
61
|
+
L += [f"## {t('h_verify')}", ""]
|
|
62
|
+
if res.verify_next:
|
|
63
|
+
L += [f"- {t('verify_line', aid=v.assumption, text=_c(v.text), risk=v.max_risk, check=_c(v.check) or '—')}"
|
|
64
|
+
for v in res.verify_next]
|
|
65
|
+
else:
|
|
66
|
+
L.append(f"- {t('verify_none')}")
|
|
67
|
+
L.append("")
|
|
68
|
+
|
|
69
|
+
L += [f"## {t('h_attacks')}", ""]
|
|
70
|
+
if res.attacks:
|
|
71
|
+
L += [f"| {t('col_rank')} | {t('col_id')} | {t('col_class')} | {t('col_assumption')} | {t('col_impact')} | "
|
|
72
|
+
f"{t('col_plaus')} | {t('col_risk')} | {t('col_sev')} |", "|--:|---|---|---|--:|--:|--:|---|"]
|
|
73
|
+
for a in res.attacks:
|
|
74
|
+
L.append(f"| {a.rank} | {a.id} | {_cls(a.class_id)} | {a.assumption} | {a.impact} | {_plaus(a)} | {a.risk} | {a.severity} |")
|
|
75
|
+
L.append("")
|
|
76
|
+
for a in res.attacks:
|
|
77
|
+
if a.plausibility != a.effective_plausibility:
|
|
78
|
+
L.append(f"- **{a.id}**: " + t("plaus_note", p=a.plausibility, e=a.effective_plausibility,
|
|
79
|
+
status=t("status_" + a.assumption_status)))
|
|
80
|
+
L.append("")
|
|
81
|
+
else:
|
|
82
|
+
L += [f"- {t('s_none_severity')}", ""]
|
|
83
|
+
|
|
84
|
+
L += [f"## {t('h_coverage')}", ""]
|
|
85
|
+
for c in res.coverage:
|
|
86
|
+
if c.attack_ids:
|
|
87
|
+
state = t("cov_attacks", n=len(c.attack_ids), ids=", ".join(c.attack_ids))
|
|
88
|
+
elif c.skipped_reason:
|
|
89
|
+
state = t("cov_skipped", reason=_c(c.skipped_reason))
|
|
90
|
+
else:
|
|
91
|
+
state = f"**{t('cov_uncovered')}**"
|
|
92
|
+
L.append(f"- {_cls(c.class_id)}: {state}")
|
|
93
|
+
L.append("")
|
|
94
|
+
|
|
95
|
+
if res.rejections:
|
|
96
|
+
L += [f"## {t('h_rejected')}", "", f"| {t('col_kind')} | {t('col_id')} | {t('col_reason')} |", "|---|---|---|"]
|
|
97
|
+
L += [f"| {t('kind_' + r.kind)} | {r.id} | {_c(r.detail)} |" for r in res.rejections]
|
|
98
|
+
L.append("")
|
|
99
|
+
|
|
100
|
+
if res.warnings:
|
|
101
|
+
L += [f"## {t('h_warnings')}", ""] + [f"- {w}" for w in res.warnings] + [""]
|
|
102
|
+
L += ["---", t("footer"), ""]
|
|
103
|
+
return "\n".join(L)
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Diseño: enviar notificaciones desde un consumidor de streams (EJEMPLO SINTÉTICO)
|
|
2
|
+
|
|
3
|
+
Estado: propuesto. Responsable: equipo de plataforma.
|
|
4
|
+
|
|
5
|
+
## Contexto
|
|
6
|
+
|
|
7
|
+
Las notificaciones (correo y push) se envían hoy con un cron que recorre la tabla `notifications` cada minuto.
|
|
8
|
+
En hora punta el recorrido tarda 40 segundos y algunas notificaciones salen tarde.
|
|
9
|
+
|
|
10
|
+
## Propuesta
|
|
11
|
+
|
|
12
|
+
1. La API escribe cada notificación en la tabla `notifications` y, en la misma petición, publica su id en un Redis Stream llamado `notify`.
|
|
13
|
+
2. Un grupo de 4 consumidores lee el stream mediante un consumer group, llama al proveedor de correo y marca la fila como `sent`.
|
|
14
|
+
3. Cada consumidor confirma el mensaje (ack) apenas lo lee, de modo que una llamada lenta al proveedor nunca bloquea al grupo.
|
|
15
|
+
4. El cron se elimina en el mismo despliegue.
|
|
16
|
+
|
|
17
|
+
## Supuestos
|
|
18
|
+
|
|
19
|
+
- Redis casi siempre está disponible cuando la API publica; si no lo está, la notificación queda en la tabla y se enviará más tarde.
|
|
20
|
+
- El proveedor de correo acepta como máximo un mensaje por segundo por consumidor, y con 4 consumidores nos quedamos por debajo.
|
|
21
|
+
- Las notificaciones rara vez se duplican, así que los consumidores no necesitan ser idempotentes.
|
|
22
|
+
- La carga en hora punta seguirá por debajo de 200 notificaciones por minuto.
|
|
23
|
+
|
|
24
|
+
## Despliegue
|
|
25
|
+
|
|
26
|
+
El grupo de consumidores se activa detrás de un flag. Cuando el flag esté activo para todos los usuarios, se elimina el cron
|
|
27
|
+
y su código, y la columna antigua `notifications.sent_at` se borra en la siguiente migración.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Design: send notifications from a stream consumer (SYNTHETIC EXAMPLE)
|
|
2
|
+
|
|
3
|
+
Status: proposed. Owner: platform team.
|
|
4
|
+
|
|
5
|
+
## Context
|
|
6
|
+
|
|
7
|
+
Notifications (email and push) are sent today by a cron job that scans the `notifications` table every minute.
|
|
8
|
+
At peak the scan takes 40 seconds and some notifications go out late.
|
|
9
|
+
|
|
10
|
+
## Proposal
|
|
11
|
+
|
|
12
|
+
1. The API writes each notification to the `notifications` table and, in the same request, publishes its id to a Redis Stream called `notify`.
|
|
13
|
+
2. A pool of 4 consumers reads the stream through a consumer group, calls the email provider and marks the row as `sent`.
|
|
14
|
+
3. Each consumer acknowledges the message as soon as it is read, so a slow provider call never blocks the group.
|
|
15
|
+
4. The cron job is deleted in the same release.
|
|
16
|
+
|
|
17
|
+
## Assumptions
|
|
18
|
+
|
|
19
|
+
- Redis is almost always available when the API publishes; if it is not, the notification stays in the table and will be picked up later.
|
|
20
|
+
- The email provider accepts at most one message per second per consumer, and 4 consumers stay under that.
|
|
21
|
+
- Notifications are rarely duplicated, so consumers do not need to be idempotent.
|
|
22
|
+
- Peak load will stay under 200 notifications per minute.
|
|
23
|
+
|
|
24
|
+
## Rollout
|
|
25
|
+
|
|
26
|
+
The consumer pool ships behind a flag. Once the flag is on for all users, the cron job and its code are removed
|
|
27
|
+
and the old `notifications.sent_at` column is dropped in the next migration.
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schema": "clarent.redteam/1",
|
|
3
|
+
"title": "Notificaciones desde un consumidor de streams (EJEMPLO SINTÉTICO)",
|
|
4
|
+
"root": ".",
|
|
5
|
+
"target": { "kind": "design", "files": ["design.es.md"] },
|
|
6
|
+
"assumptions": [
|
|
7
|
+
{
|
|
8
|
+
"id": "A1",
|
|
9
|
+
"text": "Si Redis está caído cuando la API publica, la notificación no se pierde: se envía después desde la tabla.",
|
|
10
|
+
"quote": "si no lo está, la notificación queda en la tabla y se enviará más tarde",
|
|
11
|
+
"status": "contradicted",
|
|
12
|
+
"evidence": [
|
|
13
|
+
{ "ref": "design.es.md:15", "observation": "El paso 4 elimina el cron, que es el único lector de la tabla, así que nada recoge la fila después." }
|
|
14
|
+
]
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
"id": "A2",
|
|
18
|
+
"text": "El límite del proveedor se aplica por consumidor, así que añadir consumidores añade capacidad.",
|
|
19
|
+
"quote": "El proveedor de correo acepta como máximo un mensaje por segundo por consumidor",
|
|
20
|
+
"status": "unverified",
|
|
21
|
+
"check": "Leer la documentación de límites del proveedor y enviar una ráfaga de 50 mensajes desde dos consumidores que comparten una cuenta sandbox."
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
"id": "A3",
|
|
25
|
+
"text": "Las notificaciones duplicadas son raras, así que los consumidores pueden prescindir de la idempotencia.",
|
|
26
|
+
"quote": "Las notificaciones rara vez se duplican, así que los consumidores no necesitan ser idempotentes",
|
|
27
|
+
"status": "unverified",
|
|
28
|
+
"check": "Contar los ids de notificación publicados más de una vez en los últimos 30 días (agrupar el log de publicación por id, quedarse con count > 1)."
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
"id": "A4",
|
|
32
|
+
"text": "La carga se mantiene por debajo de 200 notificaciones por minuto.",
|
|
33
|
+
"quote": "La carga en hora punta seguirá por debajo de 200 notificaciones por minuto",
|
|
34
|
+
"status": "verified",
|
|
35
|
+
"evidence": [
|
|
36
|
+
{
|
|
37
|
+
"ref": "psql -c \"select max(n) from (select count(*) n from notifications group by date_trunc('minute', created_at)) m\"",
|
|
38
|
+
"observation": "máximo de 118 por minuto en los últimos 30 días (resultado sintético de este ejemplo; no dice nada sobre campañas)"
|
|
39
|
+
}
|
|
40
|
+
]
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
"id": "A5",
|
|
44
|
+
"text": "Apagar el flag es un rollback seguro.",
|
|
45
|
+
"quote": "El grupo de consumidores se activa detrás de un flag",
|
|
46
|
+
"status": "contradicted",
|
|
47
|
+
"evidence": [
|
|
48
|
+
{ "ref": "design.es.md:26-27", "observation": "Cuando el flag está activo para todos se elimina el cron y su código y se borra sent_at, así que apagar el flag no restaura nada." }
|
|
49
|
+
]
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
"id": "A6",
|
|
53
|
+
"text": "Un mensaje confirmado al leerlo no puede perderse.",
|
|
54
|
+
"quote": "Cada consumidor confirma el mensaje (ack) apenas lo lee",
|
|
55
|
+
"status": "unverified",
|
|
56
|
+
"check": "En staging, matar con kill -9 a un consumidor entre la lectura y la llamada al proveedor y contar las notificaciones que nunca se enviaron."
|
|
57
|
+
}
|
|
58
|
+
],
|
|
59
|
+
"attacks": [
|
|
60
|
+
{
|
|
61
|
+
"id": "X1",
|
|
62
|
+
"class": "failure-modes",
|
|
63
|
+
"assumption": "A1",
|
|
64
|
+
"quote": "la notificación queda en la tabla y se enviará más tarde",
|
|
65
|
+
"attack": "Si Redis está caído cuando la API publica, la fila queda en la tabla pero nada la lee cuando el cron desaparece: esas notificaciones no se envían nunca y nadie se entera.",
|
|
66
|
+
"impact": 4,
|
|
67
|
+
"plausibility": 3,
|
|
68
|
+
"check": "Detener Redis en staging, crear 20 notificaciones, reiniciar Redis y contar cuántas se envían."
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
"id": "X2",
|
|
72
|
+
"class": "failure-modes",
|
|
73
|
+
"assumption": "A6",
|
|
74
|
+
"quote": "confirma el mensaje (ack) apenas lo lee",
|
|
75
|
+
"attack": "Un consumidor que se cae después de leer y antes de que responda el proveedor pierde la notificación: confirmar al leer da entrega como máximo una vez, y la fila queda pendiente para siempre.",
|
|
76
|
+
"impact": 4,
|
|
77
|
+
"plausibility": 4,
|
|
78
|
+
"check": "En staging, matar con kill -9 a un consumidor entre la lectura y la llamada al proveedor; contar las filas aún pendientes tras 10 minutos."
|
|
79
|
+
},
|
|
80
|
+
{
|
|
81
|
+
"id": "X3",
|
|
82
|
+
"class": "reversibility",
|
|
83
|
+
"assumption": "A5",
|
|
84
|
+
"quote": "se elimina el cron y su código",
|
|
85
|
+
"attack": "Tras el despliegue no hay vuelta atrás: el flag no puede traer de vuelta el cron ni la columna sent_at, así que una mala versión solo se corrige publicando otra mientras se pierden notificaciones.",
|
|
86
|
+
"impact": 5,
|
|
87
|
+
"plausibility": 3,
|
|
88
|
+
"check": "Aplicar la migración en staging, intentar volver a la versión anterior y enviar una notificación."
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
"id": "X4",
|
|
92
|
+
"class": "dependency",
|
|
93
|
+
"assumption": "A2",
|
|
94
|
+
"quote": "acepta como máximo un mensaje por segundo por consumidor",
|
|
95
|
+
"attack": "Si el límite del proveedor se aplica por cuenta y no por consumidor, los 4 consumidores lo comparten, y los envíos limitados que ya se habían confirmado se descartan.",
|
|
96
|
+
"impact": 3,
|
|
97
|
+
"plausibility": 3,
|
|
98
|
+
"check": "Preguntar al proveedor (o leer su documentación) si el límite es por clave de API o por conexión."
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
"id": "X5",
|
|
102
|
+
"class": "abuse",
|
|
103
|
+
"assumption": "A3",
|
|
104
|
+
"quote": "publica su id en un Redis Stream llamado `notify`",
|
|
105
|
+
"attack": "Un cliente que repite una petición (un formulario de recuperación de contraseña, un bucle de reintentos) crea una notificación por petición; sin límite por usuario el stream se llena de duplicados y retrasa a todos, justo lo que el supuesto dice que no ocurre.",
|
|
106
|
+
"impact": 3,
|
|
107
|
+
"plausibility": 3,
|
|
108
|
+
"check": "Enviar 1.000 solicitudes de recuperación para una misma dirección en staging y medir el retraso de una notificación ajena."
|
|
109
|
+
},
|
|
110
|
+
{
|
|
111
|
+
"id": "X6",
|
|
112
|
+
"class": "scale",
|
|
113
|
+
"assumption": "A4",
|
|
114
|
+
"quote": "La carga en hora punta seguirá por debajo de 200 notificaciones por minuto",
|
|
115
|
+
"attack": "Una campaña de marketing de 50.000 notificaciones entra de golpe al stream; 4 consumidores a un mensaje por segundo tardan unas 3,5 horas en vaciarlo y los correos transaccionales esperan detrás.",
|
|
116
|
+
"impact": 4,
|
|
117
|
+
"plausibility": 4,
|
|
118
|
+
"check": "Calcular N / (consumidores x tasa) para la mayor campaña del trimestre pasado y probar una ráfaga de 50.000 mensajes en staging."
|
|
119
|
+
},
|
|
120
|
+
{
|
|
121
|
+
"id": "X7",
|
|
122
|
+
"class": "key-assumptions",
|
|
123
|
+
"assumption": "A3",
|
|
124
|
+
"quote": "así que los consumidores no necesitan ser idempotentes",
|
|
125
|
+
"attack": "La API publica dentro de la petición, así que cualquier reintento del cliente o del balanceador publica dos veces. Los duplicados vienen del publicador, no de la rareza de los eventos, y un consumidor no idempotente envía dos correos.",
|
|
126
|
+
"impact": 2,
|
|
127
|
+
"plausibility": 4,
|
|
128
|
+
"check": "Contar los ids de notificación publicados más de una vez en los últimos 30 días."
|
|
129
|
+
}
|
|
130
|
+
],
|
|
131
|
+
"skipped_classes": []
|
|
132
|
+
}
|