Go-live prep: link API, adopt shadow incidents, comments stay on Thor's ticket #12

Merged
jared merged 2 commits from go-live-prep into main 2026-11-27 10:36:16 -05:00
13 changed files with 157 additions and 8 deletions

No files matched your search

+2 -1
View File
@@ -103,7 +103,8 @@ class FakeStore:
def incident_ticket(self, key):
self._check('incident_ticket')
ids = [a['ticket_id'] for a in self.actions if a['incident_key'] == key and a.get('ticket_id')]
ids = [a['ticket_id'] for a in self.actions if a['incident_key'] == key and a.get('ticket_id')
and a['kind'] in ('open', 'escalate', 'refresh')]
return ids[-1] if ids else None
def save_observation(self, f, now):
+12
View File
@@ -214,6 +214,18 @@ def test_a_higher_cause_found_later_absorbs_pending_and_comments_on_opened():
assert e.incidents['monitor-01:reboot'].facts['root_cause'] == 'cluster:partition'
def test_a_live_higher_cause_links_the_lower_ticket_it_explains():
s = Settings()
s.checks = {'reboots': 'live', 'cluster': 'live'}
e = Engine(s, HostRegistry(), {}, lambda *a, **k: None)
e.process([F('reboot', 'monitor-01', LAYER_HOST_DOWN, cluster_effect=True, check='reboots')], T0 - 200)
e.process([], T0 + 200)
acts = e.process([F('partition', 'cluster', 60, check='cluster')], T0 + 250)
assert [(a.kind, a.incident_key) for a in acts] == [
('root_cause', 'monitor-01:reboot'), ('link', 'cluster:partition')]
assert acts[1].payload == {'from_key': 'monitor-01:reboot'} and acts[1].mode == 'live'
def test_known_condition_sends_a_note_to_its_ticket():
e, _ = engine()
e.known = [{'kind': 'reboot', 'subject': 'compute-storage-02', 'ticket_id': 693930698, 'reason': 'DIMM'}]
+27
View File
@@ -212,6 +212,33 @@ def test_tinker_comment_and_reads():
assert TinkerClient('', '').open_tickets() is None
def test_tinker_link_treats_existing_and_gone_as_done():
url = 'https://t/api/ticket_link_api.php'
sess = (FakeSession().add('POST', url, FakeResponse(200, {'success': True}), FakeResponse(409, {}),
FakeResponse(404, {}), requests.ConnectionError('x'), FakeResponse(403, {})))
t = TinkerClient(TINKER, 'k', session=sess)
assert t.link('615797777', '900000001') is True
assert sess.requests[0]['json'] == {'ticket_id': '615797777', 'other_ticket_id': '900000001',
'relation': 'relates_to'}
assert t.link('1', '2') is True # already linked
assert t.link('1', '2') is True # a ticket was deleted
assert t.link('1', '2') is False # network: retry later
assert t.link('1', '2') is False and t.writes_denied
assert t.link('1', '2') is False # no more writes this run
assert TinkerClient('', '').link('1', '2') is False
def test_tinker_create_reads_every_contract_action():
"""tinker_tickets#124 replies: each names the ticket Thor's incident now lives on."""
for action, extra in (('reopened', {}), ('recurrence_noted', {}), ('updated', {}),
('new_recurrence', {'previous_ticket_id': '100'})):
reply = dict(success=True, ticket_id='200', action=action, **extra)
sess = FakeSession().add('POST', TINKER, FakeResponse(200, reply))
r = TinkerClient(TINKER, 'k', session=sess).create(title='t', description='d', priority=3, category='c',
ticket_type='Issue', dedup_key='host:h:oom')
assert (r.ticket_id, r.action, r.ok) == ('200', action, True)
def test_backoff():
assert backoff_s(1) == 120
assert backoff_s(3) == 480
+5 -1
View File
@@ -88,9 +88,13 @@ def test_incidents_actions_observations(db):
s.mark_action_sent(live, '615797777', t + 200)
assert s.incident_ticket(inc['key']) == '615797777'
assert s.incident_ticket('other') is None
attach = s.add_action({'incident_key': inc['key'], 'kind': 'attach', 'created': t + 300, 'mode': 'live',
'payload': {'ticket_id': '673679581', 'comment': 'Root cause'}})
s.mark_action_sent(attach, '673679581', t + 300)
assert s.incident_ticket(inc['key']) == '615797777' # never another app's ticket
s.mark_action_failed(shadow, 'x', 30, None)
recent = s.recent_actions(t - 1)
assert {a['id'] for a in recent} == {shadow, live}
assert {a['id'] for a in recent} == {shadow, live, attach}
f = {'key': 'host:storage-01:scrape', 'kind': 'scrape', 'subject': 'storage-01', 'role': 'symptom',
'start': t + 10, 'end': t + 20, 'summary': 'slow'}
s.save_observation(f, t + 20)
+12
View File
@@ -132,6 +132,18 @@ def test_live_mode_actions_and_catch_up_open_at_once():
assert 'Seen after the fact' in acts[0].payload['description']
def test_open_shadow_incident_gets_its_ticket_when_the_check_goes_live():
e, _ = engine()
e.process([cause(T0)], T0 + 30)
assert kinds(e.process([], T0 + 150)) == ['open'] # shadow
e.settings.checks = {'memory': 'live'}
acts = e.process([cause(T0 + 200)], T0 + 210)
assert [(a.kind, a.mode) for a in acts] == [('open', 'live')]
assert 'adopt' not in e.incidents['host:compute-storage-01:oom'].facts
acts = e.process([cause(T0 + 300)], T0 + 330)
assert 'open' not in kinds(acts) # adopted once, then normal traffic
def test_refresh_when_summary_changes_rate_limited_and_once_more_when_clearing():
class Flat(Rules):
def priority(self, inc):
+2 -1
View File
@@ -140,8 +140,9 @@ def test_attach_and_detach(app):
is_err, text = call(app, 'attach_ticket', {'key': 'host:compute-storage-01:oom', 'ticket_id': '615797777'})
assert not is_err and 'shadow' in text
assert store.links[0]['added_by'] == 'jared'
a = store.actions[-1]
a, link = store.actions[-2:]
assert a['kind'] == 'attach' and a['status'] == 'shadow' and a['payload']['ticket_id'] == '615797777'
assert link['kind'] == 'link' and link['payload'] == {'ticket_id': '615797777'}
assert call(app, 'attach_ticket', {'key': 'maintenance:gandalf:2', 'ticket_id': '1'})[0]
assert call(app, 'attach_ticket', {'key': 'host:compute-storage-01:oom', 'ticket_id': 'x'})[0]
assert call(app, 'attach_ticket', {'key': 'nope', 'ticket_id': '1'})[0]
+38 -1
View File
@@ -13,7 +13,7 @@ class FakeTinker:
def __init__(self, ok=True):
self.ok = ok
self.created, self.comments = [], []
self.created, self.comments, self.links = [], [], []
def create(self, **kw):
self.created.append(kw)
@@ -23,6 +23,10 @@ class FakeTinker:
self.comments.append((ticket_id, text))
return self.ok
def link(self, ticket_id, other, relation='relates_to'):
self.links.append((ticket_id, other, relation))
return self.ok
def live(store, kind, key='host:h:oom', **payload):
base = {'title': 't', 'description': 'd', 'priority': 2, 'category': 'Software', 'type': 'Issue',
@@ -64,6 +68,39 @@ def test_outbox_comment_waits_for_its_ticket_and_unknown_kinds_fail():
assert 'unknown action' in store.actions[bad - 1]['error']
def test_comments_never_follow_an_attached_ticket():
"""attach and link rows record another ticket's number; Thor's comments stay on its own."""
store, tinker = FakeStore(), FakeTinker()
live(store, 'open')
Outbox(store, tinker).flush(200.0)
store.add_action({'incident_key': 'host:h:oom', 'kind': 'attach', 'created': 210.0, 'mode': 'live',
'payload': {'ticket_id': '615797777', 'comment': 'Root cause'}})
store.add_action({'incident_key': 'host:h:oom', 'kind': 'link', 'created': 210.0, 'mode': 'live',
'payload': {'ticket_id': '615797777'}})
live(store, 'also_seen', comment='also')
assert Outbox(store, tinker).flush(300.0) == 3
assert tinker.comments == [('615797777', 'Root cause'), ('555', 'also')]
assert tinker.links == [('615797777', '555', 'relates_to')]
assert store.incident_ticket('host:h:oom') == '555'
def test_link_waits_for_both_tickets():
store, tinker = FakeStore(), FakeTinker()
aid = store.add_action({'incident_key': 'cluster:corosync:partition', 'kind': 'link', 'created': 100.0,
'mode': 'live', 'payload': {'from_key': 'host:monitor-01:reboot'}})
Outbox(store, tinker).flush(200.0)
assert 'waiting for both tickets' in store.actions[aid - 1]['error'] and tinker.links == []
live(store, 'open', key='cluster:corosync:partition')
live(store, 'open', key='host:monitor-01:reboot')
store.actions[aid - 1]['next_attempt_at'] = 0
tinker_ids = iter(['900', '901'])
tinker.create = lambda **kw: TicketResult(next(tinker_ids), 'created', ok=True)
Outbox(store, tinker).flush(400.0) # opens sent; the older link row went first
store.actions[aid - 1]['next_attempt_at'] = 0
Outbox(store, tinker).flush(500.0)
assert tinker.links == [('901', '900', 'relates_to')]
def test_outbox_does_nothing_unconfigured_or_without_db():
store = FakeStore()
t = FakeTinker()
+29
View File
@@ -41,6 +41,7 @@ class TinkerClient:
# Tinker serves its other API scripts under api/ beside create_ticket_api.php
self.comment_url = urljoin(url, 'api/ticket_comment_api.php') if url else ''
self.read_url = urljoin(url, 'api/tickets_api.php') if url else ''
self.link_url = urljoin(url, 'api/ticket_link_api.php') if url else ''
self.writes_denied = False
@property
@@ -99,6 +100,34 @@ class TinkerClient:
logger.error('Comment on #%s failed: %s', ticket_id, e)
return False
def link(self, ticket_id: str, other_ticket_id: str, relation: str = 'relates_to') -> bool:
"""Link two tickets (tinker_tickets#123): "ticket_id <relation> other_ticket_id".
False means try again later. An existing link (409) or a deleted ticket (404) counts as
done, so a retry after a lost reply never loops.
"""
if not self.configured or self.writes_denied:
return False
try:
resp = self.session.post(
self.link_url, headers=self._headers(), timeout=self.timeout,
json={'ticket_id': str(ticket_id), 'other_ticket_id': str(other_ticket_id), 'relation': relation})
if resp.status_code in (401, 403):
self.writes_denied = True
logger.error('Tinker refused a link #%s -> #%s (HTTP %s)', ticket_id, other_ticket_id,
resp.status_code)
return False
if resp.status_code == 409:
return True
if resp.status_code == 404:
logger.warning('Link #%s -> #%s: a ticket no longer exists; dropping it', ticket_id, other_ticket_id)
return True
resp.raise_for_status()
return bool(resp.json().get('success'))
except (requests.RequestException, ValueError) as e:
logger.error('Link #%s -> #%s failed: %s', ticket_id, other_ticket_id, e)
return False
def open_tickets(self) -> Optional[Dict[str, Dict]]:
"""{ticket_id: {title, status, priority}} for every ticket not closed, or None if unknown."""
if not self.configured:
+4 -1
View File
@@ -367,8 +367,11 @@ class Store:
(status, attempts, to_dt(retry_at), error[:2000], action_id))
def incident_ticket(self, incident_key: str) -> Optional[str]:
# Only Thor's own creates name its ticket: attach, link and known_note rows record
# another ticket's number, and comments must never follow those.
rows = self.db.query("""SELECT ticket_id FROM actions WHERE incident_key=%s AND ticket_id IS NOT NULL
ORDER BY id DESC LIMIT 1""", (incident_key,))
AND kind IN ('open', 'escalate', 'refresh') ORDER BY id DESC LIMIT 1""",
(incident_key,))
return rows[0]['ticket_id'] if rows else None
def recent_actions(self, since: float, limit: int = 200) -> List[Dict[str, Any]]:
+13 -1
View File
@@ -183,6 +183,9 @@ class Engine:
low.state, low.cleared_at = CLEARED, now
self._action(actions, low, 'root_cause', now,
comment=ticket_text.root_cause_comment(top), root_cause=top.key)
if low.mode == 'live':
# Only a live lower incident has a ticket to link from.
self._action(actions, top, 'link', now, from_key=low.key)
self.write('save_incident', low.to_dict(), now)
@staticmethod
@@ -207,7 +210,12 @@ class Engine:
inc.state, inc.pending_since, inc.cleared_at = PENDING, now, None
inc.first_seen, inc.symptoms, inc.priority = f.start, {}, f.priority
inc.facts.pop('sent_priority', None)
inc.mode = self.settings.check_mode(f.check)
mode = self.settings.check_mode(f.check)
if mode == 'live' and inc.mode != 'live' and inc.state == OPEN and inc.ticket and not inc.known_ticket:
# Its check went live while it was open in shadow: it has no ticket yet, so open one
# now or every later comment would wait forever for it.
inc.facts['adopt'] = True
inc.mode = mode
inc.first_seen = min(inc.first_seen, f.start)
inc.last_seen = max(inc.last_seen, f.end)
inc.facts.update(f.facts)
@@ -243,6 +251,10 @@ class Engine:
if now - self._last_activity(inc) >= CLEAR_AFTER_S:
inc.state, inc.cleared_at = CLEARED, now
return
if inc.facts.pop('adopt', False):
self._action(actions, inc, 'open', now, **self._open_payload(inc))
inc.facts['sent_priority'] = inc.priority
self._sent(inc, now)
sent = inc.facts.get('sent_priority', before)
if inc.priority < sent:
reason = inc.facts.get('escalation_reason') or 'The incident got worse.'
+1 -1
View File
@@ -95,7 +95,7 @@ class Incident:
class Action:
"""Something to tell Tinker. In shadow mode it is recorded and never sent."""
incident_key: str
kind: str # 'open', 'escalate', 'refresh', 'also_seen', 'cleared'
kind: str # 'open', 'escalate', 'refresh', 'also_seen', 'cleared', 'root_cause', 'link', ...
created: float
mode: str # 'shadow' or 'live'
payload: Dict[str, Any] = field(default_factory=dict)
+9 -1
View File
@@ -1,6 +1,5 @@
"""Sends live ticket actions to Tinker, with retries. Shadow actions never get here.
No check is live before tinker_tickets#123 ships (thor#1), so in phase 1 this mostly waits.
An action that can't be sent stays pending and is retried with backoff; Tinker being down
(it lives on CT 132 and the same MariaDB) never loses an action.
"""
@@ -57,6 +56,15 @@ class Outbox:
if a['kind'] in ('known_note', 'attach'):
ok = self.tinker.comment(p['ticket_id'], p['comment'])
return ok, p['ticket_id'], '' if ok else 'comment failed'
if a['kind'] == 'link':
# Another ticket (attached by an operator, or Thor's own lower incident) relates to
# this incident's ticket. Both must exist first.
target = self.store.incident_ticket(a['incident_key'])
source = p.get('ticket_id') or (self.store.incident_ticket(p['from_key']) if p.get('from_key') else None)
if not target or not source:
return False, None, 'waiting for both tickets to exist before linking'
ok = self.tinker.link(source, target, 'relates_to')
return ok, source, '' if ok else 'link failed'
if a['kind'] in COMMENT_KINDS:
ticket_id = self.store.incident_ticket(a['incident_key'])
if not ticket_id:
+3
View File
@@ -194,6 +194,9 @@ def t_attach(args, user):
'payload': {'ticket_id': ticket, 'comment': (
f'**Root cause: {inc.get("summary")}** (`{key}`), tracked by Thor. '
f'Attached by {user["name"]}. Close this ticket when you are happy it is covered.')}})
# And a relates_to link once Thor's own ticket exists (the outbox waits for it).
store.add_action({'incident_key': key, 'kind': 'link', 'created': _now(), 'mode': inc.get('mode', 'shadow'),
'payload': {'ticket_id': ticket}})
sent = 'recorded (shadow: nothing sent)' if inc.get('mode') != 'live' else 'queued: Thor comments on it'
return {'incident': key, 'ticket_id': ticket, 'attached': True, 'tinker': sent}