@luanpdd/kit-mcp 1.8.1 → 1.10.0
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.
- package/CHANGELOG.md +86 -0
- package/README.md +97 -1
- package/gates/golden-signals-coverage.md +133 -0
- package/gates/obs-agents-mcp-supabase.md +86 -0
- package/gates/obs-skills-frontmatter.md +76 -0
- package/gates/omm-no-regression.md +83 -0
- package/gates/postmortem-template-required.md +127 -0
- package/gates/prr-checklist-coverage.md +128 -0
- package/gates/skill-must-include.md +21 -19
- package/kit/agents/burn-rate-forecaster.md +160 -0
- package/kit/agents/golden-signals-instrumenter.md +241 -0
- package/kit/agents/incident-investigator.md +245 -0
- package/kit/agents/observability-instrumenter.md +200 -0
- package/kit/agents/omm-auditor.md +251 -0
- package/kit/agents/postmortem-writer.md +282 -0
- package/kit/agents/prr-conductor.md +288 -0
- package/kit/agents/slo-engineer.md +224 -0
- package/kit/agents/supabase-architect.md +62 -0
- package/kit/agents/supabase-auth-bootstrapper.md +17 -0
- package/kit/agents/supabase-edge-fn-writer.md +124 -0
- package/kit/agents/supabase-migration-writer.md +98 -0
- package/kit/agents/supabase-realtime-implementer.md +23 -0
- package/kit/agents/supabase-rls-writer.md +17 -0
- package/kit/agents/supabase-storage-implementer.md +174 -0
- package/kit/agents/toil-auditor.md +277 -0
- package/kit/commands/auditar-marco.md +102 -1
- package/kit/commands/auditar-observabilidade.md +103 -0
- package/kit/commands/auditar-toil.md +129 -0
- package/kit/commands/burn-rate-status.md +140 -0
- package/kit/commands/concluir-marco.md +73 -1
- package/kit/commands/definir-slo.md +108 -0
- package/kit/commands/discutir-fase.md +26 -0
- package/kit/commands/forense.md +83 -1
- package/kit/commands/golden-signals.md +142 -0
- package/kit/commands/instrumentar-fase.md +200 -0
- package/kit/commands/investigar-producao.md +162 -0
- package/kit/commands/observabilidade.md +116 -0
- package/kit/commands/planejar-fase.md +20 -0
- package/kit/commands/postmortem.md +179 -0
- package/kit/commands/prr.md +205 -0
- package/kit/commands/risk-budget.md +220 -0
- package/kit/commands/sre.md +227 -0
- package/kit/commands/verificar-trabalho.md +26 -0
- package/kit/skills/_shared-observability/glossary.md +396 -0
- package/kit/skills/_shared-sre/glossary.md +573 -0
- package/kit/skills/blameless-postmortems/SKILL.md +340 -0
- package/kit/skills/burn-rate-alerting/SKILL.md +258 -0
- package/kit/skills/core-analysis-loop/SKILL.md +352 -0
- package/kit/skills/distributed-tracing/SKILL.md +362 -0
- package/kit/skills/eliminating-toil/SKILL.md +243 -0
- package/kit/skills/event-based-slos/SKILL.md +296 -0
- package/kit/skills/four-golden-signals/SKILL.md +297 -0
- package/kit/skills/observability-driven-development/SKILL.md +315 -0
- package/kit/skills/observability-maturity-model/SKILL.md +222 -0
- package/kit/skills/opentelemetry-standard/SKILL.md +351 -0
- package/kit/skills/production-readiness-review/SKILL.md +305 -0
- package/kit/skills/sre-risk-management/SKILL.md +221 -0
- package/kit/skills/structured-events/SKILL.md +265 -0
- package/kit/skills/telemetry-pipelines/SKILL.md +259 -0
- package/kit/skills/telemetry-sampling/SKILL.md +256 -0
- package/package.json +1 -1
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: distributed-tracing
|
|
3
|
+
description: Use ao instrumentar tracing — trace_id/span_id/parent_id, propagar W3C TraceContext via header traceparent, stitching além de RPCs (batch, lambda, queue).
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Observabilidade — Distributed Tracing
|
|
7
|
+
|
|
8
|
+
## Quando usar
|
|
9
|
+
|
|
10
|
+
LLM carrega esta skill ao instrumentar tracing distribuído ou stitching de spans. Trigger phrases:
|
|
11
|
+
|
|
12
|
+
- "distributed tracing", "traces", "spans"
|
|
13
|
+
- "propagar contexto entre serviços", "trace cross-service"
|
|
14
|
+
- "W3C TraceContext", "traceparent header"
|
|
15
|
+
- "trace_id span_id parent_span_id"
|
|
16
|
+
- "ligar lambda batch job ao trace"
|
|
17
|
+
- "stitching de eventos"
|
|
18
|
+
|
|
19
|
+
## Regras absolutas
|
|
20
|
+
|
|
21
|
+
- **trace_id é compartilhado** entre todos os spans de um único request distribuído. **NÃO** mude por hop.
|
|
22
|
+
- **span_id é único por span** — gere novo a cada `startSpan()`. 16 hex chars (8 bytes).
|
|
23
|
+
- **parent_span_id aponta para span pai** — null no root span. Define a árvore.
|
|
24
|
+
- **W3C TraceContext é o padrão** — header HTTP `traceparent: 00-{trace_id}-{span_id}-{flags}`. Adote sempre. B3 é fallback para legacy.
|
|
25
|
+
- **Propague ANTES de fazer call cross-service** — extrair contexto do request inbound, propagar no request outbound. Sem isso, trace quebra.
|
|
26
|
+
- **Stitching ≠ apenas RPC** — também batch jobs, queue messages, lambda invocations, S3 uploads. Carregue `traceparent` em metadata da queue, env var do lambda, header da Step Function.
|
|
27
|
+
- **Sample decision propaga** — bit `01` em flags de `traceparent` significa "sample=true". Decisão tomada no head propaga downstream.
|
|
28
|
+
- **Não invente trace_id** — sempre derive do contexto inbound ou gere via SDK (não `crypto.randomUUID()`).
|
|
29
|
+
- **Spans devem ter `kind`** — `SERVER` (handler de inbound), `CLIENT` (call outbound), `PRODUCER`/`CONSUMER` (queue), `INTERNAL` (subspan dentro do mesmo process).
|
|
30
|
+
|
|
31
|
+
## Patterns canônicos
|
|
32
|
+
|
|
33
|
+
### Pattern: extrair contexto inbound + propagar outbound (Node)
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
// PT-BR: handler HTTP — extrai traceparent do request inbound, propaga em call outbound
|
|
37
|
+
import { trace, context, propagation } from '@opentelemetry/api'
|
|
38
|
+
|
|
39
|
+
const tracer = trace.getTracer('orders-service')
|
|
40
|
+
|
|
41
|
+
export async function placeOrder(req: Request) {
|
|
42
|
+
// PT-BR: 1 — extrair contexto inbound do header traceparent
|
|
43
|
+
const inboundContext = propagation.extract(context.active(), req.headers)
|
|
44
|
+
|
|
45
|
+
return tracer.startActiveSpan(
|
|
46
|
+
'place_order',
|
|
47
|
+
{ kind: SpanKind.SERVER },
|
|
48
|
+
inboundContext,
|
|
49
|
+
async (span) => {
|
|
50
|
+
span.setAttribute('user.id', req.user.id)
|
|
51
|
+
|
|
52
|
+
// PT-BR: 2 — fazer call outbound — propagation injeta traceparent automaticamente
|
|
53
|
+
// se você usar fetch/grpc instrumentados (ver skill opentelemetry-standard)
|
|
54
|
+
const outboundHeaders: Record<string, string> = {}
|
|
55
|
+
propagation.inject(context.active(), outboundHeaders)
|
|
56
|
+
|
|
57
|
+
const inventoryRes = await fetch('http://inventory/check', {
|
|
58
|
+
headers: outboundHeaders, // PT-BR: traceparent injetado aqui
|
|
59
|
+
body: JSON.stringify({ items: req.items })
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
span.end()
|
|
63
|
+
return inventoryRes.json()
|
|
64
|
+
}
|
|
65
|
+
)
|
|
66
|
+
}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### Pattern: traceparent format
|
|
70
|
+
|
|
71
|
+
```text
|
|
72
|
+
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
|
|
73
|
+
^ ^ ^ ^
|
|
74
|
+
| | | |
|
|
75
|
+
version | flags (sampled bit)
|
|
76
|
+
trace_id (32 hex / 16 bytes) |
|
|
77
|
+
span_id (16 hex / 8 bytes)
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
```text
|
|
81
|
+
flags:
|
|
82
|
+
01 = sampled (decisão upstream: capture este trace)
|
|
83
|
+
00 = not sampled (decisão upstream: skip)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### Pattern: trace cross-service via Supabase Edge Function
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
// PT-BR: Edge Function recebe request → propaga para outro service
|
|
90
|
+
import { trace, context, propagation } from 'npm:@opentelemetry/api@1.9.0'
|
|
91
|
+
import { W3CTraceContextPropagator } from 'npm:@opentelemetry/core@1.27.0'
|
|
92
|
+
|
|
93
|
+
propagation.setGlobalPropagator(new W3CTraceContextPropagator())
|
|
94
|
+
|
|
95
|
+
const tracer = trace.getTracer('edge-orders')
|
|
96
|
+
|
|
97
|
+
Deno.serve(async (req) => {
|
|
98
|
+
// PT-BR: extrair traceparent inbound
|
|
99
|
+
const inboundCtx = propagation.extract(context.active(), {
|
|
100
|
+
traceparent: req.headers.get('traceparent') ?? '',
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
return tracer.startActiveSpan(
|
|
104
|
+
'edge_handler',
|
|
105
|
+
{ kind: 1 /* SERVER */ },
|
|
106
|
+
inboundCtx,
|
|
107
|
+
async (span) => {
|
|
108
|
+
span.setAttribute('endpoint', new URL(req.url).pathname)
|
|
109
|
+
|
|
110
|
+
// PT-BR: call outbound para Postgres via PostgREST — injeta traceparent
|
|
111
|
+
const outHeaders: Record<string, string> = {}
|
|
112
|
+
propagation.inject(context.active(), outHeaders)
|
|
113
|
+
|
|
114
|
+
const dbRes = await fetch(Deno.env.get('SUPABASE_URL') + '/rest/v1/orders', {
|
|
115
|
+
method: 'POST',
|
|
116
|
+
headers: {
|
|
117
|
+
...outHeaders,
|
|
118
|
+
'apikey': Deno.env.get('SUPABASE_ANON_KEY')!,
|
|
119
|
+
'content-type': 'application/json',
|
|
120
|
+
},
|
|
121
|
+
body: await req.text(),
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
span.setAttribute('db.status_code', dbRes.status)
|
|
125
|
+
span.end()
|
|
126
|
+
return dbRes
|
|
127
|
+
}
|
|
128
|
+
)
|
|
129
|
+
})
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
### Pattern: stitching além de RPC — queue message (não-RPC)
|
|
133
|
+
|
|
134
|
+
```ts
|
|
135
|
+
// PT-BR: producer — anexa traceparent ao payload da queue (pgmq, SQS, RabbitMQ)
|
|
136
|
+
import { trace, context, propagation } from '@opentelemetry/api'
|
|
137
|
+
|
|
138
|
+
const tracer = trace.getTracer('producer')
|
|
139
|
+
|
|
140
|
+
export async function enqueueEmail(emailJob: EmailJob) {
|
|
141
|
+
return tracer.startActiveSpan(
|
|
142
|
+
'enqueue_email',
|
|
143
|
+
{ kind: SpanKind.PRODUCER },
|
|
144
|
+
async (span) => {
|
|
145
|
+
span.setAttribute('queue.name', 'emails')
|
|
146
|
+
span.setAttribute('email.recipient', emailJob.to)
|
|
147
|
+
|
|
148
|
+
// PT-BR: serializar contexto no payload da mensagem
|
|
149
|
+
const carrier: Record<string, string> = {}
|
|
150
|
+
propagation.inject(context.active(), carrier)
|
|
151
|
+
|
|
152
|
+
await pgmqEnqueue('emails', {
|
|
153
|
+
...emailJob,
|
|
154
|
+
_trace_context: carrier, // PT-BR: viaja com o job
|
|
155
|
+
})
|
|
156
|
+
|
|
157
|
+
span.end()
|
|
158
|
+
}
|
|
159
|
+
)
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// PT-BR: consumer — extrai traceparent do payload, continua o trace
|
|
163
|
+
export async function processEmailJob(job: EmailJobWithContext) {
|
|
164
|
+
const inboundCtx = propagation.extract(
|
|
165
|
+
context.active(),
|
|
166
|
+
job._trace_context ?? {} // PT-BR: se vazio, novo trace
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
return tracer.startActiveSpan(
|
|
170
|
+
'process_email',
|
|
171
|
+
{ kind: SpanKind.CONSUMER },
|
|
172
|
+
inboundCtx,
|
|
173
|
+
async (span) => {
|
|
174
|
+
span.setAttribute('email.recipient', job.to)
|
|
175
|
+
// PT-BR: agora o span do worker faz parte do mesmo trace do producer
|
|
176
|
+
await sendEmail(job)
|
|
177
|
+
span.end()
|
|
178
|
+
}
|
|
179
|
+
)
|
|
180
|
+
}
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
### Pattern: stitching de batch job (não-RPC)
|
|
184
|
+
|
|
185
|
+
```ts
|
|
186
|
+
// PT-BR: cron job processa N items — 1 span por item, todos com mesmo trace_id
|
|
187
|
+
const tracer = trace.getTracer('billing-cron')
|
|
188
|
+
|
|
189
|
+
export async function dailyBillingJob() {
|
|
190
|
+
return tracer.startActiveSpan('daily_billing', async (rootSpan) => {
|
|
191
|
+
rootSpan.setAttribute('job.type', 'cron')
|
|
192
|
+
rootSpan.setAttribute('build_id', BUILD_ID)
|
|
193
|
+
|
|
194
|
+
const customers = await db.getCustomersDueForBilling()
|
|
195
|
+
rootSpan.setAttribute('customers.count', customers.length)
|
|
196
|
+
|
|
197
|
+
// PT-BR: cada customer vira span filho com mesmo trace_id
|
|
198
|
+
for (const customer of customers) {
|
|
199
|
+
await tracer.startActiveSpan(
|
|
200
|
+
'bill_customer',
|
|
201
|
+
{ kind: SpanKind.INTERNAL },
|
|
202
|
+
async (span) => {
|
|
203
|
+
span.setAttribute('customer.id', customer.id)
|
|
204
|
+
span.setAttribute('customer.tier', customer.tier)
|
|
205
|
+
try {
|
|
206
|
+
await chargeCustomer(customer)
|
|
207
|
+
span.setAttribute('result.success', true)
|
|
208
|
+
} catch (e) {
|
|
209
|
+
span.setAttribute('result.success', false)
|
|
210
|
+
span.setAttribute('error.type', classify(e))
|
|
211
|
+
} finally {
|
|
212
|
+
span.end()
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
)
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
rootSpan.end()
|
|
219
|
+
})
|
|
220
|
+
}
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
### Pattern: span kinds
|
|
224
|
+
|
|
225
|
+
| Kind | Quando usar | Exemplo |
|
|
226
|
+
|---|---|---|
|
|
227
|
+
| `SERVER` | Recebendo request inbound | Handler HTTP, gRPC server method |
|
|
228
|
+
| `CLIENT` | Fazendo call outbound | `fetch()`, gRPC client call, DB query |
|
|
229
|
+
| `PRODUCER` | Enviando msg para queue | `pgmq.enqueue()`, SQS publish |
|
|
230
|
+
| `CONSUMER` | Processando msg de queue | Worker recebendo job |
|
|
231
|
+
| `INTERNAL` | Subdivisão dentro do mesmo process | "json_parse", "validation_step" |
|
|
232
|
+
|
|
233
|
+
### Pattern: query traces — montar waterfall
|
|
234
|
+
|
|
235
|
+
```sql
|
|
236
|
+
-- PT-BR: pegar todos os spans de um trace em ordem cronológica
|
|
237
|
+
select
|
|
238
|
+
span_id,
|
|
239
|
+
parent_span_id,
|
|
240
|
+
span_name,
|
|
241
|
+
span_kind,
|
|
242
|
+
service_name,
|
|
243
|
+
duration_ms,
|
|
244
|
+
start_time
|
|
245
|
+
from observability.spans
|
|
246
|
+
where trace_id = '4bf92f3577b34da6a3ce929d0e0e4736'
|
|
247
|
+
order by start_time asc;
|
|
248
|
+
|
|
249
|
+
-- PT-BR: encontrar root span — parent_span_id IS NULL ou span sem parent no mesmo trace
|
|
250
|
+
select *
|
|
251
|
+
from observability.spans
|
|
252
|
+
where trace_id = '4bf92f3577b34da6a3ce929d0e0e4736'
|
|
253
|
+
and parent_span_id is null;
|
|
254
|
+
|
|
255
|
+
-- PT-BR: spans mais lentos cross-trace, último 1h
|
|
256
|
+
select
|
|
257
|
+
service_name,
|
|
258
|
+
span_name,
|
|
259
|
+
percentile_cont(0.99) within group (order by duration_ms) as p99,
|
|
260
|
+
count(*) as samples
|
|
261
|
+
from observability.spans
|
|
262
|
+
where start_time > now() - interval '1 hour'
|
|
263
|
+
group by service_name, span_name
|
|
264
|
+
having count(*) > 100
|
|
265
|
+
order by p99 desc
|
|
266
|
+
limit 20;
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
## Anti-patterns
|
|
270
|
+
|
|
271
|
+
### ANTI: gerar trace_id por hop
|
|
272
|
+
|
|
273
|
+
```ts
|
|
274
|
+
// PT-BR: BAD — quebra a cadeia, cada service vê trace diferente
|
|
275
|
+
const traceId = crypto.randomUUID().replace(/-/g, '').slice(0, 32)
|
|
276
|
+
|
|
277
|
+
// PT-BR: GOOD — extrair do header inbound; deixar SDK gerar root
|
|
278
|
+
const inboundCtx = propagation.extract(context.active(), req.headers)
|
|
279
|
+
tracer.startActiveSpan('handler', {}, inboundCtx, ...)
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
### ANTI: esquecer de propagar em call outbound
|
|
283
|
+
|
|
284
|
+
```ts
|
|
285
|
+
// PT-BR: BAD — outbound call sem traceparent — trace quebra no service B
|
|
286
|
+
await fetch('http://service-b/api', { body: ... })
|
|
287
|
+
|
|
288
|
+
// PT-BR: GOOD — injetar traceparent
|
|
289
|
+
const headers: Record<string, string> = {}
|
|
290
|
+
propagation.inject(context.active(), headers)
|
|
291
|
+
await fetch('http://service-b/api', { headers, body: ... })
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
### ANTI: trace só de RPCs, não de batch/queue
|
|
295
|
+
|
|
296
|
+
```ts
|
|
297
|
+
// PT-BR: BAD — producer/consumer não compartilham trace, debug fica fragmentado
|
|
298
|
+
await pgmqEnqueue('emails', payload) // sem trace context
|
|
299
|
+
// ... depois worker processa sem saber que veio do request X
|
|
300
|
+
|
|
301
|
+
// PT-BR: GOOD — propagar contexto via metadata da queue
|
|
302
|
+
const carrier = {}
|
|
303
|
+
propagation.inject(context.active(), carrier)
|
|
304
|
+
await pgmqEnqueue('emails', { ...payload, _trace_context: carrier })
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
### ANTI: span sem `end()`
|
|
308
|
+
|
|
309
|
+
```ts
|
|
310
|
+
// PT-BR: BAD — span fica aberto forever, duration_ms não calculado, memory leak
|
|
311
|
+
const span = tracer.startSpan('handler')
|
|
312
|
+
// ... handler logic
|
|
313
|
+
return result // PT-BR: ESQUECEU span.end()
|
|
314
|
+
|
|
315
|
+
// PT-BR: GOOD — sempre `try/finally`
|
|
316
|
+
const span = tracer.startSpan('handler')
|
|
317
|
+
try {
|
|
318
|
+
// ... logic
|
|
319
|
+
} finally {
|
|
320
|
+
span.end()
|
|
321
|
+
}
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
### ANTI: span hierarchy errada
|
|
325
|
+
|
|
326
|
+
```ts
|
|
327
|
+
// PT-BR: BAD — usar startSpan sem startActiveSpan, parent não é settado automático
|
|
328
|
+
const parent = tracer.startSpan('parent')
|
|
329
|
+
const child = tracer.startSpan('child') // PT-BR: parent_span_id ficou null
|
|
330
|
+
parent.end()
|
|
331
|
+
child.end()
|
|
332
|
+
|
|
333
|
+
// PT-BR: GOOD — startActiveSpan empurra contexto, child herda parent
|
|
334
|
+
tracer.startActiveSpan('parent', (parent) => {
|
|
335
|
+
tracer.startActiveSpan('child', (child) => {
|
|
336
|
+
// PT-BR: child.parent_span_id === parent.span_id
|
|
337
|
+
child.end()
|
|
338
|
+
})
|
|
339
|
+
parent.end()
|
|
340
|
+
})
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
## Verificação
|
|
344
|
+
|
|
345
|
+
1. **1 trace_id por request** — enviar 1 request, queryar `SELECT DISTINCT trace_id FROM spans WHERE request_id = X` → 1 resultado.
|
|
346
|
+
2. **Cross-service stitching** — request HTTP service A → service B → DB. Queryar `SELECT count(distinct service_name) FROM spans WHERE trace_id = X` → ≥ 3.
|
|
347
|
+
3. **Root span identificável** — `SELECT * FROM spans WHERE trace_id = X AND parent_span_id IS NULL` → 1 row (o root).
|
|
348
|
+
4. **Span hierarchy correta** — graficar via tool (Jaeger UI, Honeycomb, etc.) ou recursivo SQL — deve formar árvore válida (sem ciclos).
|
|
349
|
+
5. **Duration não-zero** — `SELECT min(duration_ms), max(duration_ms) FROM spans` — min ≥ 0, max razoável.
|
|
350
|
+
6. **Sampled flag respeitado** — verificar que se traceparent inbound = `01`, downstream também sample=true.
|
|
351
|
+
7. **Queue stitching funciona** — enqueue + consume → mesmo `trace_id` em ambos os spans.
|
|
352
|
+
|
|
353
|
+
---
|
|
354
|
+
|
|
355
|
+
## Ver também
|
|
356
|
+
|
|
357
|
+
- `kit/skills/_shared-observability/glossary.md` — W3C TraceContext, B3, span kinds
|
|
358
|
+
- `kit/skills/structured-events/SKILL.md` — atributos canônicos por span
|
|
359
|
+
- `kit/skills/opentelemetry-standard/SKILL.md` — SDK que faz extract/inject
|
|
360
|
+
- `kit/skills/telemetry-sampling/SKILL.md` *(Phase 34)* — head vs tail sampling decisão
|
|
361
|
+
|
|
362
|
+
*Material-fonte: Observability Engineering (O'Reilly, 2022) — Cap 6: "Stitching Events into Traces".*
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: eliminating-toil
|
|
3
|
+
description: Use ao identificar/eliminar toil — 6 critérios canônicos (manual, repetitivo, automatizável, tático, sem valor durável, escala linear), regra ≤ 50%, automação como invariante.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# SRE — Eliminating Toil
|
|
7
|
+
|
|
8
|
+
## Quando usar
|
|
9
|
+
|
|
10
|
+
LLM carrega esta skill ao auditar tarefas operacionais, classificar trabalho como toil/non-toil, ou propor automação. Trigger phrases:
|
|
11
|
+
|
|
12
|
+
- "toil", "trabalho operacional"
|
|
13
|
+
- "eliminar toil", "reduzir toil"
|
|
14
|
+
- "≤ 50% toil", "regra 50%"
|
|
15
|
+
- "automation", "automatizar tarefa repetitiva"
|
|
16
|
+
- "isso é toil ou overhead?"
|
|
17
|
+
- "Google SRE cap 5"
|
|
18
|
+
- "TOIL-AUDIT"
|
|
19
|
+
|
|
20
|
+
## Regras absolutas
|
|
21
|
+
|
|
22
|
+
- **Toil tem 6 critérios canônicos** — uma tarefa É toil se TODOS os 6 valem: (1) **Manual** — humano executa cada vez; (2) **Repetitivo** — você já fez isso 3+ vezes; (3) **Automatizável** — script/cron resolve sem julgamento humano; (4) **Tático** — reage a evento, não planeja; (5) **Sem valor durável** — não cria asset permanente; (6) **Escala linear** — mais users = mais trabalho. Se QUALQUER um dos 6 = não, NÃO é toil (é overhead ou grungy work).
|
|
23
|
+
- **Regra ≤ 50%** — SRE não pode gastar mais que 50% do tempo em toil; restante é engineering (automação, capacity planning, instrumentation, postmortems). Se medindo > 50% por 1+ trimestre, é red flag — peça ajuda à liderança.
|
|
24
|
+
- **Toil ≠ overhead** — reuniões, RH, planejamento de quarter, performance review são **overhead** — necessários, não-elimináveis, NÃO contam para a regra ≤ 50%. Confundir overhead com toil = sub-medir.
|
|
25
|
+
- **Toil ≠ grungy work** — refactor de código legado, security cleanup, DB rebuild para reduzir bloat são **grungy work** — necessários, têm valor durável, são engineering trabalho. NÃO contam como toil.
|
|
26
|
+
- **Automação é o objetivo, não o meio** — automatizar parcialmente (humano clica botão A, depois B, depois C) ainda é toil. Automação completa (cron + script + alert se falhar) elimina toil. Meias-medidas perpetuam.
|
|
27
|
+
- **Toil tax cresce com produto** — cada feature nova adiciona toil potencial: deploy manual, migration manual, feature flag rotation, customer-specific config. Prevenir > remediar — design feature considerando "como auto-operar isso?".
|
|
28
|
+
- **Quantificar toil em horas-pessoa** — "TOIL-AUDIT.md" deve ter coluna `hours_per_week_per_person` para cada item. Sem quantificação, "muito toil" é subjetivo e não-acionável.
|
|
29
|
+
- **Priorizar por (frequency × pain) / automation_effort** — P0 = alto frequency + alto pain + baixo effort. P2 = baixa frequency OU alto effort. Não automatizar tudo de uma vez — começar pelo P0.
|
|
30
|
+
|
|
31
|
+
## Patterns canônicos
|
|
32
|
+
|
|
33
|
+
### Pattern: decision tree para classificar trabalho
|
|
34
|
+
|
|
35
|
+
```text
|
|
36
|
+
Tarefa repetitiva detectada → aplicar 6 critérios canônicos:
|
|
37
|
+
|
|
38
|
+
1. Manual? (humano executa cada vez) ┐
|
|
39
|
+
2. Repetitiva? (já fiz isso 3+ vezes) │
|
|
40
|
+
3. Automatizável? (script/cron resolve sem julgamento) │── Se TODOS sim → TOIL
|
|
41
|
+
4. Tática? (reage a evento, não planeja) │ → automatizar / eliminar
|
|
42
|
+
5. Sem valor durável? (não cria asset permanente) │ → contar em ≤ 50% rule
|
|
43
|
+
6. Escala linear? (mais users = mais trabalho) ─┘
|
|
44
|
+
|
|
45
|
+
Se NÃO for toil mas repetitivo, classificar:
|
|
46
|
+
- OVERHEAD (reuniões, RH, planning) → não-eliminável; NÃO conta em ≤ 50%
|
|
47
|
+
- GRUNGY WORK (refactor, sec cleanup) → necessário, valor durável → projeto engineering
|
|
48
|
+
- PROJECT WORK (criar novo serviço) → engineering trabalho ≠ toil
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### Pattern: template `TOIL-AUDIT.md`
|
|
52
|
+
|
|
53
|
+
Formato canônico que `toil-auditor` (Phase 37) gera:
|
|
54
|
+
|
|
55
|
+
```markdown
|
|
56
|
+
# TOIL-AUDIT — <projeto> — <data>
|
|
57
|
+
|
|
58
|
+
## Métrica agregada
|
|
59
|
+
|
|
60
|
+
- Toil estimado: X.X horas-pessoa/semana (Y% do tempo do time)
|
|
61
|
+
- **Status vs ≤ 50% rule:** [GREEN: < 30%] | [YELLOW: 30-50%] | [RED: > 50%]
|
|
62
|
+
- Top 3 áreas: <lista>
|
|
63
|
+
|
|
64
|
+
## Itens identificados
|
|
65
|
+
|
|
66
|
+
| # | Item | Frequência | Hours/week | Pain (1-5) | Automation effort | Priority |
|
|
67
|
+
|---|------|------------|------------|------------|-------------------|----------|
|
|
68
|
+
| 1 | Reset DB seed manual antes de cada test run | 2×/dia | 1.5 h | 4 | M (3 dias) | P0 |
|
|
69
|
+
| 2 | Rotation de access_token de Edge Function | 1×/semana | 0.5 h | 2 | S (1 dia) | P1 |
|
|
70
|
+
| 3 | Rebuild de índice fts_search após batch import | 1×/mês | 0.5 h | 3 | M (2 dias) | P1 |
|
|
71
|
+
| 4 | Limpeza manual de orphan rows em audit_log | 1×/semana | 0.3 h | 1 | S (1 dia) | P2 |
|
|
72
|
+
|
|
73
|
+
## P0 (automatizar agora)
|
|
74
|
+
|
|
75
|
+
### Item 1: Reset DB seed manual
|
|
76
|
+
|
|
77
|
+
**Por que é toil:** atende 6 critérios canônicos (manual, repetitivo 2×/dia, automatizável via script + pg_cron, tática reativa, sem valor durável, escala com #devs).
|
|
78
|
+
|
|
79
|
+
**Automação proposta:** `make db-reset` que invoca `supabase db reset && pnpm run seed`. Adicionar pre-test hook em CI.
|
|
80
|
+
|
|
81
|
+
**Esforço estimado:** 3 dias (Med — script existe parcialmente, falta seed deterministic).
|
|
82
|
+
|
|
83
|
+
**Owner sugerido:** @dev-tools-team
|
|
84
|
+
|
|
85
|
+
## P1 / P2 (escalonar)
|
|
86
|
+
|
|
87
|
+
...
|
|
88
|
+
|
|
89
|
+
## Não-toil identificado
|
|
90
|
+
|
|
91
|
+
- **Overhead:** sprint planning (2h × semana × 5 pessoas = 10h/semana) — NÃO conta no ≤ 50%
|
|
92
|
+
- **Grungy work:** refactor de `legacy_orders_service` (8h × semana × 1 pessoa = 8h/semana) — projeto, não toil
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### Pattern: estágios de automação (níveis Google)
|
|
96
|
+
|
|
97
|
+
| Estágio | Descrição | Exemplo |
|
|
98
|
+
|---|---|---|
|
|
99
|
+
| **L0: Manual** | 100% humano | "Cada deploy: SSH no host, copy binary, kill+restart" |
|
|
100
|
+
| **L1: Documented** | Runbook escrito; humano segue passos | "Doc passo-a-passo de deploy em wiki" |
|
|
101
|
+
| **L2: Tooled** | Script executa passos; humano invoca | "`./deploy.sh prod`" |
|
|
102
|
+
| **L3: Self-service** | UI/CLI trigger; humano clica | "GitHub Actions deploy on PR merge" |
|
|
103
|
+
| **L4: Autonomous** | Sem humano; só fail-state intervenção | "Auto-rollback se SLO burn rate > 4 nos primeiros 5 min após deploy" |
|
|
104
|
+
|
|
105
|
+
Meta SRE é mover toda toil de L0/L1 para L3/L4. L2 é meio-passo aceitável quando L3+ requer investimento maior. **L1 (apenas runbook) é toil disfarçado** — runbook é manual com passo extra de "ler doc".
|
|
106
|
+
|
|
107
|
+
### Pattern: identificação de toil via git log + scripts
|
|
108
|
+
|
|
109
|
+
```bash
|
|
110
|
+
# PT-BR: scripts shell em runbooks/ ou docs/runbooks/
|
|
111
|
+
find . -name "*.sh" -path "*runbook*" -o -path "*ops*" | head -20
|
|
112
|
+
|
|
113
|
+
# PT-BR: "manual steps" em README/docs (heurística — frase canônica)
|
|
114
|
+
grep -rn "manually\|por favor\|run this\|every week\|cada semana" --include="*.md" .
|
|
115
|
+
|
|
116
|
+
# PT-BR: tarefas repetitivas via git log — commits de mesmo tipo
|
|
117
|
+
git log --since="3 months ago" --pretty=format:"%s" | sort | uniq -c | sort -rn | head -20
|
|
118
|
+
# Ex: "20× Re-run failed migration in prod" → TOIL candidato
|
|
119
|
+
# Ex: "15× Bump deploy-token" → TOIL candidato
|
|
120
|
+
|
|
121
|
+
# PT-BR: cron jobs já automatizados (saída esperada)
|
|
122
|
+
crontab -l 2>/dev/null
|
|
123
|
+
cat /etc/cron.d/* 2>/dev/null
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
### Pattern: "toil tax" — prevenir feature nascer com toil
|
|
127
|
+
|
|
128
|
+
```text
|
|
129
|
+
Antes de mergear PR de nova feature, perguntar:
|
|
130
|
+
|
|
131
|
+
1. "Como auto-operar isso em prod?" → instrumentação ODD
|
|
132
|
+
2. "Como auto-monitorar?" → 4 golden signals
|
|
133
|
+
3. "Como auto-recuperar de fail comum?" → retry, circuit breaker
|
|
134
|
+
4. "Como auto-rotacionar credenciais?" → vault + cron rotation
|
|
135
|
+
5. "Como auto-limpar dados históricos?" → retention policy + scheduled cleanup
|
|
136
|
+
6. "Como onboarding de novo cliente?" → self-service signup, não Slack ping
|
|
137
|
+
|
|
138
|
+
Se QUALQUER resposta = "humano fará isso" → toil tax. Bloqueie ou descontar do release budget.
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
## Anti-patterns
|
|
142
|
+
|
|
143
|
+
### ANTI: confundir overhead com toil
|
|
144
|
+
|
|
145
|
+
```text
|
|
146
|
+
ANTI: contar reuniões, RH, planning, performance review como toil — toda
|
|
147
|
+
atividade não-codificadora vira "toil" no audit.
|
|
148
|
+
|
|
149
|
+
PROBLEMA: métrica inflada (e.g., 60% "toil" falso); ações erradas — cortar
|
|
150
|
+
reunião não diminui toil real; equipe perde tempo em automação
|
|
151
|
+
de overhead (que é não-eliminável por design).
|
|
152
|
+
|
|
153
|
+
CERTO: overhead é categoria separada; ≤ 50% rule conta APENAS toil estrito
|
|
154
|
+
(6 critérios canônicos). Audit lista overhead em seção própria,
|
|
155
|
+
fora do total.
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
### ANTI: hero culture (toil mascara via heroísmo)
|
|
159
|
+
|
|
160
|
+
```text
|
|
161
|
+
ANTI: engineer fica 2h por dia executando deploys manuais e é "celebrado
|
|
162
|
+
por dedicação" / "salvador" — toil nunca aparece em métrica.
|
|
163
|
+
|
|
164
|
+
PROBLEMA: toil invisível para liderança; investimento em automação adiado
|
|
165
|
+
indefinidamente; engineer pede demissão; sucessor herda toil sem
|
|
166
|
+
context — incidente garantido. Ciclo se repete.
|
|
167
|
+
|
|
168
|
+
CERTO: TOIL-AUDIT trimestral mandatório; quantificar em hours/week por
|
|
169
|
+
pessoa; tornar visível em dashboards de produtividade. Heroísmo
|
|
170
|
+
sustentado = sinal de underinvestment, não de mérito.
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
### ANTI: documentar runbook em vez de automatizar
|
|
174
|
+
|
|
175
|
+
```text
|
|
176
|
+
ANTI: "Vamos só escrever um doc detalhado de como fazer isso passo-a-passo"
|
|
177
|
+
— runbook de 30 passos no wiki, sem script.
|
|
178
|
+
|
|
179
|
+
PROBLEMA: L1 (Documented) ainda é toil — humano lê doc, segue passos,
|
|
180
|
+
falha em algum, doc desatualiza em 3 meses; primeira pessoa que
|
|
181
|
+
segue após drift quebra prod; ninguém atualiza doc retroativamente.
|
|
182
|
+
|
|
183
|
+
CERTO: doc como passo intermediário (L1); meta é L3/L4 (autonomous);
|
|
184
|
+
marcar runbook com TODO de automação + owner + due date; sprint
|
|
185
|
+
seguinte transforma em script (L2) ou melhor.
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
### ANTI: automatizar parcialmente
|
|
189
|
+
|
|
190
|
+
```text
|
|
191
|
+
ANTI: script faz 3 dos 5 passos; humano completa os outros 2 — "execute
|
|
192
|
+
primeiro ./step1.sh, depois manualmente faça X em prod, depois
|
|
193
|
+
./step3.sh".
|
|
194
|
+
|
|
195
|
+
PROBLEMA: ainda é toil (humano envolvido); contexto-switch entre script e
|
|
196
|
+
humano dobra tempo total; script raramente atualizado por estar
|
|
197
|
+
"incompleto"; degrada para chain frágil que ninguém quer mexer.
|
|
198
|
+
|
|
199
|
+
CERTO: automação completa OU não automatizar — meias-medidas perpetuam.
|
|
200
|
+
Se faltam 2 passos manuais, gastar mais 1 dia para fechar o loop;
|
|
201
|
+
resultado é L3/L4 autônomo, não L1.5 frankenstein.
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
### ANTI: ignorar toil de baixa frequência
|
|
205
|
+
|
|
206
|
+
```text
|
|
207
|
+
ANTI: "Só faço isso 1× por trimestre, não vale automatizar" — descartar
|
|
208
|
+
tarefas raras do audit.
|
|
209
|
+
|
|
210
|
+
PROBLEMA: cumulative impact alto (10 tarefas trimestrais × 4 trimestres ×
|
|
211
|
+
30 min = 20h/ano); cada vez que retorna, pessoa esquece passos;
|
|
212
|
+
documentação envelhece entre execuções; DR exercises e migrations
|
|
213
|
+
raras são exatamente onde erro humano custa mais.
|
|
214
|
+
|
|
215
|
+
CERTO: priorizar por (frequency × pain) / effort; baixa frequência +
|
|
216
|
+
alto pain (e.g., DR exercise, schema migration crítica) = ainda
|
|
217
|
+
P1. Frequência baixa ≠ toil baixo — soma de raras é alta.
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
## Verificação
|
|
221
|
+
|
|
222
|
+
Antes de marcar audit de toil como completo:
|
|
223
|
+
|
|
224
|
+
1. **Aplicado os 6 critérios canônicos** — cada item passou pelo decision tree (manual, repetitivo, automatizável, tático, sem valor durável, escala linear)
|
|
225
|
+
2. **Quantificado em hours/week** — não "muito toil" mas "3.5h/week por pessoa"
|
|
226
|
+
3. **% do tempo do time** computado — comparado contra ≤ 50% rule
|
|
227
|
+
4. **Priorização por (frequency × pain) / effort** — P0/P1/P2 atribuído
|
|
228
|
+
5. **Owner nomeado** para cada item P0
|
|
229
|
+
6. **Overhead identificado separadamente** — não conta para ≤ 50%
|
|
230
|
+
7. **Grungy work identificado separadamente** — projeto engineering, não toil
|
|
231
|
+
8. **Pelo menos 1 item P0 escalonado** com automação proposta + esforço estimado
|
|
232
|
+
|
|
233
|
+
---
|
|
234
|
+
|
|
235
|
+
## Ver também
|
|
236
|
+
|
|
237
|
+
- [`_shared-sre/glossary.md`](../_shared-sre/glossary.md) — termos canônicos toil, overhead, grungy work, automation
|
|
238
|
+
- [`observability-maturity-model`](../observability-maturity-model/SKILL.md) (v1.9) — Capacidade 3 (Complexidade/Tech Debt) consome toil score
|
|
239
|
+
- [`production-readiness-review`](../production-readiness-review/SKILL.md) — PRR axis "Change Management" verifica deploy não é toil
|
|
240
|
+
- [`blameless-postmortems`](../blameless-postmortems/SKILL.md) — postmortems de toil-induced incidents alimentam audit
|
|
241
|
+
- [`sre-risk-management`](../sre-risk-management/SKILL.md) — toil reduz tempo para reduzir risk
|
|
242
|
+
|
|
243
|
+
*Material-fonte: Site Reliability Engineering — Beyer, Jones, Petoff, Murphy (Google/O'Reilly, 2016) — Cap 5: "Eliminating Toil".*
|